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