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