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