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