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