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