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