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