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