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