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