AudioFlinger.cpp revision 9e58b552f51b00b3b674102876bd6c77ef3da806
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 <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
27#include <binder/IPCThreadState.h>
28#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <utils/Trace.h>
31#include <binder/Parcel.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
34#include <utils/Atomic.h>
35
36#include <cutils/bitops.h>
37#include <cutils/properties.h>
38#include <cutils/compiler.h>
39
40//#include <private/media/AudioTrackShared.h>
41//#include <private/media/AudioEffectShared.h>
42
43#include <system/audio.h>
44#include <hardware/audio.h>
45
46#include "AudioMixer.h"
47#include "AudioFlinger.h"
48#include "ServiceUtilities.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 <common_time/cc_helper.h>
60//#include <common_time/local_clock.h>
61
62#include <media/IMediaLogService.h>
63
64// ----------------------------------------------------------------------------
65
66// Note: the following macro is used for extremely verbose logging message.  In
67// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
68// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
69// are so verbose that we want to suppress them even when we have ALOG_ASSERT
70// turned on.  Do not uncomment the #def below unless you really know what you
71// are doing and want to see all of the extremely verbose messages.
72//#define VERY_VERY_VERBOSE_LOGGING
73#ifdef VERY_VERY_VERBOSE_LOGGING
74#define ALOGVV ALOGV
75#else
76#define ALOGVV(a...) do { } while(0)
77#endif
78
79namespace android {
80
81static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
82static const char kHardwareLockedString[] = "Hardware lock is taken\n";
83
84
85nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
86
87uint32_t AudioFlinger::mScreenState;
88
89// ----------------------------------------------------------------------------
90
91static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
92{
93    const hw_module_t *mod;
94    int rc;
95
96    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
97    ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
98                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
99    if (rc) {
100        goto out;
101    }
102    rc = audio_hw_device_open(mod, dev);
103    ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
104                 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
105    if (rc) {
106        goto out;
107    }
108    if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
109        ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
110        rc = BAD_VALUE;
111        goto out;
112    }
113    return 0;
114
115out:
116    *dev = NULL;
117    return rc;
118}
119
120// ----------------------------------------------------------------------------
121
122AudioFlinger::AudioFlinger()
123    : BnAudioFlinger(),
124      mPrimaryHardwareDev(NULL),
125      mHardwareStatus(AUDIO_HW_IDLE),
126      mMasterVolume(1.0f),
127      mMasterMute(false),
128      mNextUniqueId(1),
129      mMode(AUDIO_MODE_INVALID),
130      mBtNrecIsOff(false)
131{
132    char value[PROPERTY_VALUE_MAX];
133    bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
134    if (doLog) {
135        mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters");
136    }
137}
138
139void AudioFlinger::onFirstRef()
140{
141    int rc = 0;
142
143    Mutex::Autolock _l(mLock);
144
145    /* TODO: move all this work into an Init() function */
146    char val_str[PROPERTY_VALUE_MAX] = { 0 };
147    if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
148        uint32_t int_val;
149        if (1 == sscanf(val_str, "%u", &int_val)) {
150            mStandbyTimeInNsecs = milliseconds(int_val);
151            ALOGI("Using %u mSec as standby time.", int_val);
152        } else {
153            mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
154            ALOGI("Using default %u mSec as standby time.",
155                    (uint32_t)(mStandbyTimeInNsecs / 1000000));
156        }
157    }
158
159    mMode = AUDIO_MODE_NORMAL;
160}
161
162AudioFlinger::~AudioFlinger()
163{
164    while (!mRecordThreads.isEmpty()) {
165        // closeInput_nonvirtual() will remove specified entry from mRecordThreads
166        closeInput_nonvirtual(mRecordThreads.keyAt(0));
167    }
168    while (!mPlaybackThreads.isEmpty()) {
169        // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
170        closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
171    }
172
173    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
174        // no mHardwareLock needed, as there are no other references to this
175        audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
176        delete mAudioHwDevs.valueAt(i);
177    }
178}
179
180static const char * const audio_interfaces[] = {
181    AUDIO_HARDWARE_MODULE_ID_PRIMARY,
182    AUDIO_HARDWARE_MODULE_ID_A2DP,
183    AUDIO_HARDWARE_MODULE_ID_USB,
184};
185#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
186
187AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
188        audio_module_handle_t module,
189        audio_devices_t devices)
190{
191    // if module is 0, the request comes from an old policy manager and we should load
192    // well known modules
193    if (module == 0) {
194        ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
195        for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
196            loadHwModule_l(audio_interfaces[i]);
197        }
198        // then try to find a module supporting the requested device.
199        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
200            AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
201            audio_hw_device_t *dev = audioHwDevice->hwDevice();
202            if ((dev->get_supported_devices != NULL) &&
203                    (dev->get_supported_devices(dev) & devices) == devices)
204                return audioHwDevice;
205        }
206    } else {
207        // check a match for the requested module handle
208        AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
209        if (audioHwDevice != NULL) {
210            return audioHwDevice;
211        }
212    }
213
214    return NULL;
215}
216
217void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
218{
219    const size_t SIZE = 256;
220    char buffer[SIZE];
221    String8 result;
222
223    result.append("Clients:\n");
224    for (size_t i = 0; i < mClients.size(); ++i) {
225        sp<Client> client = mClients.valueAt(i).promote();
226        if (client != 0) {
227            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
228            result.append(buffer);
229        }
230    }
231
232    result.append("Global session refs:\n");
233    result.append(" session pid count\n");
234    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
235        AudioSessionRef *r = mAudioSessionRefs[i];
236        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
237        result.append(buffer);
238    }
239    write(fd, result.string(), result.size());
240}
241
242
243void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
244{
245    const size_t SIZE = 256;
246    char buffer[SIZE];
247    String8 result;
248    hardware_call_state hardwareStatus = mHardwareStatus;
249
250    snprintf(buffer, SIZE, "Hardware status: %d\n"
251                           "Standby Time mSec: %u\n",
252                            hardwareStatus,
253                            (uint32_t)(mStandbyTimeInNsecs / 1000000));
254    result.append(buffer);
255    write(fd, result.string(), result.size());
256}
257
258void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
259{
260    const size_t SIZE = 256;
261    char buffer[SIZE];
262    String8 result;
263    snprintf(buffer, SIZE, "Permission Denial: "
264            "can't dump AudioFlinger from pid=%d, uid=%d\n",
265            IPCThreadState::self()->getCallingPid(),
266            IPCThreadState::self()->getCallingUid());
267    result.append(buffer);
268    write(fd, result.string(), result.size());
269}
270
271bool AudioFlinger::dumpTryLock(Mutex& mutex)
272{
273    bool locked = false;
274    for (int i = 0; i < kDumpLockRetries; ++i) {
275        if (mutex.tryLock() == NO_ERROR) {
276            locked = true;
277            break;
278        }
279        usleep(kDumpLockSleepUs);
280    }
281    return locked;
282}
283
284status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
285{
286    if (!dumpAllowed()) {
287        dumpPermissionDenial(fd, args);
288    } else {
289        // get state of hardware lock
290        bool hardwareLocked = dumpTryLock(mHardwareLock);
291        if (!hardwareLocked) {
292            String8 result(kHardwareLockedString);
293            write(fd, result.string(), result.size());
294        } else {
295            mHardwareLock.unlock();
296        }
297
298        bool locked = dumpTryLock(mLock);
299
300        // failed to lock - AudioFlinger is probably deadlocked
301        if (!locked) {
302            String8 result(kDeadlockedString);
303            write(fd, result.string(), result.size());
304        }
305
306        dumpClients(fd, args);
307        dumpInternals(fd, args);
308
309        // dump playback threads
310        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
311            mPlaybackThreads.valueAt(i)->dump(fd, args);
312        }
313
314        // dump record threads
315        for (size_t i = 0; i < mRecordThreads.size(); i++) {
316            mRecordThreads.valueAt(i)->dump(fd, args);
317        }
318
319        // dump all hardware devs
320        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
321            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
322            dev->dump(dev, fd);
323        }
324
325        // dump the serially shared record tee sink
326        if (mRecordTeeSource != 0) {
327            dumpTee(fd, mRecordTeeSource);
328        }
329
330        if (locked) {
331            mLock.unlock();
332        }
333
334        // append a copy of media.log here by forwarding fd to it, but don't attempt
335        // to lookup the service if it's not running, as it will block for a second
336        if (mLogMemoryDealer != 0) {
337            sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
338            if (binder != 0) {
339                fdprintf(fd, "\nmedia.log:\n");
340                Vector<String16> args;
341                binder->dump(fd, args);
342            }
343        }
344    }
345    return NO_ERROR;
346}
347
348sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
349{
350    // If pid is already in the mClients wp<> map, then use that entry
351    // (for which promote() is always != 0), otherwise create a new entry and Client.
352    sp<Client> client = mClients.valueFor(pid).promote();
353    if (client == 0) {
354        client = new Client(this, pid);
355        mClients.add(pid, client);
356    }
357
358    return client;
359}
360
361sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
362{
363    if (mLogMemoryDealer == 0) {
364        return new NBLog::Writer();
365    }
366    sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
367    sp<NBLog::Writer> writer = new NBLog::Writer(size, shared);
368    sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
369    if (binder != 0) {
370        interface_cast<IMediaLogService>(binder)->registerWriter(shared, size, name);
371    }
372    return writer;
373}
374
375void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
376{
377    sp<IMemory> iMemory(writer->getIMemory());
378    if (iMemory == 0) {
379        return;
380    }
381    sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
382    if (binder != 0) {
383        interface_cast<IMediaLogService>(binder)->unregisterWriter(iMemory);
384        // Now the media.log remote reference to IMemory is gone.
385        // When our last local reference to IMemory also drops to zero,
386        // the IMemory destructor will deallocate the region from mMemoryDealer.
387    }
388}
389
390// IAudioFlinger interface
391
392
393sp<IAudioTrack> AudioFlinger::createTrack(
394        audio_stream_type_t streamType,
395        uint32_t sampleRate,
396        audio_format_t format,
397        audio_channel_mask_t channelMask,
398        size_t frameCount,
399        IAudioFlinger::track_flags_t *flags,
400        const sp<IMemory>& sharedBuffer,
401        audio_io_handle_t output,
402        pid_t tid,
403        int *sessionId,
404        status_t *status)
405{
406    sp<PlaybackThread::Track> track;
407    sp<TrackHandle> trackHandle;
408    sp<Client> client;
409    status_t lStatus;
410    int lSessionId;
411
412    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
413    // but if someone uses binder directly they could bypass that and cause us to crash
414    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
415        ALOGE("createTrack() invalid stream type %d", streamType);
416        lStatus = BAD_VALUE;
417        goto Exit;
418    }
419
420    // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
421    // and we don't yet support 8.24 or 32-bit PCM
422    if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
423        ALOGE("createTrack() invalid format %d", format);
424        lStatus = BAD_VALUE;
425        goto Exit;
426    }
427
428    {
429        Mutex::Autolock _l(mLock);
430        PlaybackThread *thread = checkPlaybackThread_l(output);
431        PlaybackThread *effectThread = NULL;
432        if (thread == NULL) {
433            ALOGE("unknown output thread");
434            lStatus = BAD_VALUE;
435            goto Exit;
436        }
437
438        pid_t pid = IPCThreadState::self()->getCallingPid();
439        client = registerPid_l(pid);
440
441        ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
442        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
443            // check if an effect chain with the same session ID is present on another
444            // output thread and move it here.
445            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
446                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
447                if (mPlaybackThreads.keyAt(i) != output) {
448                    uint32_t sessions = t->hasAudioSession(*sessionId);
449                    if (sessions & PlaybackThread::EFFECT_SESSION) {
450                        effectThread = t.get();
451                        break;
452                    }
453                }
454            }
455            lSessionId = *sessionId;
456        } else {
457            // if no audio session id is provided, create one here
458            lSessionId = nextUniqueId();
459            if (sessionId != NULL) {
460                *sessionId = lSessionId;
461            }
462        }
463        ALOGV("createTrack() lSessionId: %d", lSessionId);
464
465        track = thread->createTrack_l(client, streamType, sampleRate, format,
466                channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
467
468        // move effect chain to this output thread if an effect on same session was waiting
469        // for a track to be created
470        if (lStatus == NO_ERROR && effectThread != NULL) {
471            Mutex::Autolock _dl(thread->mLock);
472            Mutex::Autolock _sl(effectThread->mLock);
473            moveEffectChain_l(lSessionId, effectThread, thread, true);
474        }
475
476        // Look for sync events awaiting for a session to be used.
477        for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
478            if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
479                if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
480                    if (lStatus == NO_ERROR) {
481                        (void) track->setSyncEvent(mPendingSyncEvents[i]);
482                    } else {
483                        mPendingSyncEvents[i]->cancel();
484                    }
485                    mPendingSyncEvents.removeAt(i);
486                    i--;
487                }
488            }
489        }
490    }
491    if (lStatus == NO_ERROR) {
492        trackHandle = new TrackHandle(track);
493    } else {
494        // remove local strong reference to Client before deleting the Track so that the Client
495        // destructor is called by the TrackBase destructor with mLock held
496        client.clear();
497        track.clear();
498    }
499
500Exit:
501    if (status != NULL) {
502        *status = lStatus;
503    }
504    return trackHandle;
505}
506
507uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
508{
509    Mutex::Autolock _l(mLock);
510    PlaybackThread *thread = checkPlaybackThread_l(output);
511    if (thread == NULL) {
512        ALOGW("sampleRate() unknown thread %d", output);
513        return 0;
514    }
515    return thread->sampleRate();
516}
517
518int AudioFlinger::channelCount(audio_io_handle_t output) const
519{
520    Mutex::Autolock _l(mLock);
521    PlaybackThread *thread = checkPlaybackThread_l(output);
522    if (thread == NULL) {
523        ALOGW("channelCount() unknown thread %d", output);
524        return 0;
525    }
526    return thread->channelCount();
527}
528
529audio_format_t AudioFlinger::format(audio_io_handle_t output) const
530{
531    Mutex::Autolock _l(mLock);
532    PlaybackThread *thread = checkPlaybackThread_l(output);
533    if (thread == NULL) {
534        ALOGW("format() unknown thread %d", output);
535        return AUDIO_FORMAT_INVALID;
536    }
537    return thread->format();
538}
539
540size_t AudioFlinger::frameCount(audio_io_handle_t output) const
541{
542    Mutex::Autolock _l(mLock);
543    PlaybackThread *thread = checkPlaybackThread_l(output);
544    if (thread == NULL) {
545        ALOGW("frameCount() unknown thread %d", output);
546        return 0;
547    }
548    // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
549    //       should examine all callers and fix them to handle smaller counts
550    return thread->frameCount();
551}
552
553uint32_t AudioFlinger::latency(audio_io_handle_t output) const
554{
555    Mutex::Autolock _l(mLock);
556    PlaybackThread *thread = checkPlaybackThread_l(output);
557    if (thread == NULL) {
558        ALOGW("latency() unknown thread %d", output);
559        return 0;
560    }
561    return thread->latency();
562}
563
564status_t AudioFlinger::setMasterVolume(float value)
565{
566    status_t ret = initCheck();
567    if (ret != NO_ERROR) {
568        return ret;
569    }
570
571    // check calling permissions
572    if (!settingsAllowed()) {
573        return PERMISSION_DENIED;
574    }
575
576    Mutex::Autolock _l(mLock);
577    mMasterVolume = value;
578
579    // Set master volume in the HALs which support it.
580    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
581        AutoMutex lock(mHardwareLock);
582        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
583
584        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
585        if (dev->canSetMasterVolume()) {
586            dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
587        }
588        mHardwareStatus = AUDIO_HW_IDLE;
589    }
590
591    // Now set the master volume in each playback thread.  Playback threads
592    // assigned to HALs which do not have master volume support will apply
593    // master volume during the mix operation.  Threads with HALs which do
594    // support master volume will simply ignore the setting.
595    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
596        mPlaybackThreads.valueAt(i)->setMasterVolume(value);
597
598    return NO_ERROR;
599}
600
601status_t AudioFlinger::setMode(audio_mode_t mode)
602{
603    status_t ret = initCheck();
604    if (ret != NO_ERROR) {
605        return ret;
606    }
607
608    // check calling permissions
609    if (!settingsAllowed()) {
610        return PERMISSION_DENIED;
611    }
612    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
613        ALOGW("Illegal value: setMode(%d)", mode);
614        return BAD_VALUE;
615    }
616
617    { // scope for the lock
618        AutoMutex lock(mHardwareLock);
619        audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
620        mHardwareStatus = AUDIO_HW_SET_MODE;
621        ret = dev->set_mode(dev, mode);
622        mHardwareStatus = AUDIO_HW_IDLE;
623    }
624
625    if (NO_ERROR == ret) {
626        Mutex::Autolock _l(mLock);
627        mMode = mode;
628        for (size_t i = 0; i < mPlaybackThreads.size(); i++)
629            mPlaybackThreads.valueAt(i)->setMode(mode);
630    }
631
632    return ret;
633}
634
635status_t AudioFlinger::setMicMute(bool state)
636{
637    status_t ret = initCheck();
638    if (ret != NO_ERROR) {
639        return ret;
640    }
641
642    // check calling permissions
643    if (!settingsAllowed()) {
644        return PERMISSION_DENIED;
645    }
646
647    AutoMutex lock(mHardwareLock);
648    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
649    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
650    ret = dev->set_mic_mute(dev, state);
651    mHardwareStatus = AUDIO_HW_IDLE;
652    return ret;
653}
654
655bool AudioFlinger::getMicMute() const
656{
657    status_t ret = initCheck();
658    if (ret != NO_ERROR) {
659        return false;
660    }
661
662    bool state = AUDIO_MODE_INVALID;
663    AutoMutex lock(mHardwareLock);
664    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
665    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
666    dev->get_mic_mute(dev, &state);
667    mHardwareStatus = AUDIO_HW_IDLE;
668    return state;
669}
670
671status_t AudioFlinger::setMasterMute(bool muted)
672{
673    status_t ret = initCheck();
674    if (ret != NO_ERROR) {
675        return ret;
676    }
677
678    // check calling permissions
679    if (!settingsAllowed()) {
680        return PERMISSION_DENIED;
681    }
682
683    Mutex::Autolock _l(mLock);
684    mMasterMute = muted;
685
686    // Set master mute in the HALs which support it.
687    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
688        AutoMutex lock(mHardwareLock);
689        AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
690
691        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
692        if (dev->canSetMasterMute()) {
693            dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
694        }
695        mHardwareStatus = AUDIO_HW_IDLE;
696    }
697
698    // Now set the master mute in each playback thread.  Playback threads
699    // assigned to HALs which do not have master mute support will apply master
700    // mute during the mix operation.  Threads with HALs which do support master
701    // mute will simply ignore the setting.
702    for (size_t i = 0; i < mPlaybackThreads.size(); i++)
703        mPlaybackThreads.valueAt(i)->setMasterMute(muted);
704
705    return NO_ERROR;
706}
707
708float AudioFlinger::masterVolume() const
709{
710    Mutex::Autolock _l(mLock);
711    return masterVolume_l();
712}
713
714bool AudioFlinger::masterMute() const
715{
716    Mutex::Autolock _l(mLock);
717    return masterMute_l();
718}
719
720float AudioFlinger::masterVolume_l() const
721{
722    return mMasterVolume;
723}
724
725bool AudioFlinger::masterMute_l() const
726{
727    return mMasterMute;
728}
729
730status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
731        audio_io_handle_t output)
732{
733    // check calling permissions
734    if (!settingsAllowed()) {
735        return PERMISSION_DENIED;
736    }
737
738    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
739        ALOGE("setStreamVolume() invalid stream %d", stream);
740        return BAD_VALUE;
741    }
742
743    AutoMutex lock(mLock);
744    PlaybackThread *thread = NULL;
745    if (output) {
746        thread = checkPlaybackThread_l(output);
747        if (thread == NULL) {
748            return BAD_VALUE;
749        }
750    }
751
752    mStreamTypes[stream].volume = value;
753
754    if (thread == NULL) {
755        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
756            mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
757        }
758    } else {
759        thread->setStreamVolume(stream, value);
760    }
761
762    return NO_ERROR;
763}
764
765status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
766{
767    // check calling permissions
768    if (!settingsAllowed()) {
769        return PERMISSION_DENIED;
770    }
771
772    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
773        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
774        ALOGE("setStreamMute() invalid stream %d", stream);
775        return BAD_VALUE;
776    }
777
778    AutoMutex lock(mLock);
779    mStreamTypes[stream].mute = muted;
780    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
781        mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
782
783    return NO_ERROR;
784}
785
786float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
787{
788    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
789        return 0.0f;
790    }
791
792    AutoMutex lock(mLock);
793    float volume;
794    if (output) {
795        PlaybackThread *thread = checkPlaybackThread_l(output);
796        if (thread == NULL) {
797            return 0.0f;
798        }
799        volume = thread->streamVolume(stream);
800    } else {
801        volume = streamVolume_l(stream);
802    }
803
804    return volume;
805}
806
807bool AudioFlinger::streamMute(audio_stream_type_t stream) const
808{
809    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
810        return true;
811    }
812
813    AutoMutex lock(mLock);
814    return streamMute_l(stream);
815}
816
817status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
818{
819    ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
820            ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
821
822    // check calling permissions
823    if (!settingsAllowed()) {
824        return PERMISSION_DENIED;
825    }
826
827    // ioHandle == 0 means the parameters are global to the audio hardware interface
828    if (ioHandle == 0) {
829        Mutex::Autolock _l(mLock);
830        status_t final_result = NO_ERROR;
831        {
832            AutoMutex lock(mHardwareLock);
833            mHardwareStatus = AUDIO_HW_SET_PARAMETER;
834            for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
835                audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
836                status_t result = dev->set_parameters(dev, keyValuePairs.string());
837                final_result = result ?: final_result;
838            }
839            mHardwareStatus = AUDIO_HW_IDLE;
840        }
841        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
842        AudioParameter param = AudioParameter(keyValuePairs);
843        String8 value;
844        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
845            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
846            if (mBtNrecIsOff != btNrecIsOff) {
847                for (size_t i = 0; i < mRecordThreads.size(); i++) {
848                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
849                    audio_devices_t device = thread->inDevice();
850                    bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
851                    // collect all of the thread's session IDs
852                    KeyedVector<int, bool> ids = thread->sessionIds();
853                    // suspend effects associated with those session IDs
854                    for (size_t j = 0; j < ids.size(); ++j) {
855                        int sessionId = ids.keyAt(j);
856                        thread->setEffectSuspended(FX_IID_AEC,
857                                                   suspend,
858                                                   sessionId);
859                        thread->setEffectSuspended(FX_IID_NS,
860                                                   suspend,
861                                                   sessionId);
862                    }
863                }
864                mBtNrecIsOff = btNrecIsOff;
865            }
866        }
867        String8 screenState;
868        if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
869            bool isOff = screenState == "off";
870            if (isOff != (AudioFlinger::mScreenState & 1)) {
871                AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
872            }
873        }
874        return final_result;
875    }
876
877    // hold a strong ref on thread in case closeOutput() or closeInput() is called
878    // and the thread is exited once the lock is released
879    sp<ThreadBase> thread;
880    {
881        Mutex::Autolock _l(mLock);
882        thread = checkPlaybackThread_l(ioHandle);
883        if (thread == 0) {
884            thread = checkRecordThread_l(ioHandle);
885        } else if (thread == primaryPlaybackThread_l()) {
886            // indicate output device change to all input threads for pre processing
887            AudioParameter param = AudioParameter(keyValuePairs);
888            int value;
889            if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
890                    (value != 0)) {
891                for (size_t i = 0; i < mRecordThreads.size(); i++) {
892                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
893                }
894            }
895        }
896    }
897    if (thread != 0) {
898        return thread->setParameters(keyValuePairs);
899    }
900    return BAD_VALUE;
901}
902
903String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
904{
905    ALOGVV("getParameters() io %d, keys %s, calling pid %d",
906            ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
907
908    Mutex::Autolock _l(mLock);
909
910    if (ioHandle == 0) {
911        String8 out_s8;
912
913        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
914            char *s;
915            {
916            AutoMutex lock(mHardwareLock);
917            mHardwareStatus = AUDIO_HW_GET_PARAMETER;
918            audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
919            s = dev->get_parameters(dev, keys.string());
920            mHardwareStatus = AUDIO_HW_IDLE;
921            }
922            out_s8 += String8(s ? s : "");
923            free(s);
924        }
925        return out_s8;
926    }
927
928    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
929    if (playbackThread != NULL) {
930        return playbackThread->getParameters(keys);
931    }
932    RecordThread *recordThread = checkRecordThread_l(ioHandle);
933    if (recordThread != NULL) {
934        return recordThread->getParameters(keys);
935    }
936    return String8("");
937}
938
939size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
940        audio_channel_mask_t channelMask) const
941{
942    status_t ret = initCheck();
943    if (ret != NO_ERROR) {
944        return 0;
945    }
946
947    AutoMutex lock(mHardwareLock);
948    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
949    struct audio_config config = {
950        sample_rate: sampleRate,
951        channel_mask: channelMask,
952        format: format,
953    };
954    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
955    size_t size = dev->get_input_buffer_size(dev, &config);
956    mHardwareStatus = AUDIO_HW_IDLE;
957    return size;
958}
959
960unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
961{
962    Mutex::Autolock _l(mLock);
963
964    RecordThread *recordThread = checkRecordThread_l(ioHandle);
965    if (recordThread != NULL) {
966        return recordThread->getInputFramesLost();
967    }
968    return 0;
969}
970
971status_t AudioFlinger::setVoiceVolume(float value)
972{
973    status_t ret = initCheck();
974    if (ret != NO_ERROR) {
975        return ret;
976    }
977
978    // check calling permissions
979    if (!settingsAllowed()) {
980        return PERMISSION_DENIED;
981    }
982
983    AutoMutex lock(mHardwareLock);
984    audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
985    mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
986    ret = dev->set_voice_volume(dev, value);
987    mHardwareStatus = AUDIO_HW_IDLE;
988
989    return ret;
990}
991
992status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
993        audio_io_handle_t output) const
994{
995    status_t status;
996
997    Mutex::Autolock _l(mLock);
998
999    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1000    if (playbackThread != NULL) {
1001        return playbackThread->getRenderPosition(halFrames, dspFrames);
1002    }
1003
1004    return BAD_VALUE;
1005}
1006
1007void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1008{
1009
1010    Mutex::Autolock _l(mLock);
1011
1012    pid_t pid = IPCThreadState::self()->getCallingPid();
1013    if (mNotificationClients.indexOfKey(pid) < 0) {
1014        sp<NotificationClient> notificationClient = new NotificationClient(this,
1015                                                                            client,
1016                                                                            pid);
1017        ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
1018
1019        mNotificationClients.add(pid, notificationClient);
1020
1021        sp<IBinder> binder = client->asBinder();
1022        binder->linkToDeath(notificationClient);
1023
1024        // the config change is always sent from playback or record threads to avoid deadlock
1025        // with AudioSystem::gLock
1026        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1027            mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
1028        }
1029
1030        for (size_t i = 0; i < mRecordThreads.size(); i++) {
1031            mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
1032        }
1033    }
1034}
1035
1036void AudioFlinger::removeNotificationClient(pid_t pid)
1037{
1038    Mutex::Autolock _l(mLock);
1039
1040    mNotificationClients.removeItem(pid);
1041
1042    ALOGV("%d died, releasing its sessions", pid);
1043    size_t num = mAudioSessionRefs.size();
1044    bool removed = false;
1045    for (size_t i = 0; i< num; ) {
1046        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1047        ALOGV(" pid %d @ %d", ref->mPid, i);
1048        if (ref->mPid == pid) {
1049            ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1050            mAudioSessionRefs.removeAt(i);
1051            delete ref;
1052            removed = true;
1053            num--;
1054        } else {
1055            i++;
1056        }
1057    }
1058    if (removed) {
1059        purgeStaleEffects_l();
1060    }
1061}
1062
1063// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1064void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
1065{
1066    size_t size = mNotificationClients.size();
1067    for (size_t i = 0; i < size; i++) {
1068        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1069                                                                               param2);
1070    }
1071}
1072
1073// removeClient_l() must be called with AudioFlinger::mLock held
1074void AudioFlinger::removeClient_l(pid_t pid)
1075{
1076    ALOGV("removeClient_l() pid %d, calling pid %d", pid,
1077            IPCThreadState::self()->getCallingPid());
1078    mClients.removeItem(pid);
1079}
1080
1081// getEffectThread_l() must be called with AudioFlinger::mLock held
1082sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1083{
1084    sp<PlaybackThread> thread;
1085
1086    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1087        if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1088            ALOG_ASSERT(thread == 0);
1089            thread = mPlaybackThreads.valueAt(i);
1090        }
1091    }
1092
1093    return thread;
1094}
1095
1096
1097
1098// ----------------------------------------------------------------------------
1099
1100AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1101    :   RefBase(),
1102        mAudioFlinger(audioFlinger),
1103        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
1104        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
1105        mPid(pid),
1106        mTimedTrackCount(0)
1107{
1108    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
1109}
1110
1111// Client destructor must be called with AudioFlinger::mLock held
1112AudioFlinger::Client::~Client()
1113{
1114    mAudioFlinger->removeClient_l(mPid);
1115}
1116
1117sp<MemoryDealer> AudioFlinger::Client::heap() const
1118{
1119    return mMemoryDealer;
1120}
1121
1122// Reserve one of the limited slots for a timed audio track associated
1123// with this client
1124bool AudioFlinger::Client::reserveTimedTrack()
1125{
1126    const int kMaxTimedTracksPerClient = 4;
1127
1128    Mutex::Autolock _l(mTimedTrackLock);
1129
1130    if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1131        ALOGW("can not create timed track - pid %d has exceeded the limit",
1132             mPid);
1133        return false;
1134    }
1135
1136    mTimedTrackCount++;
1137    return true;
1138}
1139
1140// Release a slot for a timed audio track
1141void AudioFlinger::Client::releaseTimedTrack()
1142{
1143    Mutex::Autolock _l(mTimedTrackLock);
1144    mTimedTrackCount--;
1145}
1146
1147// ----------------------------------------------------------------------------
1148
1149AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1150                                                     const sp<IAudioFlingerClient>& client,
1151                                                     pid_t pid)
1152    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
1153{
1154}
1155
1156AudioFlinger::NotificationClient::~NotificationClient()
1157{
1158}
1159
1160void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
1161{
1162    sp<NotificationClient> keep(this);
1163    mAudioFlinger->removeNotificationClient(mPid);
1164}
1165
1166
1167// ----------------------------------------------------------------------------
1168
1169sp<IAudioRecord> AudioFlinger::openRecord(
1170        audio_io_handle_t input,
1171        uint32_t sampleRate,
1172        audio_format_t format,
1173        audio_channel_mask_t channelMask,
1174        size_t frameCount,
1175        IAudioFlinger::track_flags_t flags,
1176        pid_t tid,
1177        int *sessionId,
1178        status_t *status)
1179{
1180    sp<RecordThread::RecordTrack> recordTrack;
1181    sp<RecordHandle> recordHandle;
1182    sp<Client> client;
1183    status_t lStatus;
1184    RecordThread *thread;
1185    size_t inFrameCount;
1186    int lSessionId;
1187
1188    // check calling permissions
1189    if (!recordingAllowed()) {
1190        lStatus = PERMISSION_DENIED;
1191        goto Exit;
1192    }
1193
1194    // add client to list
1195    { // scope for mLock
1196        Mutex::Autolock _l(mLock);
1197        thread = checkRecordThread_l(input);
1198        if (thread == NULL) {
1199            lStatus = BAD_VALUE;
1200            goto Exit;
1201        }
1202
1203        pid_t pid = IPCThreadState::self()->getCallingPid();
1204        client = registerPid_l(pid);
1205
1206        // If no audio session id is provided, create one here
1207        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1208            lSessionId = *sessionId;
1209        } else {
1210            lSessionId = nextUniqueId();
1211            if (sessionId != NULL) {
1212                *sessionId = lSessionId;
1213            }
1214        }
1215        // create new record track.
1216        // The record track uses one track in mHardwareMixerThread by convention.
1217        recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
1218                                                  frameCount, lSessionId, flags, tid, &lStatus);
1219    }
1220    if (lStatus != NO_ERROR) {
1221        // remove local strong reference to Client before deleting the RecordTrack so that the
1222        // Client destructor is called by the TrackBase destructor with mLock held
1223        client.clear();
1224        recordTrack.clear();
1225        goto Exit;
1226    }
1227
1228    // return to handle to client
1229    recordHandle = new RecordHandle(recordTrack);
1230    lStatus = NO_ERROR;
1231
1232Exit:
1233    if (status) {
1234        *status = lStatus;
1235    }
1236    return recordHandle;
1237}
1238
1239
1240
1241// ----------------------------------------------------------------------------
1242
1243audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1244{
1245    if (!settingsAllowed()) {
1246        return 0;
1247    }
1248    Mutex::Autolock _l(mLock);
1249    return loadHwModule_l(name);
1250}
1251
1252// loadHwModule_l() must be called with AudioFlinger::mLock held
1253audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1254{
1255    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1256        if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1257            ALOGW("loadHwModule() module %s already loaded", name);
1258            return mAudioHwDevs.keyAt(i);
1259        }
1260    }
1261
1262    audio_hw_device_t *dev;
1263
1264    int rc = load_audio_interface(name, &dev);
1265    if (rc) {
1266        ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1267        return 0;
1268    }
1269
1270    mHardwareStatus = AUDIO_HW_INIT;
1271    rc = dev->init_check(dev);
1272    mHardwareStatus = AUDIO_HW_IDLE;
1273    if (rc) {
1274        ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1275        return 0;
1276    }
1277
1278    // Check and cache this HAL's level of support for master mute and master
1279    // volume.  If this is the first HAL opened, and it supports the get
1280    // methods, use the initial values provided by the HAL as the current
1281    // master mute and volume settings.
1282
1283    AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1284    {  // scope for auto-lock pattern
1285        AutoMutex lock(mHardwareLock);
1286
1287        if (0 == mAudioHwDevs.size()) {
1288            mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1289            if (NULL != dev->get_master_volume) {
1290                float mv;
1291                if (OK == dev->get_master_volume(dev, &mv)) {
1292                    mMasterVolume = mv;
1293                }
1294            }
1295
1296            mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1297            if (NULL != dev->get_master_mute) {
1298                bool mm;
1299                if (OK == dev->get_master_mute(dev, &mm)) {
1300                    mMasterMute = mm;
1301                }
1302            }
1303        }
1304
1305        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1306        if ((NULL != dev->set_master_volume) &&
1307            (OK == dev->set_master_volume(dev, mMasterVolume))) {
1308            flags = static_cast<AudioHwDevice::Flags>(flags |
1309                    AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1310        }
1311
1312        mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1313        if ((NULL != dev->set_master_mute) &&
1314            (OK == dev->set_master_mute(dev, mMasterMute))) {
1315            flags = static_cast<AudioHwDevice::Flags>(flags |
1316                    AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1317        }
1318
1319        mHardwareStatus = AUDIO_HW_IDLE;
1320    }
1321
1322    audio_module_handle_t handle = nextUniqueId();
1323    mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
1324
1325    ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
1326          name, dev->common.module->name, dev->common.module->id, handle);
1327
1328    return handle;
1329
1330}
1331
1332// ----------------------------------------------------------------------------
1333
1334uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
1335{
1336    Mutex::Autolock _l(mLock);
1337    PlaybackThread *thread = primaryPlaybackThread_l();
1338    return thread != NULL ? thread->sampleRate() : 0;
1339}
1340
1341size_t AudioFlinger::getPrimaryOutputFrameCount()
1342{
1343    Mutex::Autolock _l(mLock);
1344    PlaybackThread *thread = primaryPlaybackThread_l();
1345    return thread != NULL ? thread->frameCountHAL() : 0;
1346}
1347
1348// ----------------------------------------------------------------------------
1349
1350audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
1351                                           audio_devices_t *pDevices,
1352                                           uint32_t *pSamplingRate,
1353                                           audio_format_t *pFormat,
1354                                           audio_channel_mask_t *pChannelMask,
1355                                           uint32_t *pLatencyMs,
1356                                           audio_output_flags_t flags)
1357{
1358    status_t status;
1359    PlaybackThread *thread = NULL;
1360    struct audio_config config = {
1361        sample_rate: pSamplingRate ? *pSamplingRate : 0,
1362        channel_mask: pChannelMask ? *pChannelMask : 0,
1363        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
1364    };
1365    audio_stream_out_t *outStream = NULL;
1366    AudioHwDevice *outHwDev;
1367
1368    ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
1369              module,
1370              (pDevices != NULL) ? *pDevices : 0,
1371              config.sample_rate,
1372              config.format,
1373              config.channel_mask,
1374              flags);
1375
1376    if (pDevices == NULL || *pDevices == 0) {
1377        return 0;
1378    }
1379
1380    Mutex::Autolock _l(mLock);
1381
1382    outHwDev = findSuitableHwDev_l(module, *pDevices);
1383    if (outHwDev == NULL)
1384        return 0;
1385
1386    audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1387    audio_io_handle_t id = nextUniqueId();
1388
1389    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1390
1391    status = hwDevHal->open_output_stream(hwDevHal,
1392                                          id,
1393                                          *pDevices,
1394                                          (audio_output_flags_t)flags,
1395                                          &config,
1396                                          &outStream);
1397
1398    mHardwareStatus = AUDIO_HW_IDLE;
1399    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
1400            "Channels %x, status %d",
1401            outStream,
1402            config.sample_rate,
1403            config.format,
1404            config.channel_mask,
1405            status);
1406
1407    if (status == NO_ERROR && outStream != NULL) {
1408        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
1409
1410        if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1411            (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
1412            (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
1413            thread = new DirectOutputThread(this, output, id, *pDevices);
1414            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
1415        } else {
1416            thread = new MixerThread(this, output, id, *pDevices);
1417            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
1418        }
1419        mPlaybackThreads.add(id, thread);
1420
1421        if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
1422        if (pFormat != NULL) *pFormat = config.format;
1423        if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
1424        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
1425
1426        // notify client processes of the new output creation
1427        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
1428
1429        // the first primary output opened designates the primary hw device
1430        if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
1431            ALOGI("Using module %d has the primary audio interface", module);
1432            mPrimaryHardwareDev = outHwDev;
1433
1434            AutoMutex lock(mHardwareLock);
1435            mHardwareStatus = AUDIO_HW_SET_MODE;
1436            hwDevHal->set_mode(hwDevHal, mMode);
1437            mHardwareStatus = AUDIO_HW_IDLE;
1438        }
1439        return id;
1440    }
1441
1442    return 0;
1443}
1444
1445audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1446        audio_io_handle_t output2)
1447{
1448    Mutex::Autolock _l(mLock);
1449    MixerThread *thread1 = checkMixerThread_l(output1);
1450    MixerThread *thread2 = checkMixerThread_l(output2);
1451
1452    if (thread1 == NULL || thread2 == NULL) {
1453        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1454                output2);
1455        return 0;
1456    }
1457
1458    audio_io_handle_t id = nextUniqueId();
1459    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
1460    thread->addOutputTrack(thread2);
1461    mPlaybackThreads.add(id, thread);
1462    // notify client processes of the new output creation
1463    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
1464    return id;
1465}
1466
1467status_t AudioFlinger::closeOutput(audio_io_handle_t output)
1468{
1469    return closeOutput_nonvirtual(output);
1470}
1471
1472status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1473{
1474    // keep strong reference on the playback thread so that
1475    // it is not destroyed while exit() is executed
1476    sp<PlaybackThread> thread;
1477    {
1478        Mutex::Autolock _l(mLock);
1479        thread = checkPlaybackThread_l(output);
1480        if (thread == NULL) {
1481            return BAD_VALUE;
1482        }
1483
1484        ALOGV("closeOutput() %d", output);
1485
1486        if (thread->type() == ThreadBase::MIXER) {
1487            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1488                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
1489                    DuplicatingThread *dupThread =
1490                            (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
1491                    dupThread->removeOutputTrack((MixerThread *)thread.get());
1492                }
1493            }
1494        }
1495        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
1496        mPlaybackThreads.removeItem(output);
1497    }
1498    thread->exit();
1499    // The thread entity (active unit of execution) is no longer running here,
1500    // but the ThreadBase container still exists.
1501
1502    if (thread->type() != ThreadBase::DUPLICATING) {
1503        AudioStreamOut *out = thread->clearOutput();
1504        ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1505        // from now on thread->mOutput is NULL
1506        out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1507        delete out;
1508    }
1509    return NO_ERROR;
1510}
1511
1512status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
1513{
1514    Mutex::Autolock _l(mLock);
1515    PlaybackThread *thread = checkPlaybackThread_l(output);
1516
1517    if (thread == NULL) {
1518        return BAD_VALUE;
1519    }
1520
1521    ALOGV("suspendOutput() %d", output);
1522    thread->suspend();
1523
1524    return NO_ERROR;
1525}
1526
1527status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
1528{
1529    Mutex::Autolock _l(mLock);
1530    PlaybackThread *thread = checkPlaybackThread_l(output);
1531
1532    if (thread == NULL) {
1533        return BAD_VALUE;
1534    }
1535
1536    ALOGV("restoreOutput() %d", output);
1537
1538    thread->restore();
1539
1540    return NO_ERROR;
1541}
1542
1543audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
1544                                          audio_devices_t *pDevices,
1545                                          uint32_t *pSamplingRate,
1546                                          audio_format_t *pFormat,
1547                                          audio_channel_mask_t *pChannelMask)
1548{
1549    status_t status;
1550    RecordThread *thread = NULL;
1551    struct audio_config config = {
1552        sample_rate: pSamplingRate ? *pSamplingRate : 0,
1553        channel_mask: pChannelMask ? *pChannelMask : 0,
1554        format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
1555    };
1556    uint32_t reqSamplingRate = config.sample_rate;
1557    audio_format_t reqFormat = config.format;
1558    audio_channel_mask_t reqChannels = config.channel_mask;
1559    audio_stream_in_t *inStream = NULL;
1560    AudioHwDevice *inHwDev;
1561
1562    if (pDevices == NULL || *pDevices == 0) {
1563        return 0;
1564    }
1565
1566    Mutex::Autolock _l(mLock);
1567
1568    inHwDev = findSuitableHwDev_l(module, *pDevices);
1569    if (inHwDev == NULL)
1570        return 0;
1571
1572    audio_hw_device_t *inHwHal = inHwDev->hwDevice();
1573    audio_io_handle_t id = nextUniqueId();
1574
1575    status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
1576                                        &inStream);
1577    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
1578            "status %d",
1579            inStream,
1580            config.sample_rate,
1581            config.format,
1582            config.channel_mask,
1583            status);
1584
1585    // If the input could not be opened with the requested parameters and we can handle the
1586    // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
1587    // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
1588    if (status == BAD_VALUE &&
1589        reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
1590        (config.sample_rate <= 2 * reqSamplingRate) &&
1591        (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
1592        ALOGV("openInput() reopening with proposed sampling rate and channel mask");
1593        inStream = NULL;
1594        status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
1595    }
1596
1597    if (status == NO_ERROR && inStream != NULL) {
1598
1599        // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
1600        // or (re-)create if current Pipe is idle and does not match the new format
1601        sp<NBAIO_Sink> teeSink;
1602#ifdef TEE_SINK_INPUT_FRAMES
1603        enum {
1604            TEE_SINK_NO,    // don't copy input
1605            TEE_SINK_NEW,   // copy input using a new pipe
1606            TEE_SINK_OLD,   // copy input using an existing pipe
1607        } kind;
1608        NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
1609                                        popcount(inStream->common.get_channels(&inStream->common)));
1610        if (format == Format_Invalid) {
1611            kind = TEE_SINK_NO;
1612        } else if (mRecordTeeSink == 0) {
1613            kind = TEE_SINK_NEW;
1614        } else if (mRecordTeeSink->getStrongCount() != 1) {
1615            kind = TEE_SINK_NO;
1616        } else if (format == mRecordTeeSink->format()) {
1617            kind = TEE_SINK_OLD;
1618        } else {
1619            kind = TEE_SINK_NEW;
1620        }
1621        switch (kind) {
1622        case TEE_SINK_NEW: {
1623            Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
1624            size_t numCounterOffers = 0;
1625            const NBAIO_Format offers[1] = {format};
1626            ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
1627            ALOG_ASSERT(index == 0);
1628            PipeReader *pipeReader = new PipeReader(*pipe);
1629            numCounterOffers = 0;
1630            index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
1631            ALOG_ASSERT(index == 0);
1632            mRecordTeeSink = pipe;
1633            mRecordTeeSource = pipeReader;
1634            teeSink = pipe;
1635            }
1636            break;
1637        case TEE_SINK_OLD:
1638            teeSink = mRecordTeeSink;
1639            break;
1640        case TEE_SINK_NO:
1641        default:
1642            break;
1643        }
1644#endif
1645        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
1646
1647        // Start record thread
1648        // RecorThread require both input and output device indication to forward to audio
1649        // pre processing modules
1650        audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
1651
1652        thread = new RecordThread(this,
1653                                  input,
1654                                  reqSamplingRate,
1655                                  reqChannels,
1656                                  id,
1657                                  device, teeSink);
1658        mRecordThreads.add(id, thread);
1659        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
1660        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
1661        if (pFormat != NULL) *pFormat = config.format;
1662        if (pChannelMask != NULL) *pChannelMask = reqChannels;
1663
1664        // notify client processes of the new input creation
1665        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
1666        return id;
1667    }
1668
1669    return 0;
1670}
1671
1672status_t AudioFlinger::closeInput(audio_io_handle_t input)
1673{
1674    return closeInput_nonvirtual(input);
1675}
1676
1677status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
1678{
1679    // keep strong reference on the record thread so that
1680    // it is not destroyed while exit() is executed
1681    sp<RecordThread> thread;
1682    {
1683        Mutex::Autolock _l(mLock);
1684        thread = checkRecordThread_l(input);
1685        if (thread == 0) {
1686            return BAD_VALUE;
1687        }
1688
1689        ALOGV("closeInput() %d", input);
1690        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
1691        mRecordThreads.removeItem(input);
1692    }
1693    thread->exit();
1694    // The thread entity (active unit of execution) is no longer running here,
1695    // but the ThreadBase container still exists.
1696
1697    AudioStreamIn *in = thread->clearInput();
1698    ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
1699    // from now on thread->mInput is NULL
1700    in->hwDev()->close_input_stream(in->hwDev(), in->stream);
1701    delete in;
1702
1703    return NO_ERROR;
1704}
1705
1706status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
1707{
1708    Mutex::Autolock _l(mLock);
1709    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
1710
1711    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1712        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
1713        thread->invalidateTracks(stream);
1714    }
1715
1716    return NO_ERROR;
1717}
1718
1719
1720int AudioFlinger::newAudioSessionId()
1721{
1722    return nextUniqueId();
1723}
1724
1725void AudioFlinger::acquireAudioSessionId(int audioSession)
1726{
1727    Mutex::Autolock _l(mLock);
1728    pid_t caller = IPCThreadState::self()->getCallingPid();
1729    ALOGV("acquiring %d from %d", audioSession, caller);
1730    size_t num = mAudioSessionRefs.size();
1731    for (size_t i = 0; i< num; i++) {
1732        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
1733        if (ref->mSessionid == audioSession && ref->mPid == caller) {
1734            ref->mCnt++;
1735            ALOGV(" incremented refcount to %d", ref->mCnt);
1736            return;
1737        }
1738    }
1739    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
1740    ALOGV(" added new entry for %d", audioSession);
1741}
1742
1743void AudioFlinger::releaseAudioSessionId(int audioSession)
1744{
1745    Mutex::Autolock _l(mLock);
1746    pid_t caller = IPCThreadState::self()->getCallingPid();
1747    ALOGV("releasing %d from %d", audioSession, caller);
1748    size_t num = mAudioSessionRefs.size();
1749    for (size_t i = 0; i< num; i++) {
1750        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1751        if (ref->mSessionid == audioSession && ref->mPid == caller) {
1752            ref->mCnt--;
1753            ALOGV(" decremented refcount to %d", ref->mCnt);
1754            if (ref->mCnt == 0) {
1755                mAudioSessionRefs.removeAt(i);
1756                delete ref;
1757                purgeStaleEffects_l();
1758            }
1759            return;
1760        }
1761    }
1762    ALOGW("session id %d not found for pid %d", audioSession, caller);
1763}
1764
1765void AudioFlinger::purgeStaleEffects_l() {
1766
1767    ALOGV("purging stale effects");
1768
1769    Vector< sp<EffectChain> > chains;
1770
1771    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1772        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
1773        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
1774            sp<EffectChain> ec = t->mEffectChains[j];
1775            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
1776                chains.push(ec);
1777            }
1778        }
1779    }
1780    for (size_t i = 0; i < mRecordThreads.size(); i++) {
1781        sp<RecordThread> t = mRecordThreads.valueAt(i);
1782        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
1783            sp<EffectChain> ec = t->mEffectChains[j];
1784            chains.push(ec);
1785        }
1786    }
1787
1788    for (size_t i = 0; i < chains.size(); i++) {
1789        sp<EffectChain> ec = chains[i];
1790        int sessionid = ec->sessionId();
1791        sp<ThreadBase> t = ec->mThread.promote();
1792        if (t == 0) {
1793            continue;
1794        }
1795        size_t numsessionrefs = mAudioSessionRefs.size();
1796        bool found = false;
1797        for (size_t k = 0; k < numsessionrefs; k++) {
1798            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
1799            if (ref->mSessionid == sessionid) {
1800                ALOGV(" session %d still exists for %d with %d refs",
1801                    sessionid, ref->mPid, ref->mCnt);
1802                found = true;
1803                break;
1804            }
1805        }
1806        if (!found) {
1807            Mutex::Autolock _l (t->mLock);
1808            // remove all effects from the chain
1809            while (ec->mEffects.size()) {
1810                sp<EffectModule> effect = ec->mEffects[0];
1811                effect->unPin();
1812                t->removeEffect_l(effect);
1813                if (effect->purgeHandles()) {
1814                    t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
1815                }
1816                AudioSystem::unregisterEffect(effect->id());
1817            }
1818        }
1819    }
1820    return;
1821}
1822
1823// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
1824AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
1825{
1826    return mPlaybackThreads.valueFor(output).get();
1827}
1828
1829// checkMixerThread_l() must be called with AudioFlinger::mLock held
1830AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
1831{
1832    PlaybackThread *thread = checkPlaybackThread_l(output);
1833    return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
1834}
1835
1836// checkRecordThread_l() must be called with AudioFlinger::mLock held
1837AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
1838{
1839    return mRecordThreads.valueFor(input).get();
1840}
1841
1842uint32_t AudioFlinger::nextUniqueId()
1843{
1844    return android_atomic_inc(&mNextUniqueId);
1845}
1846
1847AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
1848{
1849    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1850        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
1851        AudioStreamOut *output = thread->getOutput();
1852        if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
1853            return thread;
1854        }
1855    }
1856    return NULL;
1857}
1858
1859audio_devices_t AudioFlinger::primaryOutputDevice_l() const
1860{
1861    PlaybackThread *thread = primaryPlaybackThread_l();
1862
1863    if (thread == NULL) {
1864        return 0;
1865    }
1866
1867    return thread->outDevice();
1868}
1869
1870sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
1871                                    int triggerSession,
1872                                    int listenerSession,
1873                                    sync_event_callback_t callBack,
1874                                    void *cookie)
1875{
1876    Mutex::Autolock _l(mLock);
1877
1878    sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
1879    status_t playStatus = NAME_NOT_FOUND;
1880    status_t recStatus = NAME_NOT_FOUND;
1881    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1882        playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
1883        if (playStatus == NO_ERROR) {
1884            return event;
1885        }
1886    }
1887    for (size_t i = 0; i < mRecordThreads.size(); i++) {
1888        recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
1889        if (recStatus == NO_ERROR) {
1890            return event;
1891        }
1892    }
1893    if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
1894        mPendingSyncEvents.add(event);
1895    } else {
1896        ALOGV("createSyncEvent() invalid event %d", event->type());
1897        event.clear();
1898    }
1899    return event;
1900}
1901
1902// ----------------------------------------------------------------------------
1903//  Effect management
1904// ----------------------------------------------------------------------------
1905
1906
1907status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
1908{
1909    Mutex::Autolock _l(mLock);
1910    return EffectQueryNumberEffects(numEffects);
1911}
1912
1913status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
1914{
1915    Mutex::Autolock _l(mLock);
1916    return EffectQueryEffect(index, descriptor);
1917}
1918
1919status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
1920        effect_descriptor_t *descriptor) const
1921{
1922    Mutex::Autolock _l(mLock);
1923    return EffectGetDescriptor(pUuid, descriptor);
1924}
1925
1926
1927sp<IEffect> AudioFlinger::createEffect(
1928        effect_descriptor_t *pDesc,
1929        const sp<IEffectClient>& effectClient,
1930        int32_t priority,
1931        audio_io_handle_t io,
1932        int sessionId,
1933        status_t *status,
1934        int *id,
1935        int *enabled)
1936{
1937    status_t lStatus = NO_ERROR;
1938    sp<EffectHandle> handle;
1939    effect_descriptor_t desc;
1940
1941    pid_t pid = IPCThreadState::self()->getCallingPid();
1942    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
1943            pid, effectClient.get(), priority, sessionId, io);
1944
1945    if (pDesc == NULL) {
1946        lStatus = BAD_VALUE;
1947        goto Exit;
1948    }
1949
1950    // check audio settings permission for global effects
1951    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
1952        lStatus = PERMISSION_DENIED;
1953        goto Exit;
1954    }
1955
1956    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
1957    // that can only be created by audio policy manager (running in same process)
1958    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
1959        lStatus = PERMISSION_DENIED;
1960        goto Exit;
1961    }
1962
1963    if (io == 0) {
1964        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1965            // output must be specified by AudioPolicyManager when using session
1966            // AUDIO_SESSION_OUTPUT_STAGE
1967            lStatus = BAD_VALUE;
1968            goto Exit;
1969        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1970            // if the output returned by getOutputForEffect() is removed before we lock the
1971            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
1972            // and we will exit safely
1973            io = AudioSystem::getOutputForEffect(&desc);
1974        }
1975    }
1976
1977    {
1978        Mutex::Autolock _l(mLock);
1979
1980
1981        if (!EffectIsNullUuid(&pDesc->uuid)) {
1982            // if uuid is specified, request effect descriptor
1983            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
1984            if (lStatus < 0) {
1985                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
1986                goto Exit;
1987            }
1988        } else {
1989            // if uuid is not specified, look for an available implementation
1990            // of the required type in effect factory
1991            if (EffectIsNullUuid(&pDesc->type)) {
1992                ALOGW("createEffect() no effect type");
1993                lStatus = BAD_VALUE;
1994                goto Exit;
1995            }
1996            uint32_t numEffects = 0;
1997            effect_descriptor_t d;
1998            d.flags = 0; // prevent compiler warning
1999            bool found = false;
2000
2001            lStatus = EffectQueryNumberEffects(&numEffects);
2002            if (lStatus < 0) {
2003                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
2004                goto Exit;
2005            }
2006            for (uint32_t i = 0; i < numEffects; i++) {
2007                lStatus = EffectQueryEffect(i, &desc);
2008                if (lStatus < 0) {
2009                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
2010                    continue;
2011                }
2012                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2013                    // If matching type found save effect descriptor. If the session is
2014                    // 0 and the effect is not auxiliary, continue enumeration in case
2015                    // an auxiliary version of this effect type is available
2016                    found = true;
2017                    d = desc;
2018                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
2019                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2020                        break;
2021                    }
2022                }
2023            }
2024            if (!found) {
2025                lStatus = BAD_VALUE;
2026                ALOGW("createEffect() effect not found");
2027                goto Exit;
2028            }
2029            // For same effect type, chose auxiliary version over insert version if
2030            // connect to output mix (Compliance to OpenSL ES)
2031            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
2032                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
2033                desc = d;
2034            }
2035        }
2036
2037        // Do not allow auxiliary effects on a session different from 0 (output mix)
2038        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
2039             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2040            lStatus = INVALID_OPERATION;
2041            goto Exit;
2042        }
2043
2044        // check recording permission for visualizer
2045        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
2046            !recordingAllowed()) {
2047            lStatus = PERMISSION_DENIED;
2048            goto Exit;
2049        }
2050
2051        // return effect descriptor
2052        *pDesc = desc;
2053
2054        // If output is not specified try to find a matching audio session ID in one of the
2055        // output threads.
2056        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2057        // because of code checking output when entering the function.
2058        // Note: io is never 0 when creating an effect on an input
2059        if (io == 0) {
2060            // look for the thread where the specified audio session is present
2061            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2062                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2063                    io = mPlaybackThreads.keyAt(i);
2064                    break;
2065                }
2066            }
2067            if (io == 0) {
2068                for (size_t i = 0; i < mRecordThreads.size(); i++) {
2069                    if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2070                        io = mRecordThreads.keyAt(i);
2071                        break;
2072                    }
2073                }
2074            }
2075            // If no output thread contains the requested session ID, default to
2076            // first output. The effect chain will be moved to the correct output
2077            // thread when a track with the same session ID is created
2078            if (io == 0 && mPlaybackThreads.size()) {
2079                io = mPlaybackThreads.keyAt(0);
2080            }
2081            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
2082        }
2083        ThreadBase *thread = checkRecordThread_l(io);
2084        if (thread == NULL) {
2085            thread = checkPlaybackThread_l(io);
2086            if (thread == NULL) {
2087                ALOGE("createEffect() unknown output thread");
2088                lStatus = BAD_VALUE;
2089                goto Exit;
2090            }
2091        }
2092
2093        sp<Client> client = registerPid_l(pid);
2094
2095        // create effect on selected output thread
2096        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2097                &desc, enabled, &lStatus);
2098        if (handle != 0 && id != NULL) {
2099            *id = handle->id();
2100        }
2101    }
2102
2103Exit:
2104    if (status != NULL) {
2105        *status = lStatus;
2106    }
2107    return handle;
2108}
2109
2110status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2111        audio_io_handle_t dstOutput)
2112{
2113    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
2114            sessionId, srcOutput, dstOutput);
2115    Mutex::Autolock _l(mLock);
2116    if (srcOutput == dstOutput) {
2117        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
2118        return NO_ERROR;
2119    }
2120    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2121    if (srcThread == NULL) {
2122        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
2123        return BAD_VALUE;
2124    }
2125    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2126    if (dstThread == NULL) {
2127        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
2128        return BAD_VALUE;
2129    }
2130
2131    Mutex::Autolock _dl(dstThread->mLock);
2132    Mutex::Autolock _sl(srcThread->mLock);
2133    moveEffectChain_l(sessionId, srcThread, dstThread, false);
2134
2135    return NO_ERROR;
2136}
2137
2138// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
2139status_t AudioFlinger::moveEffectChain_l(int sessionId,
2140                                   AudioFlinger::PlaybackThread *srcThread,
2141                                   AudioFlinger::PlaybackThread *dstThread,
2142                                   bool reRegister)
2143{
2144    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
2145            sessionId, srcThread, dstThread);
2146
2147    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
2148    if (chain == 0) {
2149        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
2150                sessionId, srcThread);
2151        return INVALID_OPERATION;
2152    }
2153
2154    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
2155    // so that a new chain is created with correct parameters when first effect is added. This is
2156    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
2157    // removed.
2158    srcThread->removeEffectChain_l(chain);
2159
2160    // transfer all effects one by one so that new effect chain is created on new thread with
2161    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
2162    audio_io_handle_t dstOutput = dstThread->id();
2163    sp<EffectChain> dstChain;
2164    uint32_t strategy = 0; // prevent compiler warning
2165    sp<EffectModule> effect = chain->getEffectFromId_l(0);
2166    while (effect != 0) {
2167        srcThread->removeEffect_l(effect);
2168        dstThread->addEffect_l(effect);
2169        // removeEffect_l() has stopped the effect if it was active so it must be restarted
2170        if (effect->state() == EffectModule::ACTIVE ||
2171                effect->state() == EffectModule::STOPPING) {
2172            effect->start();
2173        }
2174        // if the move request is not received from audio policy manager, the effect must be
2175        // re-registered with the new strategy and output
2176        if (dstChain == 0) {
2177            dstChain = effect->chain().promote();
2178            if (dstChain == 0) {
2179                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
2180                srcThread->addEffect_l(effect);
2181                return NO_INIT;
2182            }
2183            strategy = dstChain->strategy();
2184        }
2185        if (reRegister) {
2186            AudioSystem::unregisterEffect(effect->id());
2187            AudioSystem::registerEffect(&effect->desc(),
2188                                        dstOutput,
2189                                        strategy,
2190                                        sessionId,
2191                                        effect->id());
2192        }
2193        effect = chain->getEffectFromId_l(0);
2194    }
2195
2196    return NO_ERROR;
2197}
2198
2199void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
2200{
2201    NBAIO_Source *teeSource = source.get();
2202    if (teeSource != NULL) {
2203        char teeTime[16];
2204        struct timeval tv;
2205        gettimeofday(&tv, NULL);
2206        struct tm tm;
2207        localtime_r(&tv.tv_sec, &tm);
2208        strftime(teeTime, sizeof(teeTime), "%T", &tm);
2209        char teePath[64];
2210        sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
2211        int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
2212        if (teeFd >= 0) {
2213            char wavHeader[44];
2214            memcpy(wavHeader,
2215                "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",
2216                sizeof(wavHeader));
2217            NBAIO_Format format = teeSource->format();
2218            unsigned channelCount = Format_channelCount(format);
2219            ALOG_ASSERT(channelCount <= FCC_2);
2220            uint32_t sampleRate = Format_sampleRate(format);
2221            wavHeader[22] = channelCount;       // number of channels
2222            wavHeader[24] = sampleRate;         // sample rate
2223            wavHeader[25] = sampleRate >> 8;
2224            wavHeader[32] = channelCount * 2;   // block alignment
2225            write(teeFd, wavHeader, sizeof(wavHeader));
2226            size_t total = 0;
2227            bool firstRead = true;
2228            for (;;) {
2229#define TEE_SINK_READ 1024
2230                short buffer[TEE_SINK_READ * FCC_2];
2231                size_t count = TEE_SINK_READ;
2232                ssize_t actual = teeSource->read(buffer, count,
2233                        AudioBufferProvider::kInvalidPTS);
2234                bool wasFirstRead = firstRead;
2235                firstRead = false;
2236                if (actual <= 0) {
2237                    if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2238                        continue;
2239                    }
2240                    break;
2241                }
2242                ALOG_ASSERT(actual <= (ssize_t)count);
2243                write(teeFd, buffer, actual * channelCount * sizeof(short));
2244                total += actual;
2245            }
2246            lseek(teeFd, (off_t) 4, SEEK_SET);
2247            uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
2248            write(teeFd, &temp, sizeof(temp));
2249            lseek(teeFd, (off_t) 40, SEEK_SET);
2250            temp =  total * channelCount * sizeof(short);
2251            write(teeFd, &temp, sizeof(temp));
2252            close(teeFd);
2253            fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
2254        } else {
2255            fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
2256        }
2257    }
2258}
2259
2260// ----------------------------------------------------------------------------
2261
2262status_t AudioFlinger::onTransact(
2263        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2264{
2265    return BnAudioFlinger::onTransact(code, data, reply, flags);
2266}
2267
2268}; // namespace android
2269