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