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