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