AudioFlinger.cpp revision fdb3c07db5d44535eb8c3ec46dc78ad8446c01eb
1/*
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include "Configuration.h"
23#include <dirent.h>
24#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
29#include <binder/IPCThreadState.h>
30#include <binder/IServiceManager.h>
31#include <utils/Log.h>
32#include <utils/Trace.h>
33#include <binder/Parcel.h>
34#include <utils/String16.h>
35#include <utils/threads.h>
36#include <utils/Atomic.h>
37
38#include <cutils/bitops.h>
39#include <cutils/properties.h>
40
41#include <system/audio.h>
42#include <hardware/audio.h>
43
44#include "AudioMixer.h"
45#include "AudioFlinger.h"
46#include "ServiceUtilities.h"
47
48#include <media/AudioResamplerPublic.h>
49
50#include <media/EffectsFactoryApi.h>
51#include <audio_effects/effect_visualizer.h>
52#include <audio_effects/effect_ns.h>
53#include <audio_effects/effect_aec.h>
54
55#include <audio_utils/primitives.h>
56
57#include <powermanager/PowerManager.h>
58
59#include <media/IMediaLogService.h>
60
61#include <media/nbaio/Pipe.h>
62#include <media/nbaio/PipeReader.h>
63#include <media/AudioParameter.h>
64#include <mediautils/BatteryNotifier.h>
65#include <private/android_filesystem_config.h>
66
67// ----------------------------------------------------------------------------
68
69// Note: the following macro is used for extremely verbose logging message.  In
70// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
71// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
72// are so verbose that we want to suppress them even when we have ALOG_ASSERT
73// turned on.  Do not uncomment the #def below unless you really know what you
74// are doing and want to see all of the extremely verbose messages.
75//#define VERY_VERY_VERBOSE_LOGGING
76#ifdef VERY_VERY_VERBOSE_LOGGING
77#define ALOGVV ALOGV
78#else
79#define ALOGVV(a...) do { } while(0)
80#endif
81
82namespace android {
83
84static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
85static const char kHardwareLockedString[] = "Hardware lock is taken\n";
86static const char kClientLockedString[] = "Client lock is taken\n";
87
88
89nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
90
91uint32_t AudioFlinger::mScreenState;
92
93#ifdef TEE_SINK
94bool AudioFlinger::mTeeSinkInputEnabled = false;
95bool AudioFlinger::mTeeSinkOutputEnabled = false;
96bool AudioFlinger::mTeeSinkTrackEnabled = false;
97
98size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
99size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
100size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
101#endif
102
103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
107// ----------------------------------------------------------------------------
108
109const char *formatToString(audio_format_t format) {
110    switch (audio_get_main_format(format)) {
111    case AUDIO_FORMAT_PCM:
112        switch (format) {
113        case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
114        case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
115        case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
116        case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
117        case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
118        case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
119        default:
120            break;
121        }
122        break;
123    case AUDIO_FORMAT_MP3: return "mp3";
124    case AUDIO_FORMAT_AMR_NB: return "amr-nb";
125    case AUDIO_FORMAT_AMR_WB: return "amr-wb";
126    case AUDIO_FORMAT_AAC: return "aac";
127    case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
128    case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
129    case AUDIO_FORMAT_VORBIS: return "vorbis";
130    case AUDIO_FORMAT_OPUS: return "opus";
131    case AUDIO_FORMAT_AC3: return "ac-3";
132    case AUDIO_FORMAT_E_AC3: return "e-ac-3";
133    case AUDIO_FORMAT_IEC61937: return "iec61937";
134    default:
135        break;
136    }
137    return "unknown";
138}
139
140static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
141{
142    const hw_module_t *mod;
143    int rc;
144
145    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
146    ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
147                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
148    if (rc) {
149        goto out;
150    }
151    rc = audio_hw_device_open(mod, dev);
152    ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
153                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
154    if (rc) {
155        goto out;
156    }
157    if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
158        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
159        rc = BAD_VALUE;
160        goto out;
161    }
162    return 0;
163
164out:
165    *dev = NULL;
166    return rc;
167}
168
169// ----------------------------------------------------------------------------
170
171AudioFlinger::AudioFlinger()
172    : BnAudioFlinger(),
173      mPrimaryHardwareDev(NULL),
174      mAudioHwDevs(NULL),
175      mHardwareStatus(AUDIO_HW_IDLE),
176      mMasterVolume(1.0f),
177      mMasterMute(false),
178      mNextUniqueId(1),
179      mMode(AUDIO_MODE_INVALID),
180      mBtNrecIsOff(false),
181      mIsLowRamDevice(true),
182      mIsDeviceTypeKnown(false),
183      mGlobalEffectEnableTime(0),
184      mSystemReady(false)
185{
186    getpid_cached = getpid();
187    // disable media.log until the service is reenabled, see b/26306954
188    const bool doLog = false; // property_get_bool("ro.test_harness", false);
189    if (doLog) {
190        mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
191                MemoryHeapBase::READ_ONLY);
192    }
193
194    // reset battery stats.
195    // if the audio service has crashed, battery stats could be left
196    // in bad state, reset the state upon service start.
197    BatteryNotifier::getInstance().noteResetAudio();
198
199#ifdef TEE_SINK
200    (void) property_get("ro.debuggable", value, "0");
201    int debuggable = atoi(value);
202    int teeEnabled = 0;
203    if (debuggable) {
204        (void) property_get("af.tee", value, "0");
205        teeEnabled = atoi(value);
206    }
207    // FIXME symbolic constants here
208    if (teeEnabled & 1) {
209        mTeeSinkInputEnabled = true;
210    }
211    if (teeEnabled & 2) {
212        mTeeSinkOutputEnabled = true;
213    }
214    if (teeEnabled & 4) {
215        mTeeSinkTrackEnabled = true;
216    }
217#endif
218}
219
220void AudioFlinger::onFirstRef()
221{
222    int rc = 0;
223
224    Mutex::Autolock _l(mLock);
225
226    /* TODO: move all this work into an Init() function */
227    char val_str[PROPERTY_VALUE_MAX] = { 0 };
228    if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
229        uint32_t int_val;
230        if (1 == sscanf(val_str, "%u", &int_val)) {
231            mStandbyTimeInNsecs = milliseconds(int_val);
232            ALOGI("Using %u mSec as standby time.", int_val);
233        } else {
234            mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
235            ALOGI("Using default %u mSec as standby time.",
236                    (uint32_t)(mStandbyTimeInNsecs / 1000000));
237        }
238    }
239
240    mPatchPanel = new PatchPanel(this);
241
242    mMode = AUDIO_MODE_NORMAL;
243}
244
245AudioFlinger::~AudioFlinger()
246{
247    while (!mRecordThreads.isEmpty()) {
248        // closeInput_nonvirtual() will remove specified entry from mRecordThreads
249        closeInput_nonvirtual(mRecordThreads.keyAt(0));
250    }
251    while (!mPlaybackThreads.isEmpty()) {
252        // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
253        closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
254    }
255
256    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
257        // no mHardwareLock needed, as there are no other references to this
258        audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
259        delete mAudioHwDevs.valueAt(i);
260    }
261
262    // Tell media.log service about any old writers that still need to be unregistered
263    if (mLogMemoryDealer != 0) {
264        sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
265        if (binder != 0) {
266            sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
267            for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
268                sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
269                mUnregisteredWriters.pop();
270                mediaLogService->unregisterWriter(iMemory);
271            }
272        }
273    }
274}
275
276static const char * const audio_interfaces[] = {
277    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278    AUDIO_HARDWARE_MODULE_ID_A2DP,
279    AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
283AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284        audio_module_handle_t module,
285        audio_devices_t devices)
286{
287    // if module is 0, the request comes from an old policy manager and we should load
288    // well known modules
289    if (module == 0) {
290        ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291        for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292            loadHwModule_l(audio_interfaces[i]);
293        }
294        // then try to find a module supporting the requested device.
295        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296            AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297            audio_hw_device_t *dev = audioHwDevice->hwDevice();
298            if ((dev->get_supported_devices != NULL) &&
299                    (dev->get_supported_devices(dev) & devices) == devices)
300                return audioHwDevice;
301        }
302    } else {
303        // check a match for the requested module handle
304        AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305        if (audioHwDevice != NULL) {
306            return audioHwDevice;
307        }
308    }
309
310    return NULL;
311}
312
313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
314{
315    const size_t SIZE = 256;
316    char buffer[SIZE];
317    String8 result;
318
319    result.append("Clients:\n");
320    for (size_t i = 0; i < mClients.size(); ++i) {
321        sp<Client> client = mClients.valueAt(i).promote();
322        if (client != 0) {
323            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
324            result.append(buffer);
325        }
326    }
327
328    result.append("Notification Clients:\n");
329    for (size_t i = 0; i < mNotificationClients.size(); ++i) {
330        snprintf(buffer, SIZE, "  pid: %d\n", mNotificationClients.keyAt(i));
331        result.append(buffer);
332    }
333
334    result.append("Global session refs:\n");
335    result.append("  session   pid count\n");
336    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
337        AudioSessionRef *r = mAudioSessionRefs[i];
338        snprintf(buffer, SIZE, "  %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
339        result.append(buffer);
340    }
341    write(fd, result.string(), result.size());
342}
343
344
345void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
346{
347    const size_t SIZE = 256;
348    char buffer[SIZE];
349    String8 result;
350    hardware_call_state hardwareStatus = mHardwareStatus;
351
352    snprintf(buffer, SIZE, "Hardware status: %d\n"
353                           "Standby Time mSec: %u\n",
354                            hardwareStatus,
355                            (uint32_t)(mStandbyTimeInNsecs / 1000000));
356    result.append(buffer);
357    write(fd, result.string(), result.size());
358}
359
360void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
361{
362    const size_t SIZE = 256;
363    char buffer[SIZE];
364    String8 result;
365    snprintf(buffer, SIZE, "Permission Denial: "
366            "can't dump AudioFlinger from pid=%d, uid=%d\n",
367            IPCThreadState::self()->getCallingPid(),
368            IPCThreadState::self()->getCallingUid());
369    result.append(buffer);
370    write(fd, result.string(), result.size());
371}
372
373bool AudioFlinger::dumpTryLock(Mutex& mutex)
374{
375    bool locked = false;
376    for (int i = 0; i < kDumpLockRetries; ++i) {
377        if (mutex.tryLock() == NO_ERROR) {
378            locked = true;
379            break;
380        }
381        usleep(kDumpLockSleepUs);
382    }
383    return locked;
384}
385
386status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
387{
388    if (!dumpAllowed()) {
389        dumpPermissionDenial(fd, args);
390    } else {
391        // get state of hardware lock
392        bool hardwareLocked = dumpTryLock(mHardwareLock);
393        if (!hardwareLocked) {
394            String8 result(kHardwareLockedString);
395            write(fd, result.string(), result.size());
396        } else {
397            mHardwareLock.unlock();
398        }
399
400        bool locked = dumpTryLock(mLock);
401
402        // failed to lock - AudioFlinger is probably deadlocked
403        if (!locked) {
404            String8 result(kDeadlockedString);
405            write(fd, result.string(), result.size());
406        }
407
408        bool clientLocked = dumpTryLock(mClientLock);
409        if (!clientLocked) {
410            String8 result(kClientLockedString);
411            write(fd, result.string(), result.size());
412        }
413
414        EffectDumpEffects(fd);
415
416        dumpClients(fd, args);
417        if (clientLocked) {
418            mClientLock.unlock();
419        }
420
421        dumpInternals(fd, args);
422
423        // dump playback threads
424        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
425            mPlaybackThreads.valueAt(i)->dump(fd, args);
426        }
427
428        // dump record threads
429        for (size_t i = 0; i < mRecordThreads.size(); i++) {
430            mRecordThreads.valueAt(i)->dump(fd, args);
431        }
432
433        // dump orphan effect chains
434        if (mOrphanEffectChains.size() != 0) {
435            write(fd, "  Orphan Effect Chains\n", strlen("  Orphan Effect Chains\n"));
436            for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
437                mOrphanEffectChains.valueAt(i)->dump(fd, args);
438            }
439        }
440        // dump all hardware devs
441        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
442            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
443            dev->dump(dev, fd);
444        }
445
446#ifdef TEE_SINK
447        // dump the serially shared record tee sink
448        if (mRecordTeeSource != 0) {
449            dumpTee(fd, mRecordTeeSource);
450        }
451#endif
452
453        if (locked) {
454            mLock.unlock();
455        }
456
457        // append a copy of media.log here by forwarding fd to it, but don't attempt
458        // to lookup the service if it's not running, as it will block for a second
459        if (mLogMemoryDealer != 0) {
460            sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
461            if (binder != 0) {
462                dprintf(fd, "\nmedia.log:\n");
463                Vector<String16> args;
464                binder->dump(fd, args);
465            }
466        }
467    }
468    return NO_ERROR;
469}
470
471sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
472{
473    Mutex::Autolock _cl(mClientLock);
474    // If pid is already in the mClients wp<> map, then use that entry
475    // (for which promote() is always != 0), otherwise create a new entry and Client.
476    sp<Client> client = mClients.valueFor(pid).promote();
477    if (client == 0) {
478        client = new Client(this, pid);
479        mClients.add(pid, client);
480    }
481
482    return client;
483}
484
485sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
486{
487    // If there is no memory allocated for logs, return a dummy writer that does nothing
488    if (mLogMemoryDealer == 0) {
489        return new NBLog::Writer();
490    }
491    sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
492    // Similarly if we can't contact the media.log service, also return a dummy writer
493    if (binder == 0) {
494        return new NBLog::Writer();
495    }
496    sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
497    sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
498    // If allocation fails, consult the vector of previously unregistered writers
499    // and garbage-collect one or more them until an allocation succeeds
500    if (shared == 0) {
501        Mutex::Autolock _l(mUnregisteredWritersLock);
502        for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
503            {
504                // Pick the oldest stale writer to garbage-collect
505                sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
506                mUnregisteredWriters.removeAt(0);
507                mediaLogService->unregisterWriter(iMemory);
508                // Now the media.log remote reference to IMemory is gone.  When our last local
509                // reference to IMemory also drops to zero at end of this block,
510                // the IMemory destructor will deallocate the region from mLogMemoryDealer.
511            }
512            // Re-attempt the allocation
513            shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
514            if (shared != 0) {
515                goto success;
516            }
517        }
518        // Even after garbage-collecting all old writers, there is still not enough memory,
519        // so return a dummy writer
520        return new NBLog::Writer();
521    }
522success:
523    mediaLogService->registerWriter(shared, size, name);
524    return new NBLog::Writer(size, shared);
525}
526
527void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
528{
529    if (writer == 0) {
530        return;
531    }
532    sp<IMemory> iMemory(writer->getIMemory());
533    if (iMemory == 0) {
534        return;
535    }
536    // Rather than removing the writer immediately, append it to a queue of old writers to
537    // be garbage-collected later.  This allows us to continue to view old logs for a while.
538    Mutex::Autolock _l(mUnregisteredWritersLock);
539    mUnregisteredWriters.push(writer);
540}
541
542// IAudioFlinger interface
543
544
545sp<IAudioTrack> AudioFlinger::createTrack(
546        audio_stream_type_t streamType,
547        uint32_t sampleRate,
548        audio_format_t format,
549        audio_channel_mask_t channelMask,
550        size_t *frameCount,
551        IAudioFlinger::track_flags_t *flags,
552        const sp<IMemory>& sharedBuffer,
553        audio_io_handle_t output,
554        pid_t tid,
555        int *sessionId,
556        int clientUid,
557        status_t *status)
558{
559    sp<PlaybackThread::Track> track;
560    sp<TrackHandle> trackHandle;
561    sp<Client> client;
562    status_t lStatus;
563    int lSessionId;
564
565    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
566    // but if someone uses binder directly they could bypass that and cause us to crash
567    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
568        ALOGE("createTrack() invalid stream type %d", streamType);
569        lStatus = BAD_VALUE;
570        goto Exit;
571    }
572
573    // further sample rate checks are performed by createTrack_l() depending on the thread type
574    if (sampleRate == 0) {
575        ALOGE("createTrack() invalid sample rate %u", sampleRate);
576        lStatus = BAD_VALUE;
577        goto Exit;
578    }
579
580    // further channel mask checks are performed by createTrack_l() depending on the thread type
581    if (!audio_is_output_channel(channelMask)) {
582        ALOGE("createTrack() invalid channel mask %#x", channelMask);
583        lStatus = BAD_VALUE;
584        goto Exit;
585    }
586
587    // further format checks are performed by createTrack_l() depending on the thread type
588    if (!audio_is_valid_format(format)) {
589        ALOGE("createTrack() invalid format %#x", format);
590        lStatus = BAD_VALUE;
591        goto Exit;
592    }
593
594    if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
595        ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
596        lStatus = BAD_VALUE;
597        goto Exit;
598    }
599
600    {
601        Mutex::Autolock _l(mLock);
602        PlaybackThread *thread = checkPlaybackThread_l(output);
603        if (thread == NULL) {
604            ALOGE("no playback thread found for output handle %d", output);
605            lStatus = BAD_VALUE;
606            goto Exit;
607        }
608
609        pid_t pid = IPCThreadState::self()->getCallingPid();
610        client = registerPid(pid);
611
612        PlaybackThread *effectThread = NULL;
613        if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
614            lSessionId = *sessionId;
615            // check if an effect chain with the same session ID is present on another
616            // output thread and move it here.
617            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
618                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
619                if (mPlaybackThreads.keyAt(i) != output) {
620                    uint32_t sessions = t->hasAudioSession(lSessionId);
621                    if (sessions & PlaybackThread::EFFECT_SESSION) {
622                        effectThread = t.get();
623                        break;
624                    }
625                }
626            }
627        } else {
628            // if no audio session id is provided, create one here
629            lSessionId = nextUniqueId();
630            if (sessionId != NULL) {
631                *sessionId = lSessionId;
632            }
633        }
634        ALOGV("createTrack() lSessionId: %d", lSessionId);
635
636        track = thread->createTrack_l(client, streamType, sampleRate, format,
637                channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
638        LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
639        // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
640
641        // move effect chain to this output thread if an effect on same session was waiting
642        // for a track to be created
643        if (lStatus == NO_ERROR && effectThread != NULL) {
644            // no risk of deadlock because AudioFlinger::mLock is held
645            Mutex::Autolock _dl(thread->mLock);
646            Mutex::Autolock _sl(effectThread->mLock);
647            moveEffectChain_l(lSessionId, effectThread, thread, true);
648        }
649
650        // Look for sync events awaiting for a session to be used.
651        for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
652            if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
653                if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
654                    if (lStatus == NO_ERROR) {
655                        (void) track->setSyncEvent(mPendingSyncEvents[i]);
656                    } else {
657                        mPendingSyncEvents[i]->cancel();
658                    }
659                    mPendingSyncEvents.removeAt(i);
660                    i--;
661                }
662            }
663        }
664
665        setAudioHwSyncForSession_l(thread, (audio_session_t)lSessionId);
666    }
667
668    if (lStatus != NO_ERROR) {
669        // remove local strong reference to Client before deleting the Track so that the
670        // Client destructor is called by the TrackBase destructor with mClientLock held
671        // Don't hold mClientLock when releasing the reference on the track as the
672        // destructor will acquire it.
673        {
674            Mutex::Autolock _cl(mClientLock);
675            client.clear();
676        }
677        track.clear();
678        goto Exit;
679    }
680
681    // return handle to client
682    trackHandle = new TrackHandle(track);
683
684Exit:
685    *status = lStatus;
686    return trackHandle;
687}
688
689uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
690{
691    Mutex::Autolock _l(mLock);
692    PlaybackThread *thread = checkPlaybackThread_l(output);
693    if (thread == NULL) {
694        ALOGW("sampleRate() unknown thread %d", output);
695        return 0;
696    }
697    return thread->sampleRate();
698}
699
700audio_format_t AudioFlinger::format(audio_io_handle_t output) const
701{
702    Mutex::Autolock _l(mLock);
703    PlaybackThread *thread = checkPlaybackThread_l(output);
704    if (thread == NULL) {
705        ALOGW("format() unknown thread %d", output);
706        return AUDIO_FORMAT_INVALID;
707    }
708    return thread->format();
709}
710
711size_t AudioFlinger::frameCount(audio_io_handle_t output) const
712{
713    Mutex::Autolock _l(mLock);
714    PlaybackThread *thread = checkPlaybackThread_l(output);
715    if (thread == NULL) {
716        ALOGW("frameCount() unknown thread %d", output);
717        return 0;
718    }
719    // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
720    //       should examine all callers and fix them to handle smaller counts
721    return thread->frameCount();
722}
723
724uint32_t AudioFlinger::latency(audio_io_handle_t output) const
725{
726    Mutex::Autolock _l(mLock);
727    PlaybackThread *thread = checkPlaybackThread_l(output);
728    if (thread == NULL) {
729        ALOGW("latency(): no playback thread found for output handle %d", output);
730        return 0;
731    }
732    return thread->latency();
733}
734
735status_t AudioFlinger::setMasterVolume(float value)
736{
737    status_t ret = initCheck();
738    if (ret != NO_ERROR) {
739        return ret;
740    }
741
742    // check calling permissions
743    if (!settingsAllowed()) {
744        return PERMISSION_DENIED;
745    }
746
747    Mutex::Autolock _l(mLock);
748    mMasterVolume = value;
749
750    // Set master volume in the HALs which support it.
751    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
752        AutoMutex lock(mHardwareLock);
753        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
754
755        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
756        if (dev->canSetMasterVolume()) {
757            dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
758        }
759        mHardwareStatus = AUDIO_HW_IDLE;
760    }
761
762    // Now set the master volume in each playback thread.  Playback threads
763    // assigned to HALs which do not have master volume support will apply
764    // master volume during the mix operation.  Threads with HALs which do
765    // support master volume will simply ignore the setting.
766    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
767        if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
768            continue;
769        }
770        mPlaybackThreads.valueAt(i)->setMasterVolume(value);
771    }
772
773    return NO_ERROR;
774}
775
776status_t AudioFlinger::setMode(audio_mode_t mode)
777{
778    status_t ret = initCheck();
779    if (ret != NO_ERROR) {
780        return ret;
781    }
782
783    // check calling permissions
784    if (!settingsAllowed()) {
785        return PERMISSION_DENIED;
786    }
787    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
788        ALOGW("Illegal value: setMode(%d)", mode);
789        return BAD_VALUE;
790    }
791
792    { // scope for the lock
793        AutoMutex lock(mHardwareLock);
794        audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
795        mHardwareStatus = AUDIO_HW_SET_MODE;
796        ret = dev->set_mode(dev, mode);
797        mHardwareStatus = AUDIO_HW_IDLE;
798    }
799
800    if (NO_ERROR == ret) {
801        Mutex::Autolock _l(mLock);
802        mMode = mode;
803        for (size_t i = 0; i < mPlaybackThreads.size(); i++)
804            mPlaybackThreads.valueAt(i)->setMode(mode);
805    }
806
807    return ret;
808}
809
810status_t AudioFlinger::setMicMute(bool state)
811{
812    status_t ret = initCheck();
813    if (ret != NO_ERROR) {
814        return ret;
815    }
816
817    // check calling permissions
818    if (!settingsAllowed()) {
819        return PERMISSION_DENIED;
820    }
821
822    AutoMutex lock(mHardwareLock);
823    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
824    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
825        audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
826        status_t result = dev->set_mic_mute(dev, state);
827        if (result != NO_ERROR) {
828            ret = result;
829        }
830    }
831    mHardwareStatus = AUDIO_HW_IDLE;
832    return ret;
833}
834
835bool AudioFlinger::getMicMute() const
836{
837    status_t ret = initCheck();
838    if (ret != NO_ERROR) {
839        return false;
840    }
841    bool mute = true;
842    bool state = AUDIO_MODE_INVALID;
843    AutoMutex lock(mHardwareLock);
844    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
845    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
846        audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
847        status_t result = dev->get_mic_mute(dev, &state);
848        if (result == NO_ERROR) {
849            mute = mute && state;
850        }
851    }
852    mHardwareStatus = AUDIO_HW_IDLE;
853
854    return mute;
855}
856
857status_t AudioFlinger::setMasterMute(bool muted)
858{
859    status_t ret = initCheck();
860    if (ret != NO_ERROR) {
861        return ret;
862    }
863
864    // check calling permissions
865    if (!settingsAllowed()) {
866        return PERMISSION_DENIED;
867    }
868
869    Mutex::Autolock _l(mLock);
870    mMasterMute = muted;
871
872    // Set master mute in the HALs which support it.
873    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
874        AutoMutex lock(mHardwareLock);
875        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
876
877        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
878        if (dev->canSetMasterMute()) {
879            dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
880        }
881        mHardwareStatus = AUDIO_HW_IDLE;
882    }
883
884    // Now set the master mute in each playback thread.  Playback threads
885    // assigned to HALs which do not have master mute support will apply master
886    // mute during the mix operation.  Threads with HALs which do support master
887    // mute will simply ignore the setting.
888    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
889        if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
890            continue;
891        }
892        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
893    }
894
895    return NO_ERROR;
896}
897
898float AudioFlinger::masterVolume() const
899{
900    Mutex::Autolock _l(mLock);
901    return masterVolume_l();
902}
903
904bool AudioFlinger::masterMute() const
905{
906    Mutex::Autolock _l(mLock);
907    return masterMute_l();
908}
909
910float AudioFlinger::masterVolume_l() const
911{
912    return mMasterVolume;
913}
914
915bool AudioFlinger::masterMute_l() const
916{
917    return mMasterMute;
918}
919
920status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
921{
922    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
923        ALOGW("setStreamVolume() invalid stream %d", stream);
924        return BAD_VALUE;
925    }
926    pid_t caller = IPCThreadState::self()->getCallingPid();
927    if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
928        ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
929        return PERMISSION_DENIED;
930    }
931
932    return NO_ERROR;
933}
934
935status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
936        audio_io_handle_t output)
937{
938    // check calling permissions
939    if (!settingsAllowed()) {
940        return PERMISSION_DENIED;
941    }
942
943    status_t status = checkStreamType(stream);
944    if (status != NO_ERROR) {
945        return status;
946    }
947    ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
948
949    AutoMutex lock(mLock);
950    PlaybackThread *thread = NULL;
951    if (output != AUDIO_IO_HANDLE_NONE) {
952        thread = checkPlaybackThread_l(output);
953        if (thread == NULL) {
954            return BAD_VALUE;
955        }
956    }
957
958    mStreamTypes[stream].volume = value;
959
960    if (thread == NULL) {
961        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
962            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
963        }
964    } else {
965        thread->setStreamVolume(stream, value);
966    }
967
968    return NO_ERROR;
969}
970
971status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
972{
973    // check calling permissions
974    if (!settingsAllowed()) {
975        return PERMISSION_DENIED;
976    }
977
978    status_t status = checkStreamType(stream);
979    if (status != NO_ERROR) {
980        return status;
981    }
982    ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
983
984    if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
985        ALOGE("setStreamMute() invalid stream %d", stream);
986        return BAD_VALUE;
987    }
988
989    AutoMutex lock(mLock);
990    mStreamTypes[stream].mute = muted;
991    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
992        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
993
994    return NO_ERROR;
995}
996
997float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
998{
999    status_t status = checkStreamType(stream);
1000    if (status != NO_ERROR) {
1001        return 0.0f;
1002    }
1003
1004    AutoMutex lock(mLock);
1005    float volume;
1006    if (output != AUDIO_IO_HANDLE_NONE) {
1007        PlaybackThread *thread = checkPlaybackThread_l(output);
1008        if (thread == NULL) {
1009            return 0.0f;
1010        }
1011        volume = thread->streamVolume(stream);
1012    } else {
1013        volume = streamVolume_l(stream);
1014    }
1015
1016    return volume;
1017}
1018
1019bool AudioFlinger::streamMute(audio_stream_type_t stream) const
1020{
1021    status_t status = checkStreamType(stream);
1022    if (status != NO_ERROR) {
1023        return true;
1024    }
1025
1026    AutoMutex lock(mLock);
1027    return streamMute_l(stream);
1028}
1029
1030
1031void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1032{
1033    for (size_t i = 0; i < mRecordThreads.size(); i++) {
1034        mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1035    }
1036}
1037
1038status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
1039{
1040    ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1041            ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
1042
1043    // check calling permissions
1044    if (!settingsAllowed()) {
1045        return PERMISSION_DENIED;
1046    }
1047
1048    // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1049    if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1050        Mutex::Autolock _l(mLock);
1051        status_t final_result = NO_ERROR;
1052        {
1053            AutoMutex lock(mHardwareLock);
1054            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1055            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1056                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1057                status_t result = dev->set_parameters(dev, keyValuePairs.string());
1058                final_result = result ?: final_result;
1059            }
1060            mHardwareStatus = AUDIO_HW_IDLE;
1061        }
1062        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1063        AudioParameter param = AudioParameter(keyValuePairs);
1064        String8 value;
1065        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
1066            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1067            if (mBtNrecIsOff != btNrecIsOff) {
1068                for (size_t i = 0; i < mRecordThreads.size(); i++) {
1069                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
1070                    audio_devices_t device = thread->inDevice();
1071                    bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1072                    // collect all of the thread's session IDs
1073                    KeyedVector<int, bool> ids = thread->sessionIds();
1074                    // suspend effects associated with those session IDs
1075                    for (size_t j = 0; j < ids.size(); ++j) {
1076                        int sessionId = ids.keyAt(j);
1077                        thread->setEffectSuspended(FX_IID_AEC,
1078                                                   suspend,
1079                                                   sessionId);
1080                        thread->setEffectSuspended(FX_IID_NS,
1081                                                   suspend,
1082                                                   sessionId);
1083                    }
1084                }
1085                mBtNrecIsOff = btNrecIsOff;
1086            }
1087        }
1088        String8 screenState;
1089        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1090            bool isOff = screenState == "off";
1091            if (isOff != (AudioFlinger::mScreenState & 1)) {
1092                AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
1093            }
1094        }
1095        return final_result;
1096    }
1097
1098    // hold a strong ref on thread in case closeOutput() or closeInput() is called
1099    // and the thread is exited once the lock is released
1100    sp<ThreadBase> thread;
1101    {
1102        Mutex::Autolock _l(mLock);
1103        thread = checkPlaybackThread_l(ioHandle);
1104        if (thread == 0) {
1105            thread = checkRecordThread_l(ioHandle);
1106        } else if (thread == primaryPlaybackThread_l()) {
1107            // indicate output device change to all input threads for pre processing
1108            AudioParameter param = AudioParameter(keyValuePairs);
1109            int value;
1110            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1111                    (value != 0)) {
1112                broacastParametersToRecordThreads_l(keyValuePairs);
1113            }
1114        }
1115    }
1116    if (thread != 0) {
1117        return thread->setParameters(keyValuePairs);
1118    }
1119    return BAD_VALUE;
1120}
1121
1122String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
1123{
1124    ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1125            ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
1126
1127    Mutex::Autolock _l(mLock);
1128
1129    if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1130        String8 out_s8;
1131
1132        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1133            char *s;
1134            {
1135            AutoMutex lock(mHardwareLock);
1136            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
1137            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1138            s = dev->get_parameters(dev, keys.string());
1139            mHardwareStatus = AUDIO_HW_IDLE;
1140            }
1141            out_s8 += String8(s ? s : "");
1142            free(s);
1143        }
1144        return out_s8;
1145    }
1146
1147    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1148    if (playbackThread != NULL) {
1149        return playbackThread->getParameters(keys);
1150    }
1151    RecordThread *recordThread = checkRecordThread_l(ioHandle);
1152    if (recordThread != NULL) {
1153        return recordThread->getParameters(keys);
1154    }
1155    return String8("");
1156}
1157
1158size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1159        audio_channel_mask_t channelMask) const
1160{
1161    status_t ret = initCheck();
1162    if (ret != NO_ERROR) {
1163        return 0;
1164    }
1165    if ((sampleRate == 0) ||
1166            !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
1167            !audio_is_input_channel(channelMask)) {
1168        return 0;
1169    }
1170
1171    AutoMutex lock(mHardwareLock);
1172    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
1173    audio_config_t config, proposed;
1174    memset(&proposed, 0, sizeof(proposed));
1175    proposed.sample_rate = sampleRate;
1176    proposed.channel_mask = channelMask;
1177    proposed.format = format;
1178
1179    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1180    size_t frames;
1181    for (;;) {
1182        // Note: config is currently a const parameter for get_input_buffer_size()
1183        // but we use a copy from proposed in case config changes from the call.
1184        config = proposed;
1185        frames = dev->get_input_buffer_size(dev, &config);
1186        if (frames != 0) {
1187            break; // hal success, config is the result
1188        }
1189        // change one parameter of the configuration each iteration to a more "common" value
1190        // to see if the device will support it.
1191        if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1192            proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1193        } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1194            proposed.sample_rate = 44100;           // legacy AudioRecord.java. TODO: Query hw?
1195        } else {
1196            ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1197                    "format %#x, channelMask 0x%X",
1198                    sampleRate, format, channelMask);
1199            break; // retries failed, break out of loop with frames == 0.
1200        }
1201    }
1202    mHardwareStatus = AUDIO_HW_IDLE;
1203    if (frames > 0 && config.sample_rate != sampleRate) {
1204        frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1205    }
1206    return frames; // may be converted to bytes at the Java level.
1207}
1208
1209uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
1210{
1211    Mutex::Autolock _l(mLock);
1212
1213    RecordThread *recordThread = checkRecordThread_l(ioHandle);
1214    if (recordThread != NULL) {
1215        return recordThread->getInputFramesLost();
1216    }
1217    return 0;
1218}
1219
1220status_t AudioFlinger::setVoiceVolume(float value)
1221{
1222    status_t ret = initCheck();
1223    if (ret != NO_ERROR) {
1224        return ret;
1225    }
1226
1227    // check calling permissions
1228    if (!settingsAllowed()) {
1229        return PERMISSION_DENIED;
1230    }
1231
1232    AutoMutex lock(mHardwareLock);
1233    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1234    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
1235    ret = dev->set_voice_volume(dev, value);
1236    mHardwareStatus = AUDIO_HW_IDLE;
1237
1238    return ret;
1239}
1240
1241status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1242        audio_io_handle_t output) const
1243{
1244    status_t status;
1245
1246    Mutex::Autolock _l(mLock);
1247
1248    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1249    if (playbackThread != NULL) {
1250        return playbackThread->getRenderPosition(halFrames, dspFrames);
1251    }
1252
1253    return BAD_VALUE;
1254}
1255
1256void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1257{
1258    Mutex::Autolock _l(mLock);
1259    if (client == 0) {
1260        return;
1261    }
1262    pid_t pid = IPCThreadState::self()->getCallingPid();
1263    {
1264        Mutex::Autolock _cl(mClientLock);
1265        if (mNotificationClients.indexOfKey(pid) < 0) {
1266            sp<NotificationClient> notificationClient = new NotificationClient(this,
1267                                                                                client,
1268                                                                                pid);
1269            ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1270
1271            mNotificationClients.add(pid, notificationClient);
1272
1273            sp<IBinder> binder = IInterface::asBinder(client);
1274            binder->linkToDeath(notificationClient);
1275        }
1276    }
1277
1278    // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
1279    // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
1280    // the config change is always sent from playback or record threads to avoid deadlock
1281    // with AudioSystem::gLock
1282    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1283        mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1284    }
1285
1286    for (size_t i = 0; i < mRecordThreads.size(); i++) {
1287        mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
1288    }
1289}
1290
1291void AudioFlinger::removeNotificationClient(pid_t pid)
1292{
1293    Mutex::Autolock _l(mLock);
1294    {
1295        Mutex::Autolock _cl(mClientLock);
1296        mNotificationClients.removeItem(pid);
1297    }
1298
1299    ALOGV("%d died, releasing its sessions", pid);
1300    size_t num = mAudioSessionRefs.size();
1301    bool removed = false;
1302    for (size_t i = 0; i< num; ) {
1303        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1304        ALOGV(" pid %d @ %d", ref->mPid, i);
1305        if (ref->mPid == pid) {
1306            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1307            mAudioSessionRefs.removeAt(i);
1308            delete ref;
1309            removed = true;
1310            num--;
1311        } else {
1312            i++;
1313        }
1314    }
1315    if (removed) {
1316        purgeStaleEffects_l();
1317    }
1318}
1319
1320void AudioFlinger::ioConfigChanged(audio_io_config_event event,
1321                                   const sp<AudioIoDescriptor>& ioDesc,
1322                                   pid_t pid)
1323{
1324    Mutex::Autolock _l(mClientLock);
1325    size_t size = mNotificationClients.size();
1326    for (size_t i = 0; i < size; i++) {
1327        if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1328            mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1329        }
1330    }
1331}
1332
1333// removeClient_l() must be called with AudioFlinger::mClientLock held
1334void AudioFlinger::removeClient_l(pid_t pid)
1335{
1336    ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1337            IPCThreadState::self()->getCallingPid());
1338    mClients.removeItem(pid);
1339}
1340
1341// getEffectThread_l() must be called with AudioFlinger::mLock held
1342sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1343{
1344    sp<PlaybackThread> thread;
1345
1346    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1347        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1348            ALOG_ASSERT(thread == 0);
1349            thread = mPlaybackThreads.valueAt(i);
1350        }
1351    }
1352
1353    return thread;
1354}
1355
1356
1357
1358// ----------------------------------------------------------------------------
1359
1360AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1361    :   RefBase(),
1362        mAudioFlinger(audioFlinger),
1363        mPid(pid)
1364{
1365    size_t heapSize = kClientSharedHeapSizeBytes;
1366    // Increase heap size on non low ram devices to limit risk of reconnection failure for
1367    // invalidated tracks
1368    if (!audioFlinger->isLowRamDevice()) {
1369        heapSize *= kClientSharedHeapSizeMultiplier;
1370    }
1371    mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
1372}
1373
1374// Client destructor must be called with AudioFlinger::mClientLock held
1375AudioFlinger::Client::~Client()
1376{
1377    mAudioFlinger->removeClient_l(mPid);
1378}
1379
1380sp<MemoryDealer> AudioFlinger::Client::heap() const
1381{
1382    return mMemoryDealer;
1383}
1384
1385// ----------------------------------------------------------------------------
1386
1387AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1388                                                     const sp<IAudioFlingerClient>& client,
1389                                                     pid_t pid)
1390    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1391{
1392}
1393
1394AudioFlinger::NotificationClient::~NotificationClient()
1395{
1396}
1397
1398void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
1399{
1400    sp<NotificationClient> keep(this);
1401    mAudioFlinger->removeNotificationClient(mPid);
1402}
1403
1404
1405// ----------------------------------------------------------------------------
1406
1407static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1408    return audio_is_remote_submix_device(inDevice);
1409}
1410
1411sp<IAudioRecord> AudioFlinger::openRecord(
1412        audio_io_handle_t input,
1413        uint32_t sampleRate,
1414        audio_format_t format,
1415        audio_channel_mask_t channelMask,
1416        const String16& opPackageName,
1417        size_t *frameCount,
1418        IAudioFlinger::track_flags_t *flags,
1419        pid_t tid,
1420        int clientUid,
1421        int *sessionId,
1422        size_t *notificationFrames,
1423        sp<IMemory>& cblk,
1424        sp<IMemory>& buffers,
1425        status_t *status)
1426{
1427    sp<RecordThread::RecordTrack> recordTrack;
1428    sp<RecordHandle> recordHandle;
1429    sp<Client> client;
1430    status_t lStatus;
1431    int lSessionId;
1432
1433    cblk.clear();
1434    buffers.clear();
1435
1436    const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1437    if (!isTrustedCallingUid(callingUid)) {
1438        ALOGW_IF((uid_t)clientUid != callingUid,
1439                "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1440        clientUid = callingUid;
1441    }
1442
1443    // check calling permissions
1444    if (!recordingAllowed(opPackageName, tid, clientUid)) {
1445        ALOGE("openRecord() permission denied: recording not allowed");
1446        lStatus = PERMISSION_DENIED;
1447        goto Exit;
1448    }
1449
1450    // further sample rate checks are performed by createRecordTrack_l()
1451    if (sampleRate == 0) {
1452        ALOGE("openRecord() invalid sample rate %u", sampleRate);
1453        lStatus = BAD_VALUE;
1454        goto Exit;
1455    }
1456
1457    // we don't yet support anything other than linear PCM
1458    if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
1459        ALOGE("openRecord() invalid format %#x", format);
1460        lStatus = BAD_VALUE;
1461        goto Exit;
1462    }
1463
1464    // further channel mask checks are performed by createRecordTrack_l()
1465    if (!audio_is_input_channel(channelMask)) {
1466        ALOGE("openRecord() invalid channel mask %#x", channelMask);
1467        lStatus = BAD_VALUE;
1468        goto Exit;
1469    }
1470
1471    {
1472        Mutex::Autolock _l(mLock);
1473        RecordThread *thread = checkRecordThread_l(input);
1474        if (thread == NULL) {
1475            ALOGE("openRecord() checkRecordThread_l failed");
1476            lStatus = BAD_VALUE;
1477            goto Exit;
1478        }
1479
1480        pid_t pid = IPCThreadState::self()->getCallingPid();
1481        client = registerPid(pid);
1482
1483        if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
1484            lSessionId = *sessionId;
1485        } else {
1486            // if no audio session id is provided, create one here
1487            lSessionId = nextUniqueId();
1488            if (sessionId != NULL) {
1489                *sessionId = lSessionId;
1490            }
1491        }
1492        ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
1493
1494        recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
1495                                                  frameCount, lSessionId, notificationFrames,
1496                                                  clientUid, flags, tid, &lStatus);
1497        LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
1498
1499        if (lStatus == NO_ERROR) {
1500            // Check if one effect chain was awaiting for an AudioRecord to be created on this
1501            // session and move it to this thread.
1502            sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)lSessionId);
1503            if (chain != 0) {
1504                Mutex::Autolock _l(thread->mLock);
1505                thread->addEffectChain_l(chain);
1506            }
1507        }
1508    }
1509
1510    if (lStatus != NO_ERROR) {
1511        // remove local strong reference to Client before deleting the RecordTrack so that the
1512        // Client destructor is called by the TrackBase destructor with mClientLock held
1513        // Don't hold mClientLock when releasing the reference on the track as the
1514        // destructor will acquire it.
1515        {
1516            Mutex::Autolock _cl(mClientLock);
1517            client.clear();
1518        }
1519        recordTrack.clear();
1520        goto Exit;
1521    }
1522
1523    cblk = recordTrack->getCblk();
1524    buffers = recordTrack->getBuffers();
1525
1526    // return handle to client
1527    recordHandle = new RecordHandle(recordTrack);
1528
1529Exit:
1530    *status = lStatus;
1531    return recordHandle;
1532}
1533
1534
1535
1536// ----------------------------------------------------------------------------
1537
1538audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1539{
1540    if (name == NULL) {
1541        return 0;
1542    }
1543    if (!settingsAllowed()) {
1544        return 0;
1545    }
1546    Mutex::Autolock _l(mLock);
1547    return loadHwModule_l(name);
1548}
1549
1550// loadHwModule_l() must be called with AudioFlinger::mLock held
1551audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1552{
1553    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1554        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1555            ALOGW("loadHwModule() module %s already loaded", name);
1556            return mAudioHwDevs.keyAt(i);
1557        }
1558    }
1559
1560    audio_hw_device_t *dev;
1561
1562    int rc = load_audio_interface(name, &dev);
1563    if (rc) {
1564        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1565        return 0;
1566    }
1567
1568    mHardwareStatus = AUDIO_HW_INIT;
1569    rc = dev->init_check(dev);
1570    mHardwareStatus = AUDIO_HW_IDLE;
1571    if (rc) {
1572        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1573        return 0;
1574    }
1575
1576    // Check and cache this HAL's level of support for master mute and master
1577    // volume.  If this is the first HAL opened, and it supports the get
1578    // methods, use the initial values provided by the HAL as the current
1579    // master mute and volume settings.
1580
1581    AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1582    {  // scope for auto-lock pattern
1583        AutoMutex lock(mHardwareLock);
1584
1585        if (0 == mAudioHwDevs.size()) {
1586            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1587            if (NULL != dev->get_master_volume) {
1588                float mv;
1589                if (OK == dev->get_master_volume(dev, &mv)) {
1590                    mMasterVolume = mv;
1591                }
1592            }
1593
1594            mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1595            if (NULL != dev->get_master_mute) {
1596                bool mm;
1597                if (OK == dev->get_master_mute(dev, &mm)) {
1598                    mMasterMute = mm;
1599                }
1600            }
1601        }
1602
1603        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1604        if ((NULL != dev->set_master_volume) &&
1605            (OK == dev->set_master_volume(dev, mMasterVolume))) {
1606            flags = static_cast<AudioHwDevice::Flags>(flags |
1607                    AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1608        }
1609
1610        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1611        if ((NULL != dev->set_master_mute) &&
1612            (OK == dev->set_master_mute(dev, mMasterMute))) {
1613            flags = static_cast<AudioHwDevice::Flags>(flags |
1614                    AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1615        }
1616
1617        mHardwareStatus = AUDIO_HW_IDLE;
1618    }
1619
1620    audio_module_handle_t handle = nextUniqueId();
1621    mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
1622
1623    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
1624          name, dev->common.module->name, dev->common.module->id, handle);
1625
1626    return handle;
1627
1628}
1629
1630// ----------------------------------------------------------------------------
1631
1632uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
1633{
1634    Mutex::Autolock _l(mLock);
1635    PlaybackThread *thread = primaryPlaybackThread_l();
1636    return thread != NULL ? thread->sampleRate() : 0;
1637}
1638
1639size_t AudioFlinger::getPrimaryOutputFrameCount()
1640{
1641    Mutex::Autolock _l(mLock);
1642    PlaybackThread *thread = primaryPlaybackThread_l();
1643    return thread != NULL ? thread->frameCountHAL() : 0;
1644}
1645
1646// ----------------------------------------------------------------------------
1647
1648status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1649{
1650    uid_t uid = IPCThreadState::self()->getCallingUid();
1651    if (uid != AID_SYSTEM) {
1652        return PERMISSION_DENIED;
1653    }
1654    Mutex::Autolock _l(mLock);
1655    if (mIsDeviceTypeKnown) {
1656        return INVALID_OPERATION;
1657    }
1658    mIsLowRamDevice = isLowRamDevice;
1659    mIsDeviceTypeKnown = true;
1660    return NO_ERROR;
1661}
1662
1663audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1664{
1665    Mutex::Autolock _l(mLock);
1666
1667    ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1668    if (index >= 0) {
1669        ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1670              mHwAvSyncIds.valueAt(index), sessionId);
1671        return mHwAvSyncIds.valueAt(index);
1672    }
1673
1674    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1675    if (dev == NULL) {
1676        return AUDIO_HW_SYNC_INVALID;
1677    }
1678    char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1679    AudioParameter param = AudioParameter(String8(reply));
1680    free(reply);
1681
1682    int value;
1683    if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1684        ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1685        return AUDIO_HW_SYNC_INVALID;
1686    }
1687
1688    // allow only one session for a given HW A/V sync ID.
1689    for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1690        if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1691            ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1692                  value, mHwAvSyncIds.keyAt(i));
1693            mHwAvSyncIds.removeItemsAt(i);
1694            break;
1695        }
1696    }
1697
1698    mHwAvSyncIds.add(sessionId, value);
1699
1700    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1701        sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1702        uint32_t sessions = thread->hasAudioSession(sessionId);
1703        if (sessions & PlaybackThread::TRACK_SESSION) {
1704            AudioParameter param = AudioParameter();
1705            param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1706            thread->setParameters(param.toString());
1707            break;
1708        }
1709    }
1710
1711    ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1712    return (audio_hw_sync_t)value;
1713}
1714
1715status_t AudioFlinger::systemReady()
1716{
1717    Mutex::Autolock _l(mLock);
1718    ALOGI("%s", __FUNCTION__);
1719    if (mSystemReady) {
1720        ALOGW("%s called twice", __FUNCTION__);
1721        return NO_ERROR;
1722    }
1723    mSystemReady = true;
1724    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1725        ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1726        thread->systemReady();
1727    }
1728    for (size_t i = 0; i < mRecordThreads.size(); i++) {
1729        ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1730        thread->systemReady();
1731    }
1732    return NO_ERROR;
1733}
1734
1735// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1736void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1737{
1738    ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1739    if (index >= 0) {
1740        audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1741        ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1742        AudioParameter param = AudioParameter();
1743        param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1744        thread->setParameters(param.toString());
1745    }
1746}
1747
1748
1749// ----------------------------------------------------------------------------
1750
1751
1752sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
1753                                                            audio_io_handle_t *output,
1754                                                            audio_config_t *config,
1755                                                            audio_devices_t devices,
1756                                                            const String8& address,
1757                                                            audio_output_flags_t flags)
1758{
1759    AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
1760    if (outHwDev == NULL) {
1761        return 0;
1762    }
1763
1764    audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1765    if (*output == AUDIO_IO_HANDLE_NONE) {
1766        *output = nextUniqueId();
1767    }
1768
1769    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1770
1771    // FOR TESTING ONLY:
1772    // This if statement allows overriding the audio policy settings
1773    // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1774    if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1775        // Check only for Normal Mixing mode
1776        if (kEnableExtendedPrecision) {
1777            // Specify format (uncomment one below to choose)
1778            //config->format = AUDIO_FORMAT_PCM_FLOAT;
1779            //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1780            //config->format = AUDIO_FORMAT_PCM_32_BIT;
1781            //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
1782            // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
1783        }
1784        if (kEnableExtendedChannels) {
1785            // Specify channel mask (uncomment one below to choose)
1786            //config->channel_mask = audio_channel_out_mask_from_count(4);  // for USB 4ch
1787            //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1788            //        AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1);  // another 4ch example
1789        }
1790    }
1791
1792    AudioStreamOut *outputStream = NULL;
1793    status_t status = outHwDev->openOutputStream(
1794            &outputStream,
1795            *output,
1796            devices,
1797            flags,
1798            config,
1799            address.string());
1800
1801    mHardwareStatus = AUDIO_HW_IDLE;
1802
1803    if (status == NO_ERROR) {
1804
1805        PlaybackThread *thread;
1806        if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1807            thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
1808            ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
1809        } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1810                || !isValidPcmSinkFormat(config->format)
1811                || !isValidPcmSinkChannelMask(config->channel_mask)) {
1812            thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
1813            ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
1814        } else {
1815            thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
1816            ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
1817        }
1818        mPlaybackThreads.add(*output, thread);
1819        return thread;
1820    }
1821
1822    return 0;
1823}
1824
1825status_t AudioFlinger::openOutput(audio_module_handle_t module,
1826                                  audio_io_handle_t *output,
1827                                  audio_config_t *config,
1828                                  audio_devices_t *devices,
1829                                  const String8& address,
1830                                  uint32_t *latencyMs,
1831                                  audio_output_flags_t flags)
1832{
1833    ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
1834              module,
1835              (devices != NULL) ? *devices : 0,
1836              config->sample_rate,
1837              config->format,
1838              config->channel_mask,
1839              flags);
1840
1841    if (*devices == AUDIO_DEVICE_NONE) {
1842        return BAD_VALUE;
1843    }
1844
1845    Mutex::Autolock _l(mLock);
1846
1847    sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
1848    if (thread != 0) {
1849        *latencyMs = thread->latency();
1850
1851        // notify client processes of the new output creation
1852        thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
1853
1854        // the first primary output opened designates the primary hw device
1855        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
1856            ALOGI("Using module %d has the primary audio interface", module);
1857            mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
1858
1859            AutoMutex lock(mHardwareLock);
1860            mHardwareStatus = AUDIO_HW_SET_MODE;
1861            mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
1862            mHardwareStatus = AUDIO_HW_IDLE;
1863        }
1864        return NO_ERROR;
1865    }
1866
1867    return NO_INIT;
1868}
1869
1870audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1871        audio_io_handle_t output2)
1872{
1873    Mutex::Autolock _l(mLock);
1874    MixerThread *thread1 = checkMixerThread_l(output1);
1875    MixerThread *thread2 = checkMixerThread_l(output2);
1876
1877    if (thread1 == NULL || thread2 == NULL) {
1878        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1879                output2);
1880        return AUDIO_IO_HANDLE_NONE;
1881    }
1882
1883    audio_io_handle_t id = nextUniqueId();
1884    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
1885    thread->addOutputTrack(thread2);
1886    mPlaybackThreads.add(id, thread);
1887    // notify client processes of the new output creation
1888    thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
1889    return id;
1890}
1891
1892status_t AudioFlinger::closeOutput(audio_io_handle_t output)
1893{
1894    return closeOutput_nonvirtual(output);
1895}
1896
1897status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1898{
1899    // keep strong reference on the playback thread so that
1900    // it is not destroyed while exit() is executed
1901    sp<PlaybackThread> thread;
1902    {
1903        Mutex::Autolock _l(mLock);
1904        thread = checkPlaybackThread_l(output);
1905        if (thread == NULL) {
1906            return BAD_VALUE;
1907        }
1908
1909        ALOGV("closeOutput() %d", output);
1910
1911        if (thread->type() == ThreadBase::MIXER) {
1912            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1913                if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1914                    DuplicatingThread *dupThread =
1915                            (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
1916                    dupThread->removeOutputTrack((MixerThread *)thread.get());
1917                }
1918            }
1919        }
1920
1921
1922        mPlaybackThreads.removeItem(output);
1923        // save all effects to the default thread
1924        if (mPlaybackThreads.size()) {
1925            PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1926            if (dstThread != NULL) {
1927                // audioflinger lock is held here so the acquisition order of thread locks does not
1928                // matter
1929                Mutex::Autolock _dl(dstThread->mLock);
1930                Mutex::Autolock _sl(thread->mLock);
1931                Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1932                for (size_t i = 0; i < effectChains.size(); i ++) {
1933                    moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
1934                }
1935            }
1936        }
1937        const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1938        ioDesc->mIoHandle = output;
1939        ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
1940    }
1941    thread->exit();
1942    // The thread entity (active unit of execution) is no longer running here,
1943    // but the ThreadBase container still exists.
1944
1945    if (!thread->isDuplicating()) {
1946        closeOutputFinish(thread);
1947    }
1948
1949    return NO_ERROR;
1950}
1951
1952void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1953{
1954    AudioStreamOut *out = thread->clearOutput();
1955    ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1956    // from now on thread->mOutput is NULL
1957    out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1958    delete out;
1959}
1960
1961void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1962{
1963    mPlaybackThreads.removeItem(thread->mId);
1964    thread->exit();
1965    closeOutputFinish(thread);
1966}
1967
1968status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
1969{
1970    Mutex::Autolock _l(mLock);
1971    PlaybackThread *thread = checkPlaybackThread_l(output);
1972
1973    if (thread == NULL) {
1974        return BAD_VALUE;
1975    }
1976
1977    ALOGV("suspendOutput() %d", output);
1978    thread->suspend();
1979
1980    return NO_ERROR;
1981}
1982
1983status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
1984{
1985    Mutex::Autolock _l(mLock);
1986    PlaybackThread *thread = checkPlaybackThread_l(output);
1987
1988    if (thread == NULL) {
1989        return BAD_VALUE;
1990    }
1991
1992    ALOGV("restoreOutput() %d", output);
1993
1994    thread->restore();
1995
1996    return NO_ERROR;
1997}
1998
1999status_t AudioFlinger::openInput(audio_module_handle_t module,
2000                                          audio_io_handle_t *input,
2001                                          audio_config_t *config,
2002                                          audio_devices_t *devices,
2003                                          const String8& address,
2004                                          audio_source_t source,
2005                                          audio_input_flags_t flags)
2006{
2007    Mutex::Autolock _l(mLock);
2008
2009    if (*devices == AUDIO_DEVICE_NONE) {
2010        return BAD_VALUE;
2011    }
2012
2013    sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
2014
2015    if (thread != 0) {
2016        // notify client processes of the new input creation
2017        thread->ioConfigChanged(AUDIO_INPUT_OPENED);
2018        return NO_ERROR;
2019    }
2020    return NO_INIT;
2021}
2022
2023sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
2024                                                         audio_io_handle_t *input,
2025                                                         audio_config_t *config,
2026                                                         audio_devices_t devices,
2027                                                         const String8& address,
2028                                                         audio_source_t source,
2029                                                         audio_input_flags_t flags)
2030{
2031    AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
2032    if (inHwDev == NULL) {
2033        *input = AUDIO_IO_HANDLE_NONE;
2034        return 0;
2035    }
2036
2037    if (*input == AUDIO_IO_HANDLE_NONE) {
2038        *input = nextUniqueId();
2039    }
2040
2041    audio_config_t halconfig = *config;
2042    audio_hw_device_t *inHwHal = inHwDev->hwDevice();
2043    audio_stream_in_t *inStream = NULL;
2044    status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
2045                                        &inStream, flags, address.string(), source);
2046    ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
2047           ", Format %#x, Channels %x, flags %#x, status %d addr %s",
2048            inStream,
2049            halconfig.sample_rate,
2050            halconfig.format,
2051            halconfig.channel_mask,
2052            flags,
2053            status, address.string());
2054
2055    // If the input could not be opened with the requested parameters and we can handle the
2056    // conversion internally, try to open again with the proposed parameters.
2057    if (status == BAD_VALUE &&
2058        audio_is_linear_pcm(config->format) &&
2059        audio_is_linear_pcm(halconfig.format) &&
2060        (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
2061        (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
2062        (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
2063        // FIXME describe the change proposed by HAL (save old values so we can log them here)
2064        ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
2065        inStream = NULL;
2066        status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
2067                                            &inStream, flags, address.string(), source);
2068        // FIXME log this new status; HAL should not propose any further changes
2069    }
2070
2071    if (status == NO_ERROR && inStream != NULL) {
2072
2073#ifdef TEE_SINK
2074        // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2075        // or (re-)create if current Pipe is idle and does not match the new format
2076        sp<NBAIO_Sink> teeSink;
2077        enum {
2078            TEE_SINK_NO,    // don't copy input
2079            TEE_SINK_NEW,   // copy input using a new pipe
2080            TEE_SINK_OLD,   // copy input using an existing pipe
2081        } kind;
2082        NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2083                audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2084        if (!mTeeSinkInputEnabled) {
2085            kind = TEE_SINK_NO;
2086        } else if (!Format_isValid(format)) {
2087            kind = TEE_SINK_NO;
2088        } else if (mRecordTeeSink == 0) {
2089            kind = TEE_SINK_NEW;
2090        } else if (mRecordTeeSink->getStrongCount() != 1) {
2091            kind = TEE_SINK_NO;
2092        } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2093            kind = TEE_SINK_OLD;
2094        } else {
2095            kind = TEE_SINK_NEW;
2096        }
2097        switch (kind) {
2098        case TEE_SINK_NEW: {
2099            Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2100            size_t numCounterOffers = 0;
2101            const NBAIO_Format offers[1] = {format};
2102            ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2103            ALOG_ASSERT(index == 0);
2104            PipeReader *pipeReader = new PipeReader(*pipe);
2105            numCounterOffers = 0;
2106            index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2107            ALOG_ASSERT(index == 0);
2108            mRecordTeeSink = pipe;
2109            mRecordTeeSource = pipeReader;
2110            teeSink = pipe;
2111            }
2112            break;
2113        case TEE_SINK_OLD:
2114            teeSink = mRecordTeeSink;
2115            break;
2116        case TEE_SINK_NO:
2117        default:
2118            break;
2119        }
2120#endif
2121
2122        AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
2123
2124        // Start record thread
2125        // RecordThread requires both input and output device indication to forward to audio
2126        // pre processing modules
2127        sp<RecordThread> thread = new RecordThread(this,
2128                                  inputStream,
2129                                  *input,
2130                                  primaryOutputDevice_l(),
2131                                  devices,
2132                                  mSystemReady
2133#ifdef TEE_SINK
2134                                  , teeSink
2135#endif
2136                                  );
2137        mRecordThreads.add(*input, thread);
2138        ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2139        return thread;
2140    }
2141
2142    *input = AUDIO_IO_HANDLE_NONE;
2143    return 0;
2144}
2145
2146status_t AudioFlinger::closeInput(audio_io_handle_t input)
2147{
2148    return closeInput_nonvirtual(input);
2149}
2150
2151status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2152{
2153    // keep strong reference on the record thread so that
2154    // it is not destroyed while exit() is executed
2155    sp<RecordThread> thread;
2156    {
2157        Mutex::Autolock _l(mLock);
2158        thread = checkRecordThread_l(input);
2159        if (thread == 0) {
2160            return BAD_VALUE;
2161        }
2162
2163        ALOGV("closeInput() %d", input);
2164
2165        // If we still have effect chains, it means that a client still holds a handle
2166        // on at least one effect. We must either move the chain to an existing thread with the
2167        // same session ID or put it aside in case a new record thread is opened for a
2168        // new capture on the same session
2169        sp<EffectChain> chain;
2170        {
2171            Mutex::Autolock _sl(thread->mLock);
2172            Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2173            // Note: maximum one chain per record thread
2174            if (effectChains.size() != 0) {
2175                chain = effectChains[0];
2176            }
2177        }
2178        if (chain != 0) {
2179            // first check if a record thread is already opened with a client on the same session.
2180            // This should only happen in case of overlap between one thread tear down and the
2181            // creation of its replacement
2182            size_t i;
2183            for (i = 0; i < mRecordThreads.size(); i++) {
2184                sp<RecordThread> t = mRecordThreads.valueAt(i);
2185                if (t == thread) {
2186                    continue;
2187                }
2188                if (t->hasAudioSession(chain->sessionId()) != 0) {
2189                    Mutex::Autolock _l(t->mLock);
2190                    ALOGV("closeInput() found thread %d for effect session %d",
2191                          t->id(), chain->sessionId());
2192                    t->addEffectChain_l(chain);
2193                    break;
2194                }
2195            }
2196            // put the chain aside if we could not find a record thread with the same session id.
2197            if (i == mRecordThreads.size()) {
2198                putOrphanEffectChain_l(chain);
2199            }
2200        }
2201        const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2202        ioDesc->mIoHandle = input;
2203        ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
2204        mRecordThreads.removeItem(input);
2205    }
2206    // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2207    // we have a different lock for notification client
2208    closeInputFinish(thread);
2209    return NO_ERROR;
2210}
2211
2212void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2213{
2214    thread->exit();
2215    AudioStreamIn *in = thread->clearInput();
2216    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2217    // from now on thread->mInput is NULL
2218    in->hwDev()->close_input_stream(in->hwDev(), in->stream);
2219    delete in;
2220}
2221
2222void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2223{
2224    mRecordThreads.removeItem(thread->mId);
2225    closeInputFinish(thread);
2226}
2227
2228status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
2229{
2230    Mutex::Autolock _l(mLock);
2231    ALOGV("invalidateStream() stream %d", stream);
2232
2233    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2234        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2235        thread->invalidateTracks(stream);
2236    }
2237
2238    return NO_ERROR;
2239}
2240
2241
2242audio_unique_id_t AudioFlinger::newAudioUniqueId()
2243{
2244    return nextUniqueId();
2245}
2246
2247void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
2248{
2249    Mutex::Autolock _l(mLock);
2250    pid_t caller = IPCThreadState::self()->getCallingPid();
2251    ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2252    if (pid != -1 && (caller == getpid_cached)) {
2253        caller = pid;
2254    }
2255
2256    {
2257        Mutex::Autolock _cl(mClientLock);
2258        // Ignore requests received from processes not known as notification client. The request
2259        // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2260        // called from a different pid leaving a stale session reference.  Also we don't know how
2261        // to clear this reference if the client process dies.
2262        if (mNotificationClients.indexOfKey(caller) < 0) {
2263            ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2264            return;
2265        }
2266    }
2267
2268    size_t num = mAudioSessionRefs.size();
2269    for (size_t i = 0; i< num; i++) {
2270        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
2271        if (ref->mSessionid == audioSession && ref->mPid == caller) {
2272            ref->mCnt++;
2273            ALOGV(" incremented refcount to %d", ref->mCnt);
2274            return;
2275        }
2276    }
2277    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2278    ALOGV(" added new entry for %d", audioSession);
2279}
2280
2281void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
2282{
2283    Mutex::Autolock _l(mLock);
2284    pid_t caller = IPCThreadState::self()->getCallingPid();
2285    ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2286    if (pid != -1 && (caller == getpid_cached)) {
2287        caller = pid;
2288    }
2289    size_t num = mAudioSessionRefs.size();
2290    for (size_t i = 0; i< num; i++) {
2291        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2292        if (ref->mSessionid == audioSession && ref->mPid == caller) {
2293            ref->mCnt--;
2294            ALOGV(" decremented refcount to %d", ref->mCnt);
2295            if (ref->mCnt == 0) {
2296                mAudioSessionRefs.removeAt(i);
2297                delete ref;
2298                purgeStaleEffects_l();
2299            }
2300            return;
2301        }
2302    }
2303    // If the caller is mediaserver it is likely that the session being released was acquired
2304    // on behalf of a process not in notification clients and we ignore the warning.
2305    ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
2306}
2307
2308void AudioFlinger::purgeStaleEffects_l() {
2309
2310    ALOGV("purging stale effects");
2311
2312    Vector< sp<EffectChain> > chains;
2313
2314    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2315        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2316        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2317            sp<EffectChain> ec = t->mEffectChains[j];
2318            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2319                chains.push(ec);
2320            }
2321        }
2322    }
2323    for (size_t i = 0; i < mRecordThreads.size(); i++) {
2324        sp<RecordThread> t = mRecordThreads.valueAt(i);
2325        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2326            sp<EffectChain> ec = t->mEffectChains[j];
2327            chains.push(ec);
2328        }
2329    }
2330
2331    for (size_t i = 0; i < chains.size(); i++) {
2332        sp<EffectChain> ec = chains[i];
2333        int sessionid = ec->sessionId();
2334        sp<ThreadBase> t = ec->mThread.promote();
2335        if (t == 0) {
2336            continue;
2337        }
2338        size_t numsessionrefs = mAudioSessionRefs.size();
2339        bool found = false;
2340        for (size_t k = 0; k < numsessionrefs; k++) {
2341            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
2342            if (ref->mSessionid == sessionid) {
2343                ALOGV(" session %d still exists for %d with %d refs",
2344                    sessionid, ref->mPid, ref->mCnt);
2345                found = true;
2346                break;
2347            }
2348        }
2349        if (!found) {
2350            Mutex::Autolock _l(t->mLock);
2351            // remove all effects from the chain
2352            while (ec->mEffects.size()) {
2353                sp<EffectModule> effect = ec->mEffects[0];
2354                effect->unPin();
2355                t->removeEffect_l(effect);
2356                if (effect->purgeHandles()) {
2357                    t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
2358                }
2359                AudioSystem::unregisterEffect(effect->id());
2360            }
2361        }
2362    }
2363    return;
2364}
2365
2366// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2367AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
2368{
2369    return mPlaybackThreads.valueFor(output).get();
2370}
2371
2372// checkMixerThread_l() must be called with AudioFlinger::mLock held
2373AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
2374{
2375    PlaybackThread *thread = checkPlaybackThread_l(output);
2376    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
2377}
2378
2379// checkRecordThread_l() must be called with AudioFlinger::mLock held
2380AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
2381{
2382    return mRecordThreads.valueFor(input).get();
2383}
2384
2385uint32_t AudioFlinger::nextUniqueId()
2386{
2387    return (uint32_t) android_atomic_inc(&mNextUniqueId);
2388}
2389
2390AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
2391{
2392    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2393        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2394        if(thread->isDuplicating()) {
2395            continue;
2396        }
2397        AudioStreamOut *output = thread->getOutput();
2398        if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
2399            return thread;
2400        }
2401    }
2402    return NULL;
2403}
2404
2405audio_devices_t AudioFlinger::primaryOutputDevice_l() const
2406{
2407    PlaybackThread *thread = primaryPlaybackThread_l();
2408
2409    if (thread == NULL) {
2410        return 0;
2411    }
2412
2413    return thread->outDevice();
2414}
2415
2416sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2417                                    int triggerSession,
2418                                    int listenerSession,
2419                                    sync_event_callback_t callBack,
2420                                    wp<RefBase> cookie)
2421{
2422    Mutex::Autolock _l(mLock);
2423
2424    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2425    status_t playStatus = NAME_NOT_FOUND;
2426    status_t recStatus = NAME_NOT_FOUND;
2427    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2428        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2429        if (playStatus == NO_ERROR) {
2430            return event;
2431        }
2432    }
2433    for (size_t i = 0; i < mRecordThreads.size(); i++) {
2434        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2435        if (recStatus == NO_ERROR) {
2436            return event;
2437        }
2438    }
2439    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2440        mPendingSyncEvents.add(event);
2441    } else {
2442        ALOGV("createSyncEvent() invalid event %d", event->type());
2443        event.clear();
2444    }
2445    return event;
2446}
2447
2448// ----------------------------------------------------------------------------
2449//  Effect management
2450// ----------------------------------------------------------------------------
2451
2452
2453status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
2454{
2455    Mutex::Autolock _l(mLock);
2456    return EffectQueryNumberEffects(numEffects);
2457}
2458
2459status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
2460{
2461    Mutex::Autolock _l(mLock);
2462    return EffectQueryEffect(index, descriptor);
2463}
2464
2465status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
2466        effect_descriptor_t *descriptor) const
2467{
2468    Mutex::Autolock _l(mLock);
2469    return EffectGetDescriptor(pUuid, descriptor);
2470}
2471
2472
2473sp<IEffect> AudioFlinger::createEffect(
2474        effect_descriptor_t *pDesc,
2475        const sp<IEffectClient>& effectClient,
2476        int32_t priority,
2477        audio_io_handle_t io,
2478        int sessionId,
2479        const String16& opPackageName,
2480        status_t *status,
2481        int *id,
2482        int *enabled)
2483{
2484    status_t lStatus = NO_ERROR;
2485    sp<EffectHandle> handle;
2486    effect_descriptor_t desc;
2487
2488    pid_t pid = IPCThreadState::self()->getCallingPid();
2489    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
2490            pid, effectClient.get(), priority, sessionId, io);
2491
2492    if (pDesc == NULL) {
2493        lStatus = BAD_VALUE;
2494        goto Exit;
2495    }
2496
2497    // check audio settings permission for global effects
2498    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
2499        lStatus = PERMISSION_DENIED;
2500        goto Exit;
2501    }
2502
2503    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
2504    // that can only be created by audio policy manager (running in same process)
2505    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
2506        lStatus = PERMISSION_DENIED;
2507        goto Exit;
2508    }
2509
2510    {
2511        if (!EffectIsNullUuid(&pDesc->uuid)) {
2512            // if uuid is specified, request effect descriptor
2513            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2514            if (lStatus < 0) {
2515                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
2516                goto Exit;
2517            }
2518        } else {
2519            // if uuid is not specified, look for an available implementation
2520            // of the required type in effect factory
2521            if (EffectIsNullUuid(&pDesc->type)) {
2522                ALOGW("createEffect() no effect type");
2523                lStatus = BAD_VALUE;
2524                goto Exit;
2525            }
2526            uint32_t numEffects = 0;
2527            effect_descriptor_t d;
2528            d.flags = 0; // prevent compiler warning
2529            bool found = false;
2530
2531            lStatus = EffectQueryNumberEffects(&numEffects);
2532            if (lStatus < 0) {
2533                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
2534                goto Exit;
2535            }
2536            for (uint32_t i = 0; i < numEffects; i++) {
2537                lStatus = EffectQueryEffect(i, &desc);
2538                if (lStatus < 0) {
2539                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
2540                    continue;
2541                }
2542                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2543                    // If matching type found save effect descriptor. If the session is
2544                    // 0 and the effect is not auxiliary, continue enumeration in case
2545                    // an auxiliary version of this effect type is available
2546                    found = true;
2547                    d = desc;
2548                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
2549                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2550                        break;
2551                    }
2552                }
2553            }
2554            if (!found) {
2555                lStatus = BAD_VALUE;
2556                ALOGW("createEffect() effect not found");
2557                goto Exit;
2558            }
2559            // For same effect type, chose auxiliary version over insert version if
2560            // connect to output mix (Compliance to OpenSL ES)
2561            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
2562                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
2563                desc = d;
2564            }
2565        }
2566
2567        // Do not allow auxiliary effects on a session different from 0 (output mix)
2568        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
2569             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2570            lStatus = INVALID_OPERATION;
2571            goto Exit;
2572        }
2573
2574        // check recording permission for visualizer
2575        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
2576            !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
2577            lStatus = PERMISSION_DENIED;
2578            goto Exit;
2579        }
2580
2581        // return effect descriptor
2582        *pDesc = desc;
2583        if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2584            // if the output returned by getOutputForEffect() is removed before we lock the
2585            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2586            // and we will exit safely
2587            io = AudioSystem::getOutputForEffect(&desc);
2588            ALOGV("createEffect got output %d", io);
2589        }
2590
2591        Mutex::Autolock _l(mLock);
2592
2593        // If output is not specified try to find a matching audio session ID in one of the
2594        // output threads.
2595        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2596        // because of code checking output when entering the function.
2597        // Note: io is never 0 when creating an effect on an input
2598        if (io == AUDIO_IO_HANDLE_NONE) {
2599            if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2600                // output must be specified by AudioPolicyManager when using session
2601                // AUDIO_SESSION_OUTPUT_STAGE
2602                lStatus = BAD_VALUE;
2603                goto Exit;
2604            }
2605            // look for the thread where the specified audio session is present
2606            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2607                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2608                    io = mPlaybackThreads.keyAt(i);
2609                    break;
2610                }
2611            }
2612            if (io == 0) {
2613                for (size_t i = 0; i < mRecordThreads.size(); i++) {
2614                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2615                        io = mRecordThreads.keyAt(i);
2616                        break;
2617                    }
2618                }
2619            }
2620            // If no output thread contains the requested session ID, default to
2621            // first output. The effect chain will be moved to the correct output
2622            // thread when a track with the same session ID is created
2623            if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
2624                io = mPlaybackThreads.keyAt(0);
2625            }
2626            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
2627        }
2628        ThreadBase *thread = checkRecordThread_l(io);
2629        if (thread == NULL) {
2630            thread = checkPlaybackThread_l(io);
2631            if (thread == NULL) {
2632                ALOGE("createEffect() unknown output thread");
2633                lStatus = BAD_VALUE;
2634                goto Exit;
2635            }
2636        } else {
2637            // Check if one effect chain was awaiting for an effect to be created on this
2638            // session and used it instead of creating a new one.
2639            sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2640            if (chain != 0) {
2641                Mutex::Autolock _l(thread->mLock);
2642                thread->addEffectChain_l(chain);
2643            }
2644        }
2645
2646        sp<Client> client = registerPid(pid);
2647
2648        // create effect on selected output thread
2649        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2650                &desc, enabled, &lStatus);
2651        if (handle != 0 && id != NULL) {
2652            *id = handle->id();
2653        }
2654        if (handle == 0) {
2655            // remove local strong reference to Client with mClientLock held
2656            Mutex::Autolock _cl(mClientLock);
2657            client.clear();
2658        }
2659    }
2660
2661Exit:
2662    *status = lStatus;
2663    return handle;
2664}
2665
2666status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2667        audio_io_handle_t dstOutput)
2668{
2669    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
2670            sessionId, srcOutput, dstOutput);
2671    Mutex::Autolock _l(mLock);
2672    if (srcOutput == dstOutput) {
2673        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
2674        return NO_ERROR;
2675    }
2676    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2677    if (srcThread == NULL) {
2678        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
2679        return BAD_VALUE;
2680    }
2681    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2682    if (dstThread == NULL) {
2683        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
2684        return BAD_VALUE;
2685    }
2686
2687    Mutex::Autolock _dl(dstThread->mLock);
2688    Mutex::Autolock _sl(srcThread->mLock);
2689    return moveEffectChain_l(sessionId, srcThread, dstThread, false);
2690}
2691
2692// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
2693status_t AudioFlinger::moveEffectChain_l(int sessionId,
2694                                   AudioFlinger::PlaybackThread *srcThread,
2695                                   AudioFlinger::PlaybackThread *dstThread,
2696                                   bool reRegister)
2697{
2698    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
2699            sessionId, srcThread, dstThread);
2700
2701    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
2702    if (chain == 0) {
2703        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
2704                sessionId, srcThread);
2705        return INVALID_OPERATION;
2706    }
2707
2708    // Check whether the destination thread has a channel count of FCC_2, which is
2709    // currently required for (most) effects. Prevent moving the effect chain here rather
2710    // than disabling the addEffect_l() call in dstThread below.
2711    if ((dstThread->type() == ThreadBase::MIXER || dstThread->isDuplicating()) &&
2712            dstThread->mChannelCount != FCC_2) {
2713        ALOGW("moveEffectChain_l() effect chain failed because"
2714                " destination thread %p channel count(%u) != %u",
2715                dstThread, dstThread->mChannelCount, FCC_2);
2716        return INVALID_OPERATION;
2717    }
2718
2719    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
2720    // so that a new chain is created with correct parameters when first effect is added. This is
2721    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
2722    // removed.
2723    srcThread->removeEffectChain_l(chain);
2724
2725    // transfer all effects one by one so that new effect chain is created on new thread with
2726    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
2727    sp<EffectChain> dstChain;
2728    uint32_t strategy = 0; // prevent compiler warning
2729    sp<EffectModule> effect = chain->getEffectFromId_l(0);
2730    Vector< sp<EffectModule> > removed;
2731    status_t status = NO_ERROR;
2732    while (effect != 0) {
2733        srcThread->removeEffect_l(effect);
2734        removed.add(effect);
2735        status = dstThread->addEffect_l(effect);
2736        if (status != NO_ERROR) {
2737            break;
2738        }
2739        // removeEffect_l() has stopped the effect if it was active so it must be restarted
2740        if (effect->state() == EffectModule::ACTIVE ||
2741                effect->state() == EffectModule::STOPPING) {
2742            effect->start();
2743        }
2744        // if the move request is not received from audio policy manager, the effect must be
2745        // re-registered with the new strategy and output
2746        if (dstChain == 0) {
2747            dstChain = effect->chain().promote();
2748            if (dstChain == 0) {
2749                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
2750                status = NO_INIT;
2751                break;
2752            }
2753            strategy = dstChain->strategy();
2754        }
2755        if (reRegister) {
2756            AudioSystem::unregisterEffect(effect->id());
2757            AudioSystem::registerEffect(&effect->desc(),
2758                                        dstThread->id(),
2759                                        strategy,
2760                                        sessionId,
2761                                        effect->id());
2762            AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2763        }
2764        effect = chain->getEffectFromId_l(0);
2765    }
2766
2767    if (status != NO_ERROR) {
2768        for (size_t i = 0; i < removed.size(); i++) {
2769            srcThread->addEffect_l(removed[i]);
2770            if (dstChain != 0 && reRegister) {
2771                AudioSystem::unregisterEffect(removed[i]->id());
2772                AudioSystem::registerEffect(&removed[i]->desc(),
2773                                            srcThread->id(),
2774                                            strategy,
2775                                            sessionId,
2776                                            removed[i]->id());
2777                AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
2778            }
2779        }
2780    }
2781
2782    return status;
2783}
2784
2785bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
2786{
2787    if (mGlobalEffectEnableTime != 0 &&
2788            ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2789        return true;
2790    }
2791
2792    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2793        sp<EffectChain> ec =
2794                mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2795        if (ec != 0 && ec->isNonOffloadableEnabled()) {
2796            return true;
2797        }
2798    }
2799    return false;
2800}
2801
2802void AudioFlinger::onNonOffloadableGlobalEffectEnable()
2803{
2804    Mutex::Autolock _l(mLock);
2805
2806    mGlobalEffectEnableTime = systemTime();
2807
2808    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2809        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2810        if (t->mType == ThreadBase::OFFLOAD) {
2811            t->invalidateTracks(AUDIO_STREAM_MUSIC);
2812        }
2813    }
2814
2815}
2816
2817status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2818{
2819    audio_session_t session = (audio_session_t)chain->sessionId();
2820    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2821    ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2822    if (index >= 0) {
2823        ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2824        return ALREADY_EXISTS;
2825    }
2826    mOrphanEffectChains.add(session, chain);
2827    return NO_ERROR;
2828}
2829
2830sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2831{
2832    sp<EffectChain> chain;
2833    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2834    ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2835    if (index >= 0) {
2836        chain = mOrphanEffectChains.valueAt(index);
2837        mOrphanEffectChains.removeItemsAt(index);
2838    }
2839    return chain;
2840}
2841
2842bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2843{
2844    Mutex::Autolock _l(mLock);
2845    audio_session_t session = (audio_session_t)effect->sessionId();
2846    ssize_t index = mOrphanEffectChains.indexOfKey(session);
2847    ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2848    if (index >= 0) {
2849        sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2850        if (chain->removeEffect_l(effect) == 0) {
2851            ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2852            mOrphanEffectChains.removeItemsAt(index);
2853        }
2854        return true;
2855    }
2856    return false;
2857}
2858
2859
2860struct Entry {
2861#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2862    char mFileName[TEE_MAX_FILENAME];
2863};
2864
2865int comparEntry(const void *p1, const void *p2)
2866{
2867    return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
2868}
2869
2870#ifdef TEE_SINK
2871void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
2872{
2873    NBAIO_Source *teeSource = source.get();
2874    if (teeSource != NULL) {
2875        // .wav rotation
2876        // There is a benign race condition if 2 threads call this simultaneously.
2877        // They would both traverse the directory, but the result would simply be
2878        // failures at unlink() which are ignored.  It's also unlikely since
2879        // normally dumpsys is only done by bugreport or from the command line.
2880        char teePath[32+256];
2881        strcpy(teePath, "/data/misc/media");
2882        size_t teePathLen = strlen(teePath);
2883        DIR *dir = opendir(teePath);
2884        teePath[teePathLen++] = '/';
2885        if (dir != NULL) {
2886#define TEE_MAX_SORT 20 // number of entries to sort
2887#define TEE_MAX_KEEP 10 // number of entries to keep
2888            struct Entry entries[TEE_MAX_SORT];
2889            size_t entryCount = 0;
2890            while (entryCount < TEE_MAX_SORT) {
2891                struct dirent de;
2892                struct dirent *result = NULL;
2893                int rc = readdir_r(dir, &de, &result);
2894                if (rc != 0) {
2895                    ALOGW("readdir_r failed %d", rc);
2896                    break;
2897                }
2898                if (result == NULL) {
2899                    break;
2900                }
2901                if (result != &de) {
2902                    ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2903                    break;
2904                }
2905                // ignore non .wav file entries
2906                size_t nameLen = strlen(de.d_name);
2907                if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
2908                        strcmp(&de.d_name[nameLen - 4], ".wav")) {
2909                    continue;
2910                }
2911                strcpy(entries[entryCount++].mFileName, de.d_name);
2912            }
2913            (void) closedir(dir);
2914            if (entryCount > TEE_MAX_KEEP) {
2915                qsort(entries, entryCount, sizeof(Entry), comparEntry);
2916                for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
2917                    strcpy(&teePath[teePathLen], entries[i].mFileName);
2918                    (void) unlink(teePath);
2919                }
2920            }
2921        } else {
2922            if (fd >= 0) {
2923                dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
2924            }
2925        }
2926        char teeTime[16];
2927        struct timeval tv;
2928        gettimeofday(&tv, NULL);
2929        struct tm tm;
2930        localtime_r(&tv.tv_sec, &tm);
2931        strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2932        snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2933        // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2934        int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
2935        if (teeFd >= 0) {
2936            // FIXME use libsndfile
2937            char wavHeader[44];
2938            memcpy(wavHeader,
2939                "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
2940                sizeof(wavHeader));
2941            NBAIO_Format format = teeSource->format();
2942            unsigned channelCount = Format_channelCount(format);
2943            uint32_t sampleRate = Format_sampleRate(format);
2944            size_t frameSize = Format_frameSize(format);
2945            wavHeader[22] = channelCount;       // number of channels
2946            wavHeader[24] = sampleRate;         // sample rate
2947            wavHeader[25] = sampleRate >> 8;
2948            wavHeader[32] = frameSize;          // block alignment
2949            wavHeader[33] = frameSize >> 8;
2950            write(teeFd, wavHeader, sizeof(wavHeader));
2951            size_t total = 0;
2952            bool firstRead = true;
2953#define TEE_SINK_READ 1024                      // frames per I/O operation
2954            void *buffer = malloc(TEE_SINK_READ * frameSize);
2955            for (;;) {
2956                size_t count = TEE_SINK_READ;
2957                ssize_t actual = teeSource->read(buffer, count);
2958                bool wasFirstRead = firstRead;
2959                firstRead = false;
2960                if (actual <= 0) {
2961                    if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2962                        continue;
2963                    }
2964                    break;
2965                }
2966                ALOG_ASSERT(actual <= (ssize_t)count);
2967                write(teeFd, buffer, actual * frameSize);
2968                total += actual;
2969            }
2970            free(buffer);
2971            lseek(teeFd, (off_t) 4, SEEK_SET);
2972            uint32_t temp = 44 + total * frameSize - 8;
2973            // FIXME not big-endian safe
2974            write(teeFd, &temp, sizeof(temp));
2975            lseek(teeFd, (off_t) 40, SEEK_SET);
2976            temp =  total * frameSize;
2977            // FIXME not big-endian safe
2978            write(teeFd, &temp, sizeof(temp));
2979            close(teeFd);
2980            if (fd >= 0) {
2981                dprintf(fd, "tee copied to %s\n", teePath);
2982            }
2983        } else {
2984            if (fd >= 0) {
2985                dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
2986            }
2987        }
2988    }
2989}
2990#endif
2991
2992// ----------------------------------------------------------------------------
2993
2994status_t AudioFlinger::onTransact(
2995        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2996{
2997    return BnAudioFlinger::onTransact(code, data, reply, flags);
2998}
2999
3000} // namespace android
3001