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