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