blob: 1b39e2288ffc92478c22fa6c36848026fe046a0b [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
Dima Zavinfce7a472011-04-19 22:30:36 -070044#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Mathias Agopian65ab4712010-07-14 17:59:35 -070073// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
John Grossman1c345192012-03-27 14:00:17 -070075// Note: the following macro is used for extremely verbose logging message. In
76// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
77// 0; but one side effect of this is to turn all LOGV's as well. Some messages
78// are so verbose that we want to suppress them even when we have ALOG_ASSERT
79// turned on. Do not uncomment the #def below unless you really know what you
80// are doing and want to see all of the extremely verbose messages.
81//#define VERY_VERY_VERBOSE_LOGGING
82#ifdef VERY_VERY_VERBOSE_LOGGING
83#define ALOGVV ALOGV
84#else
85#define ALOGVV(a...) do { } while(0)
86#endif
Eric Laurentde070132010-07-13 04:45:46 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088namespace android {
89
Glenn Kastenec1d6b52011-12-12 09:04:45 -080090static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
91static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070092static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070093static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Glenn Kasten58912562012-04-03 10:45:00 -070095
John Grossman4ff14ba2012-02-08 16:37:41 -080096nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070099
Glenn Kasten46909e72013-02-26 09:20:22 -0800100#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800101bool AudioFlinger::mTeeSinkInputEnabled = false;
102bool AudioFlinger::mTeeSinkOutputEnabled = false;
103bool AudioFlinger::mTeeSinkTrackEnabled = false;
104
105size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
106size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
107size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800108#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800109
Eric Laurent813e2a72013-08-31 12:59:48 -0700110// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
111// we define a minimum time during which a global effect is considered enabled.
112static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700116std::string formatToString(audio_format_t format) {
117 std::string result;
118 FormatConverter::toString(format, result);
119 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800120}
121
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122// ----------------------------------------------------------------------------
123
124AudioFlinger::AudioFlinger()
125 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800126 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800127 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700128 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800129 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800130 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700131 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800132 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700133 mBtNrecIsOff(false),
134 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700135 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700136 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700137 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700138{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700139 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
140 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
141 // zero ID has a special meaning, so unavailable
142 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
143 }
144
Glenn Kasten949a9262013-04-16 12:35:20 -0700145 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800146 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800147 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800148 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
149 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800150 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700151
Wei Jia3f273d12015-11-24 09:06:49 -0800152 // reset battery stats.
153 // if the audio service has crashed, battery stats could be left
154 // in bad state, reset the state upon service start.
155 BatteryNotifier::getInstance().noteResetAudio();
156
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700157 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700158 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
159
Glenn Kasten46909e72013-02-26 09:20:22 -0800160#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800161 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800162 (void) property_get("ro.debuggable", value, "0");
163 int debuggable = atoi(value);
164 int teeEnabled = 0;
165 if (debuggable) {
166 (void) property_get("af.tee", value, "0");
167 teeEnabled = atoi(value);
168 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800169 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700170 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800171 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700172 }
173 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800174 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700175 }
176 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800177 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700178 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800179#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700180}
181
182void AudioFlinger::onFirstRef()
183{
Eric Laurent93575202011-01-18 18:39:02 -0800184 Mutex::Autolock _l(mLock);
185
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800187 char val_str[PROPERTY_VALUE_MAX] = { 0 };
188 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
189 uint32_t int_val;
190 if (1 == sscanf(val_str, "%u", &int_val)) {
191 mStandbyTimeInNsecs = milliseconds(int_val);
192 ALOGI("Using %u mSec as standby time.", int_val);
193 } else {
194 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
195 ALOGI("Using default %u mSec as standby time.",
196 (uint32_t)(mStandbyTimeInNsecs / 1000000));
197 }
198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700199
Eric Laurent1c333e22014-05-20 10:48:17 -0700200 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700201
Eric Laurenta4c5a552012-03-29 10:12:40 -0700202 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700203}
204
205AudioFlinger::~AudioFlinger()
206{
207 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700208 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700209 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
211 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700212 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700213 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700214 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700215
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800216 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
217 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700218 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700220
221 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800222 if (mLogMemoryDealer != 0) {
223 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
224 if (binder != 0) {
225 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
226 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
227 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
228 mUnregisteredWriters.pop();
229 mediaLogService->unregisterWriter(iMemory);
230 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700231 }
232 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233}
234
Eric Laurenta4c5a552012-03-29 10:12:40 -0700235static const char * const audio_interfaces[] = {
236 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
237 AUDIO_HARDWARE_MODULE_ID_A2DP,
238 AUDIO_HARDWARE_MODULE_ID_USB,
239};
240#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
241
Phil Burk062e67a2015-02-11 13:40:50 -0800242AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700243 audio_module_handle_t module,
244 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700245{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 // if module is 0, the request comes from an old policy manager and we should load
247 // well known modules
248 if (module == 0) {
249 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
250 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
251 loadHwModule_l(audio_interfaces[i]);
252 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700253 // then try to find a module supporting the requested device.
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700256 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
257 uint32_t supportedDevices;
258 if (dev->getSupportedDevices(&supportedDevices) == OK &&
259 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700260 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700261 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700262 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700263 } else {
264 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700265 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
266 if (audioHwDevice != NULL) {
267 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700268 }
269 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700270
Dima Zavin799a70e2011-04-18 16:57:27 -0700271 return NULL;
272}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273
Glenn Kasten0f11b512014-01-31 16:18:54 -0800274void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275{
276 const size_t SIZE = 256;
277 char buffer[SIZE];
278 String8 result;
279
280 result.append("Clients:\n");
281 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800282 sp<Client> client = mClients.valueAt(i).promote();
283 if (client != 0) {
284 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
285 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700286 }
287 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700288
Eric Laurentd1b28d42013-09-18 18:47:13 -0700289 result.append("Notification Clients:\n");
290 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
291 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
292 result.append(buffer);
293 }
294
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700295 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800296 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700297 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
298 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800299 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700300 result.append(buffer);
301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303}
304
305
Glenn Kasten0f11b512014-01-31 16:18:54 -0800306void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700307{
308 const size_t SIZE = 256;
309 char buffer[SIZE];
310 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800311 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
John Grossman4ff14ba2012-02-08 16:37:41 -0800313 snprintf(buffer, SIZE, "Hardware status: %d\n"
314 "Standby Time mSec: %u\n",
315 hardwareStatus,
316 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700317 result.append(buffer);
318 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319}
320
Glenn Kasten0f11b512014-01-31 16:18:54 -0800321void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700322{
323 const size_t SIZE = 256;
324 char buffer[SIZE];
325 String8 result;
326 snprintf(buffer, SIZE, "Permission Denial: "
327 "can't dump AudioFlinger from pid=%d, uid=%d\n",
328 IPCThreadState::self()->getCallingPid(),
329 IPCThreadState::self()->getCallingUid());
330 result.append(buffer);
331 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332}
333
Eric Laurent81784c32012-11-19 14:55:58 -0800334bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335{
336 bool locked = false;
337 for (int i = 0; i < kDumpLockRetries; ++i) {
338 if (mutex.tryLock() == NO_ERROR) {
339 locked = true;
340 break;
341 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800342 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700343 }
344 return locked;
345}
346
347status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
348{
Glenn Kasten44deb052012-02-05 18:09:08 -0800349 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 dumpPermissionDenial(fd, args);
351 } else {
352 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800353 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354 if (!hardwareLocked) {
355 String8 result(kHardwareLockedString);
356 write(fd, result.string(), result.size());
357 } else {
358 mHardwareLock.unlock();
359 }
360
Eric Laurent81784c32012-11-19 14:55:58 -0800361 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362
363 // failed to lock - AudioFlinger is probably deadlocked
364 if (!locked) {
365 String8 result(kDeadlockedString);
366 write(fd, result.string(), result.size());
367 }
368
Eric Laurent021cf962014-05-13 10:18:14 -0700369 bool clientLocked = dumpTryLock(mClientLock);
370 if (!clientLocked) {
371 String8 result(kClientLockedString);
372 write(fd, result.string(), result.size());
373 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700374
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700375 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700376 mEffectsFactoryHal->dumpEffects(fd);
377 } else {
378 String8 result(kNoEffectsFactory);
379 write(fd, result.string(), result.size());
380 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700381
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700383 if (clientLocked) {
384 mClientLock.unlock();
385 }
386
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 dumpInternals(fd, args);
388
389 // dump playback threads
390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
391 mPlaybackThreads.valueAt(i)->dump(fd, args);
392 }
393
394 // dump record threads
395 for (size_t i = 0; i < mRecordThreads.size(); i++) {
396 mRecordThreads.valueAt(i)->dump(fd, args);
397 }
398
Eric Laurentaaa44472014-09-12 17:41:50 -0700399 // dump orphan effect chains
400 if (mOrphanEffectChains.size() != 0) {
401 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
402 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
403 mOrphanEffectChains.valueAt(i)->dump(fd, args);
404 }
405 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 // dump all hardware devs
407 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700408 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
409 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700411
Glenn Kasten46909e72013-02-26 09:20:22 -0800412#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700413 // dump the serially shared record tee sink
414 if (mRecordTeeSource != 0) {
415 dumpTee(fd, mRecordTeeSource);
416 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800417#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700418
rago3bd1c872016-09-26 12:58:14 -0700419 BUFLOG_RESET;
420
Glenn Kastend65d73c2012-06-22 17:21:07 -0700421 if (locked) {
422 mLock.unlock();
423 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800424
425 // append a copy of media.log here by forwarding fd to it, but don't attempt
426 // to lookup the service if it's not running, as it will block for a second
427 if (mLogMemoryDealer != 0) {
428 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
429 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700430 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800431 Vector<String16> args;
432 binder->dump(fd, args);
433 }
434 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700435
436 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700437 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700438 bool unreachableMemory = false;
439 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700440 if (arg == String16("-m")) {
441 dumpMem = true;
442 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700443 unreachableMemory = true;
444 }
445 }
446
Andy Hung07b745e2016-05-23 16:21:07 -0700447 if (dumpMem) {
448 dprintf(fd, "\nDumping memory:\n");
449 std::string s = dumpMemoryAddresses(100 /* limit */);
450 write(fd, s.c_str(), s.size());
451 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700452 if (unreachableMemory) {
453 dprintf(fd, "\nDumping unreachable memory:\n");
454 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700455 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700456 write(fd, s.c_str(), s.size());
457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 }
459 return NO_ERROR;
460}
461
Eric Laurent021cf962014-05-13 10:18:14 -0700462sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800463{
Eric Laurent021cf962014-05-13 10:18:14 -0700464 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800465 // If pid is already in the mClients wp<> map, then use that entry
466 // (for which promote() is always != 0), otherwise create a new entry and Client.
467 sp<Client> client = mClients.valueFor(pid).promote();
468 if (client == 0) {
469 client = new Client(this, pid);
470 mClients.add(pid, client);
471 }
472
473 return client;
474}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475
Glenn Kasten9e58b552013-01-18 15:09:48 -0800476sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
477{
Glenn Kasten481fb672013-09-30 14:39:28 -0700478 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800479 if (mLogMemoryDealer == 0) {
480 return new NBLog::Writer();
481 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800482 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700483 // Similarly if we can't contact the media.log service, also return a dummy writer
484 if (binder == 0) {
485 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800486 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700487 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
488 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
489 // If allocation fails, consult the vector of previously unregistered writers
490 // and garbage-collect one or more them until an allocation succeeds
491 if (shared == 0) {
492 Mutex::Autolock _l(mUnregisteredWritersLock);
493 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
494 {
495 // Pick the oldest stale writer to garbage-collect
496 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
497 mUnregisteredWriters.removeAt(0);
498 mediaLogService->unregisterWriter(iMemory);
499 // Now the media.log remote reference to IMemory is gone. When our last local
500 // reference to IMemory also drops to zero at end of this block,
501 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
502 }
503 // Re-attempt the allocation
504 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
505 if (shared != 0) {
506 goto success;
507 }
508 }
509 // Even after garbage-collecting all old writers, there is still not enough memory,
510 // so return a dummy writer
511 return new NBLog::Writer();
512 }
513success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800514 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
515 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
516 // explicit destructor not needed since it is POD
Glenn Kasten481fb672013-09-30 14:39:28 -0700517 mediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800518 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800519}
520
521void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
522{
Glenn Kasten685ef092013-02-04 08:15:34 -0800523 if (writer == 0) {
524 return;
525 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800526 sp<IMemory> iMemory(writer->getIMemory());
527 if (iMemory == 0) {
528 return;
529 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700530 // Rather than removing the writer immediately, append it to a queue of old writers to
531 // be garbage-collected later. This allows us to continue to view old logs for a while.
532 Mutex::Autolock _l(mUnregisteredWritersLock);
533 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800534}
535
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536// IAudioFlinger interface
537
538
539sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800540 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800542 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700543 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800544 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700545 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700548 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800549 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800550 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800551 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800552 status_t *status,
553 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554{
555 sp<PlaybackThread::Track> track;
556 sp<TrackHandle> trackHandle;
557 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800559 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700561 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
562 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
563 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
564 ALOGW_IF(pid != -1 && pid != callingPid,
565 "%s uid %d pid %d tried to pass itself off as pid %d",
566 __func__, callingUid, callingPid, pid);
567 pid = callingPid;
568 }
569
Glenn Kasten263709e2012-01-06 08:40:01 -0800570 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
571 // but if someone uses binder directly they could bypass that and cause us to crash
572 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000573 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 lStatus = BAD_VALUE;
575 goto Exit;
576 }
577
Glenn Kasten53b5d092014-02-05 10:00:23 -0800578 // further sample rate checks are performed by createTrack_l() depending on the thread type
579 if (sampleRate == 0) {
580 ALOGE("createTrack() invalid sample rate %u", sampleRate);
581 lStatus = BAD_VALUE;
582 goto Exit;
583 }
584
585 // further channel mask checks are performed by createTrack_l() depending on the thread type
586 if (!audio_is_output_channel(channelMask)) {
587 ALOGE("createTrack() invalid channel mask %#x", channelMask);
588 lStatus = BAD_VALUE;
589 goto Exit;
590 }
591
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700592 // further format checks are performed by createTrack_l() depending on the thread type
593 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800594 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700595 lStatus = BAD_VALUE;
596 goto Exit;
597 }
598
Glenn Kasten663c2242013-09-24 11:52:37 -0700599 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
600 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
601 lStatus = BAD_VALUE;
602 goto Exit;
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 {
606 Mutex::Autolock _l(mLock);
607 PlaybackThread *thread = checkPlaybackThread_l(output);
608 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800609 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 lStatus = BAD_VALUE;
611 goto Exit;
612 }
613
Eric Laurent021cf962014-05-13 10:18:14 -0700614 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615
Glenn Kastene848bd92014-03-13 15:00:32 -0700616 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700617 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800618 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
619 ALOGE("createTrack() invalid session ID %d", *sessionId);
620 lStatus = BAD_VALUE;
621 goto Exit;
622 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700623 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700624 // check if an effect chain with the same session ID is present on another
625 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700626 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700627 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
628 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700629 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700630 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700631 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700632 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700633 }
Eric Laurentde070132010-07-13 04:45:46 -0700634 }
635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700637 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800638 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639 if (sessionId != NULL) {
640 *sessionId = lSessionId;
641 }
642 }
Steve Block3856b092011-10-20 11:56:00 +0100643 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644
645 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800646 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
647 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800648 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700649 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700650
651 // move effect chain to this output thread if an effect on same session was waiting
652 // for a track to be created
653 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700654 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700655 Mutex::Autolock _dl(thread->mLock);
656 Mutex::Autolock _sl(effectThread->mLock);
657 moveEffectChain_l(lSessionId, effectThread, thread, true);
658 }
Eric Laurenta011e352012-03-29 15:51:43 -0700659
660 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700661 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700662 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
663 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700664 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700665 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700666 } else {
667 mPendingSyncEvents[i]->cancel();
668 }
Eric Laurenta011e352012-03-29 15:51:43 -0700669 mPendingSyncEvents.removeAt(i);
670 i--;
671 }
672 }
673 }
Glenn Kastene198c362013-08-13 09:13:36 -0700674
Glenn Kastend848eb42016-03-08 13:42:11 -0800675 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 }
Glenn Kastene198c362013-08-13 09:13:36 -0700677
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700678 if (lStatus != NO_ERROR) {
679 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700680 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700681 // Don't hold mClientLock when releasing the reference on the track as the
682 // destructor will acquire it.
683 {
684 Mutex::Autolock _cl(mClientLock);
685 client.clear();
686 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700687 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700688 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 }
690
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700691 // return handle to client
692 trackHandle = new TrackHandle(track);
693
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700695 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 return trackHandle;
697}
698
Glenn Kasten2c073da2016-02-26 09:14:08 -0800699uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700{
701 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800702 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800704 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 return 0;
706 }
707 return thread->sampleRate();
708}
709
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800710audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711{
712 Mutex::Autolock _l(mLock);
713 PlaybackThread *thread = checkPlaybackThread_l(output);
714 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000715 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800716 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 }
718 return thread->format();
719}
720
Glenn Kasten2c073da2016-02-26 09:14:08 -0800721size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722{
723 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800724 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800726 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 return 0;
728 }
Glenn Kasten58912562012-04-03 10:45:00 -0700729 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
730 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 return thread->frameCount();
732}
733
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700734size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
735{
736 Mutex::Autolock _l(mLock);
737 ThreadBase *thread = checkThread_l(ioHandle);
738 if (thread == NULL) {
739 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
740 return 0;
741 }
742 return thread->frameCountHAL();
743}
744
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800745uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746{
747 Mutex::Autolock _l(mLock);
748 PlaybackThread *thread = checkPlaybackThread_l(output);
749 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800750 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 return 0;
752 }
753 return thread->latency();
754}
755
756status_t AudioFlinger::setMasterVolume(float value)
757{
Eric Laurenta1884f92011-08-23 08:25:03 -0700758 status_t ret = initCheck();
759 if (ret != NO_ERROR) {
760 return ret;
761 }
762
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 // check calling permissions
764 if (!settingsAllowed()) {
765 return PERMISSION_DENIED;
766 }
767
Eric Laurenta4c5a552012-03-29 10:12:40 -0700768 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700769 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700770
John Grossmanee578c02012-07-23 17:05:46 -0700771 // Set master volume in the HALs which support it.
772 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
773 AutoMutex lock(mHardwareLock);
774 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800775
John Grossmanee578c02012-07-23 17:05:46 -0700776 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
777 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700778 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800779 }
John Grossmanee578c02012-07-23 17:05:46 -0700780 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782
John Grossmanee578c02012-07-23 17:05:46 -0700783 // Now set the master volume in each playback thread. Playback threads
784 // assigned to HALs which do not have master volume support will apply
785 // master volume during the mix operation. Threads with HALs which do
786 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700787 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
788 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
789 continue;
790 }
John Grossmanee578c02012-07-23 17:05:46 -0700791 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793
794 return NO_ERROR;
795}
796
Glenn Kastenf78aee72012-01-04 11:00:47 -0800797status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798{
Eric Laurenta1884f92011-08-23 08:25:03 -0700799 status_t ret = initCheck();
800 if (ret != NO_ERROR) {
801 return ret;
802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803
804 // check calling permissions
805 if (!settingsAllowed()) {
806 return PERMISSION_DENIED;
807 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800808 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000809 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 return BAD_VALUE;
811 }
812
813 { // scope for the lock
814 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700815 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700817 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 mHardwareStatus = AUDIO_HW_IDLE;
819 }
820
821 if (NO_ERROR == ret) {
822 Mutex::Autolock _l(mLock);
823 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800824 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700825 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 }
827
828 return ret;
829}
830
831status_t AudioFlinger::setMicMute(bool state)
832{
Eric Laurenta1884f92011-08-23 08:25:03 -0700833 status_t ret = initCheck();
834 if (ret != NO_ERROR) {
835 return ret;
836 }
837
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 // check calling permissions
839 if (!settingsAllowed()) {
840 return PERMISSION_DENIED;
841 }
842
843 AutoMutex lock(mHardwareLock);
844 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700845 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700846 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
847 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700848 if (result != NO_ERROR) {
849 ret = result;
850 }
851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 mHardwareStatus = AUDIO_HW_IDLE;
853 return ret;
854}
855
856bool AudioFlinger::getMicMute() const
857{
Eric Laurenta1884f92011-08-23 08:25:03 -0700858 status_t ret = initCheck();
859 if (ret != NO_ERROR) {
860 return false;
861 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800862 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700863 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800864 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800866 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700867 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
868 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800869 if (result == NO_ERROR) {
870 mute = mute && state;
871 }
872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800874
875 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876}
877
878status_t AudioFlinger::setMasterMute(bool muted)
879{
John Grossmand8f178d2012-07-20 14:51:35 -0700880 status_t ret = initCheck();
881 if (ret != NO_ERROR) {
882 return ret;
883 }
884
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 // check calling permissions
886 if (!settingsAllowed()) {
887 return PERMISSION_DENIED;
888 }
889
John Grossmanee578c02012-07-23 17:05:46 -0700890 Mutex::Autolock _l(mLock);
891 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700892
John Grossmanee578c02012-07-23 17:05:46 -0700893 // Set master mute in the HALs which support it.
894 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
895 AutoMutex lock(mHardwareLock);
896 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700897
John Grossmanee578c02012-07-23 17:05:46 -0700898 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
899 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700900 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700901 }
John Grossmanee578c02012-07-23 17:05:46 -0700902 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700903 }
904
John Grossmanee578c02012-07-23 17:05:46 -0700905 // Now set the master mute in each playback thread. Playback threads
906 // assigned to HALs which do not have master mute support will apply master
907 // mute during the mix operation. Threads with HALs which do support master
908 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700909 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
910 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
911 continue;
912 }
John Grossmanee578c02012-07-23 17:05:46 -0700913 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700914 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915
916 return NO_ERROR;
917}
918
919float AudioFlinger::masterVolume() const
920{
Glenn Kasten98067102011-12-13 11:47:54 -0800921 Mutex::Autolock _l(mLock);
922 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923}
924
925bool AudioFlinger::masterMute() const
926{
Glenn Kasten98067102011-12-13 11:47:54 -0800927 Mutex::Autolock _l(mLock);
928 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929}
930
John Grossman4ff14ba2012-02-08 16:37:41 -0800931float AudioFlinger::masterVolume_l() const
932{
John Grossman4ff14ba2012-02-08 16:37:41 -0800933 return mMasterVolume;
934}
935
John Grossmand8f178d2012-07-20 14:51:35 -0700936bool AudioFlinger::masterMute_l() const
937{
John Grossmanee578c02012-07-23 17:05:46 -0700938 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700939}
940
Eric Laurent223fd5c2014-11-11 13:43:36 -0800941status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
942{
943 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
944 ALOGW("setStreamVolume() invalid stream %d", stream);
945 return BAD_VALUE;
946 }
947 pid_t caller = IPCThreadState::self()->getCallingPid();
948 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
949 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
950 return PERMISSION_DENIED;
951 }
952
953 return NO_ERROR;
954}
955
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800956status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
957 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958{
959 // check calling permissions
960 if (!settingsAllowed()) {
961 return PERMISSION_DENIED;
962 }
963
Eric Laurent223fd5c2014-11-11 13:43:36 -0800964 status_t status = checkStreamType(stream);
965 if (status != NO_ERROR) {
966 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800968 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969
970 AutoMutex lock(mLock);
971 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700972 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 thread = checkPlaybackThread_l(output);
974 if (thread == NULL) {
975 return BAD_VALUE;
976 }
977 }
978
979 mStreamTypes[stream].volume = value;
980
981 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800982 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700983 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 }
985 } else {
986 thread->setStreamVolume(stream, value);
987 }
988
989 return NO_ERROR;
990}
991
Glenn Kastenfff6d712012-01-12 16:38:12 -0800992status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
994 // check calling permissions
995 if (!settingsAllowed()) {
996 return PERMISSION_DENIED;
997 }
998
Eric Laurent223fd5c2014-11-11 13:43:36 -0800999 status_t status = checkStreamType(stream);
1000 if (status != NO_ERROR) {
1001 return status;
1002 }
1003 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1004
1005 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001006 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 return BAD_VALUE;
1008 }
1009
Eric Laurent93575202011-01-18 18:39:02 -08001010 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001012 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001013 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014
1015 return NO_ERROR;
1016}
1017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001018float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001020 status_t status = checkStreamType(stream);
1021 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 return 0.0f;
1023 }
1024
1025 AutoMutex lock(mLock);
1026 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001027 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 PlaybackThread *thread = checkPlaybackThread_l(output);
1029 if (thread == NULL) {
1030 return 0.0f;
1031 }
1032 volume = thread->streamVolume(stream);
1033 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001034 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 }
1036
1037 return volume;
1038}
1039
Glenn Kastenfff6d712012-01-12 16:38:12 -08001040bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001042 status_t status = checkStreamType(stream);
1043 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 return true;
1045 }
1046
Glenn Kasten6637baa2012-01-09 09:40:36 -08001047 AutoMutex lock(mLock);
1048 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049}
1050
Eric Laurent054d9d32015-04-24 08:48:48 -07001051
1052void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1053{
1054 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1055 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1056 }
1057}
1058
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001059status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001061 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1062 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001063
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 // check calling permissions
1065 if (!settingsAllowed()) {
1066 return PERMISSION_DENIED;
1067 }
1068
Glenn Kasten142f5192014-03-25 17:44:59 -07001069 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1070 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001071 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001072 // result will remain NO_INIT if no audio device is present
1073 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001074 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001075 AutoMutex lock(mHardwareLock);
1076 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1077 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001078 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1079 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001080 // return success if at least one audio device accepts the parameters as not all
1081 // HALs are requested to support all parameters. If no audio device supports the
1082 // requested parameters, the last error is reported.
1083 if (final_result != NO_ERROR) {
1084 final_result = result;
1085 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001086 }
1087 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001088 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001089 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1090 AudioParameter param = AudioParameter(keyValuePairs);
1091 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001092 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1093 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001094 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001095 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1096 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001097 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001098 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1099 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001100 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001101 // suspend effects associated with those session IDs
1102 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001103 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001104 thread->setEffectSuspended(FX_IID_AEC,
1105 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001106 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001107 thread->setEffectSuspended(FX_IID_NS,
1108 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001109 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001110 }
1111 }
Eric Laurentbee53372011-08-29 12:42:48 -07001112 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001113 }
1114 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001115 String8 screenState;
1116 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001117 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001118 if (isOff != (AudioFlinger::mScreenState & 1)) {
1119 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001120 }
1121 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001122 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 }
1124
1125 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1126 // and the thread is exited once the lock is released
1127 sp<ThreadBase> thread;
1128 {
1129 Mutex::Autolock _l(mLock);
1130 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001131 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001133 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001134 // indicate output device change to all input threads for pre processing
1135 AudioParameter param = AudioParameter(keyValuePairs);
1136 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001137 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1138 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001139 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 }
1142 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001143 if (thread != 0) {
1144 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 }
1146 return BAD_VALUE;
1147}
1148
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001149String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001151 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1152 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153
Eric Laurenta4c5a552012-03-29 10:12:40 -07001154 Mutex::Autolock _l(mLock);
1155
Glenn Kasten142f5192014-03-25 17:44:59 -07001156 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001157 String8 out_s8;
1158
Dima Zavin799a70e2011-04-18 16:57:27 -07001159 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001160 String8 s;
1161 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001162 {
1163 AutoMutex lock(mHardwareLock);
1164 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001165 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1166 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001167 mHardwareStatus = AUDIO_HW_IDLE;
1168 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001169 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001170 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001171 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 }
1173
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1175 if (playbackThread != NULL) {
1176 return playbackThread->getParameters(keys);
1177 }
1178 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1179 if (recordThread != NULL) {
1180 return recordThread->getParameters(keys);
1181 }
1182 return String8("");
1183}
1184
Glenn Kastendd8104c2012-07-02 12:42:44 -07001185size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1186 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187{
Eric Laurenta1884f92011-08-23 08:25:03 -07001188 status_t ret = initCheck();
1189 if (ret != NO_ERROR) {
1190 return 0;
1191 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001192 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001193 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001194 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001195 return 0;
1196 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001197
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001198 AutoMutex lock(mHardwareLock);
1199 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001200 audio_config_t config, proposed;
1201 memset(&proposed, 0, sizeof(proposed));
1202 proposed.sample_rate = sampleRate;
1203 proposed.channel_mask = channelMask;
1204 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001205
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001206 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001207 size_t frames;
1208 for (;;) {
1209 // Note: config is currently a const parameter for get_input_buffer_size()
1210 // but we use a copy from proposed in case config changes from the call.
1211 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001212 status_t result = dev->getInputBufferSize(&config, &frames);
1213 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001214 break; // hal success, config is the result
1215 }
1216 // change one parameter of the configuration each iteration to a more "common" value
1217 // to see if the device will support it.
1218 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1219 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1220 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1221 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1222 } else {
1223 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1224 "format %#x, channelMask 0x%X",
1225 sampleRate, format, channelMask);
1226 break; // retries failed, break out of loop with frames == 0.
1227 }
1228 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001229 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001230 if (frames > 0 && config.sample_rate != sampleRate) {
1231 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1232 }
1233 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234}
1235
Glenn Kasten5f972c02014-01-13 09:59:31 -08001236uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238 Mutex::Autolock _l(mLock);
1239
1240 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1241 if (recordThread != NULL) {
1242 return recordThread->getInputFramesLost();
1243 }
1244 return 0;
1245}
1246
1247status_t AudioFlinger::setVoiceVolume(float value)
1248{
Eric Laurenta1884f92011-08-23 08:25:03 -07001249 status_t ret = initCheck();
1250 if (ret != NO_ERROR) {
1251 return ret;
1252 }
1253
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 // check calling permissions
1255 if (!settingsAllowed()) {
1256 return PERMISSION_DENIED;
1257 }
1258
1259 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001260 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001261 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001262 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 mHardwareStatus = AUDIO_HW_IDLE;
1264
1265 return ret;
1266}
1267
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001268status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001269 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 Mutex::Autolock _l(mLock);
1272
1273 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1274 if (playbackThread != NULL) {
1275 return playbackThread->getRenderPosition(halFrames, dspFrames);
1276 }
1277
1278 return BAD_VALUE;
1279}
1280
1281void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1282{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001284 if (client == 0) {
1285 return;
1286 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001287 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001288 {
1289 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001290 if (mNotificationClients.indexOfKey(pid) < 0) {
1291 sp<NotificationClient> notificationClient = new NotificationClient(this,
1292 client,
1293 pid);
1294 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295
Eric Laurent021cf962014-05-13 10:18:14 -07001296 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297
Marco Nelissen06b46062014-11-14 07:58:25 -08001298 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001299 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001300 }
1301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302
Eric Laurent021cf962014-05-13 10:18:14 -07001303 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001304 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001305 // the config change is always sent from playback or record threads to avoid deadlock
1306 // with AudioSystem::gLock
1307 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1308 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001311 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1312 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313 }
1314}
1315
1316void AudioFlinger::removeNotificationClient(pid_t pid)
1317{
1318 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001319 {
1320 Mutex::Autolock _cl(mClientLock);
1321 mNotificationClients.removeItem(pid);
1322 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001323
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001325 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001326 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001327 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001328 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001329 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001330 if (ref->mPid == pid) {
1331 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001332 mAudioSessionRefs.removeAt(i);
1333 delete ref;
1334 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001335 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001336 } else {
1337 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001338 }
1339 }
1340 if (removed) {
1341 purgeStaleEffects_l();
1342 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343}
1344
Eric Laurent73e26b62015-04-27 16:55:58 -07001345void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001346 const sp<AudioIoDescriptor>& ioDesc,
1347 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348{
Eric Laurent021cf962014-05-13 10:18:14 -07001349 Mutex::Autolock _l(mClientLock);
1350 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001352 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1353 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355 }
1356}
1357
Eric Laurent021cf962014-05-13 10:18:14 -07001358// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359void AudioFlinger::removeClient_l(pid_t pid)
1360{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001361 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001362 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 mClients.removeItem(pid);
1364}
1365
Eric Laurent717e1282012-06-29 16:36:52 -07001366// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001367sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1368 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001369{
1370 sp<PlaybackThread> thread;
1371
1372 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1373 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1374 ALOG_ASSERT(thread == 0);
1375 thread = mPlaybackThreads.valueAt(i);
1376 }
1377 }
1378
1379 return thread;
1380}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383
1384// ----------------------------------------------------------------------------
1385
1386AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1387 : RefBase(),
1388 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001389 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301391 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1392 heapSize *= 1024;
1393 if (!heapSize) {
1394 heapSize = kClientSharedHeapSizeBytes;
1395 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1396 // invalidated tracks
1397 if (!audioFlinger->isLowRamDevice()) {
1398 heapSize *= kClientSharedHeapSizeMultiplier;
1399 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001400 }
1401 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402}
1403
Eric Laurent021cf962014-05-13 10:18:14 -07001404// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405AudioFlinger::Client::~Client()
1406{
1407 mAudioFlinger->removeClient_l(mPid);
1408}
1409
Glenn Kasten435dbe62012-01-30 10:15:48 -08001410sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411{
1412 return mMemoryDealer;
1413}
1414
1415// ----------------------------------------------------------------------------
1416
1417AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1418 const sp<IAudioFlingerClient>& client,
1419 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001420 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421{
1422}
1423
1424AudioFlinger::NotificationClient::~NotificationClient()
1425{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426}
1427
Glenn Kasten0f11b512014-01-31 16:18:54 -08001428void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429{
1430 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001431 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432}
1433
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434
1435// ----------------------------------------------------------------------------
1436
1437sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001438 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001440 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001441 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001442 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001443 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001444 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001445 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001446 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001447 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001448 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001449 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001450 sp<IMemory>& cblk,
1451 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001452 status_t *status,
1453 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454{
1455 sp<RecordThread::RecordTrack> recordTrack;
1456 sp<RecordHandle> recordHandle;
1457 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001459 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460
Glenn Kastend776ac62014-05-07 09:16:09 -07001461 cblk.clear();
1462 buffers.clear();
1463
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001464 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001465 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1466 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001467 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001468 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1469 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001470 updatePid = true;
1471 }
1472
1473 if (updatePid) {
1474 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1475 ALOGW_IF(pid != -1 && pid != callingPid,
1476 "%s uid %d pid %d tried to pass itself off as pid %d",
1477 __func__, callingUid, callingPid, pid);
1478 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001479 }
1480
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001482 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001483 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 lStatus = PERMISSION_DENIED;
1485 goto Exit;
1486 }
1487
Glenn Kasten53b5d092014-02-05 10:00:23 -08001488 // further sample rate checks are performed by createRecordTrack_l()
1489 if (sampleRate == 0) {
1490 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1491 lStatus = BAD_VALUE;
1492 goto Exit;
1493 }
1494
Andy Hung6770c6f2015-04-07 13:43:36 -07001495 // we don't yet support anything other than linear PCM
1496 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001497 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001498 lStatus = BAD_VALUE;
1499 goto Exit;
1500 }
1501
Glenn Kasten53b5d092014-02-05 10:00:23 -08001502 // further channel mask checks are performed by createRecordTrack_l()
1503 if (!audio_is_input_channel(channelMask)) {
1504 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
1508
Glenn Kasten05997e22014-03-13 15:08:33 -07001509 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001511 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001513 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 lStatus = BAD_VALUE;
1515 goto Exit;
1516 }
1517
Eric Laurent021cf962014-05-13 10:18:14 -07001518 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001520 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001521 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 lSessionId = *sessionId;
1526 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001527 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001528 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 if (sessionId != NULL) {
1530 *sessionId = lSessionId;
1531 }
1532 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001533 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001534
Glenn Kasten1879fff2012-07-11 15:36:59 -07001535 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001536 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001537 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001538 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001539
1540 if (lStatus == NO_ERROR) {
1541 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1542 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001543 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001544 if (chain != 0) {
1545 Mutex::Autolock _l(thread->mLock);
1546 thread->addEffectChain_l(chain);
1547 }
1548 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 }
Glenn Kastene198c362013-08-13 09:13:36 -07001550
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001551 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001552 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001553 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001554 // Don't hold mClientLock when releasing the reference on the track as the
1555 // destructor will acquire it.
1556 {
1557 Mutex::Autolock _cl(mClientLock);
1558 client.clear();
1559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 goto Exit;
1562 }
1563
Glenn Kastend776ac62014-05-07 09:16:09 -07001564 cblk = recordTrack->getCblk();
1565 buffers = recordTrack->getBuffers();
1566
Glenn Kasten2fc14732013-08-05 14:58:14 -07001567 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569
1570Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001571 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 return recordHandle;
1573}
1574
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001575
1576
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577// ----------------------------------------------------------------------------
1578
Eric Laurenta4c5a552012-03-29 10:12:40 -07001579audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1580{
Eric Laurent44622db2014-08-01 19:00:33 -07001581 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001582 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001583 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001584 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001585 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001586 }
1587 Mutex::Autolock _l(mLock);
1588 return loadHwModule_l(name);
1589}
1590
1591// loadHwModule_l() must be called with AudioFlinger::mLock held
1592audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1593{
1594 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1595 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1596 ALOGW("loadHwModule() module %s already loaded", name);
1597 return mAudioHwDevs.keyAt(i);
1598 }
1599 }
1600
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001601 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001602
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001603 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001604 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001605 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001606 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001607 }
1608
1609 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001610 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001611 mHardwareStatus = AUDIO_HW_IDLE;
1612 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001613 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001614 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001615 }
1616
John Grossmanee578c02012-07-23 17:05:46 -07001617 // Check and cache this HAL's level of support for master mute and master
1618 // volume. If this is the first HAL opened, and it supports the get
1619 // methods, use the initial values provided by the HAL as the current
1620 // master mute and volume settings.
1621
1622 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1623 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001624 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001625
1626 if (0 == mAudioHwDevs.size()) {
1627 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001628 float mv;
1629 if (OK == dev->getMasterVolume(&mv)) {
1630 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001631 }
1632
1633 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001634 bool mm;
1635 if (OK == dev->getMasterMute(&mm)) {
1636 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001637 }
1638 }
1639
Eric Laurenta4c5a552012-03-29 10:12:40 -07001640 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001641 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001642 flags = static_cast<AudioHwDevice::Flags>(flags |
1643 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1644 }
1645
1646 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001647 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001648 flags = static_cast<AudioHwDevice::Flags>(flags |
1649 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1650 }
1651
Eric Laurenta4c5a552012-03-29 10:12:40 -07001652 mHardwareStatus = AUDIO_HW_IDLE;
1653 }
1654
Glenn Kastena13cde92016-03-28 15:26:02 -07001655 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001656 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001657
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001658 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001659
1660 return handle;
1661
1662}
1663
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001664// ----------------------------------------------------------------------------
1665
Glenn Kasten3b16c762012-11-14 08:44:39 -08001666uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001667{
1668 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001669 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001670 return thread != NULL ? thread->sampleRate() : 0;
1671}
1672
Glenn Kastene33054e2012-11-14 12:54:39 -08001673size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001674{
1675 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001676 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001677 return thread != NULL ? thread->frameCountHAL() : 0;
1678}
1679
1680// ----------------------------------------------------------------------------
1681
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001682status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1683{
1684 uid_t uid = IPCThreadState::self()->getCallingUid();
1685 if (uid != AID_SYSTEM) {
1686 return PERMISSION_DENIED;
1687 }
1688 Mutex::Autolock _l(mLock);
1689 if (mIsDeviceTypeKnown) {
1690 return INVALID_OPERATION;
1691 }
1692 mIsLowRamDevice = isLowRamDevice;
1693 mIsDeviceTypeKnown = true;
1694 return NO_ERROR;
1695}
1696
Eric Laurent93c3d412014-08-01 14:48:35 -07001697audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1698{
1699 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001700
1701 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1702 if (index >= 0) {
1703 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1704 mHwAvSyncIds.valueAt(index), sessionId);
1705 return mHwAvSyncIds.valueAt(index);
1706 }
1707
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001708 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001709 if (dev == NULL) {
1710 return AUDIO_HW_SYNC_INVALID;
1711 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001712 String8 reply;
1713 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001714 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001715 param = AudioParameter(reply);
1716 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001717
1718 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001719 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001720 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1721 return AUDIO_HW_SYNC_INVALID;
1722 }
1723
1724 // allow only one session for a given HW A/V sync ID.
1725 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1726 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1727 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1728 value, mHwAvSyncIds.keyAt(i));
1729 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001730 break;
1731 }
1732 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001733
1734 mHwAvSyncIds.add(sessionId, value);
1735
1736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1737 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1738 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001739 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001740 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001741 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001742 thread->setParameters(param.toString());
1743 break;
1744 }
1745 }
1746
1747 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1748 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001749}
1750
Eric Laurent72e3f392015-05-20 14:43:50 -07001751status_t AudioFlinger::systemReady()
1752{
1753 Mutex::Autolock _l(mLock);
1754 ALOGI("%s", __FUNCTION__);
1755 if (mSystemReady) {
1756 ALOGW("%s called twice", __FUNCTION__);
1757 return NO_ERROR;
1758 }
1759 mSystemReady = true;
1760 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1761 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1762 thread->systemReady();
1763 }
1764 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1765 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1766 thread->systemReady();
1767 }
1768 return NO_ERROR;
1769}
1770
Eric Laurentfa90e842014-10-17 18:12:31 -07001771// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1772void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1773{
1774 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1775 if (index >= 0) {
1776 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1777 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1778 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001779 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001780 thread->setParameters(param.toString());
1781 }
1782}
1783
1784
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001785// ----------------------------------------------------------------------------
1786
Eric Laurent83b88082014-06-20 18:31:16 -07001787
1788sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001789 audio_io_handle_t *output,
1790 audio_config_t *config,
1791 audio_devices_t devices,
1792 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001793 audio_output_flags_t flags)
1794{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001795 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001796 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001797 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001798 }
1799
Eric Laurentcf2c0212014-07-25 16:20:43 -07001800 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001801 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1802 } else {
1803 // Audio Policy does not currently request a specific output handle.
1804 // If this is ever needed, see openInput_l() for example code.
1805 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1806 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001807 }
Eric Laurent83b88082014-06-20 18:31:16 -07001808
1809 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1810
Eric Laurent83b88082014-06-20 18:31:16 -07001811 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001812 // This if statement allows overriding the audio policy settings
1813 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1814 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1815 // Check only for Normal Mixing mode
1816 if (kEnableExtendedPrecision) {
1817 // Specify format (uncomment one below to choose)
1818 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1819 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1820 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1821 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001822 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001823 }
1824 if (kEnableExtendedChannels) {
1825 // Specify channel mask (uncomment one below to choose)
1826 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1827 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1828 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1829 }
Eric Laurent83b88082014-06-20 18:31:16 -07001830 }
1831
Phil Burk062e67a2015-02-11 13:40:50 -08001832 AudioStreamOut *outputStream = NULL;
1833 status_t status = outHwDev->openOutputStream(
1834 &outputStream,
1835 *output,
1836 devices,
1837 flags,
1838 config,
1839 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001840
1841 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001842
Phil Burk062e67a2015-02-11 13:40:50 -08001843 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001844
1845 PlaybackThread *thread;
1846 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001847 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001848 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001849 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1850 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001851 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001852 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001853 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001854 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001855 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001856 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001857 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001858 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001859 return thread;
1860 }
1861
1862 return 0;
1863}
1864
Eric Laurentcf2c0212014-07-25 16:20:43 -07001865status_t AudioFlinger::openOutput(audio_module_handle_t module,
1866 audio_io_handle_t *output,
1867 audio_config_t *config,
1868 audio_devices_t *devices,
1869 const String8& address,
1870 uint32_t *latencyMs,
1871 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872{
Phil Burk062e67a2015-02-11 13:40:50 -08001873 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001874 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001875 (devices != NULL) ? *devices : 0,
1876 config->sample_rate,
1877 config->format,
1878 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001879 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Yunlian Jiang32ba9862017-01-31 15:55:00 -08001881 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001884
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 Mutex::Autolock _l(mLock);
1886
Eric Laurentcf2c0212014-07-25 16:20:43 -07001887 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001888 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001889 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
1891 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001892 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001893
1894 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001895 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001896 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001897 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001898
1899 AutoMutex lock(mHardwareLock);
1900 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001901 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001902 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001903 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001904 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 }
1906
Eric Laurentcf2c0212014-07-25 16:20:43 -07001907 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908}
1909
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001910audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1911 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912{
1913 Mutex::Autolock _l(mLock);
1914 MixerThread *thread1 = checkMixerThread_l(output1);
1915 MixerThread *thread2 = checkMixerThread_l(output2);
1916
1917 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001918 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1919 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001920 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 }
1922
Glenn Kasteneeecb982016-02-26 10:44:04 -08001923 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001924 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 thread->addOutputTrack(thread2);
1926 mPlaybackThreads.add(id, thread);
1927 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001928 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 return id;
1930}
1931
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001932status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kastend96c5722012-04-25 13:44:49 -07001934 return closeOutput_nonvirtual(output);
1935}
1936
1937status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1938{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 // keep strong reference on the playback thread so that
1940 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001941 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 {
1943 Mutex::Autolock _l(mLock);
1944 thread = checkPlaybackThread_l(output);
1945 if (thread == NULL) {
1946 return BAD_VALUE;
1947 }
1948
Steve Block3856b092011-10-20 11:56:00 +01001949 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001951 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001953 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001954 DuplicatingThread *dupThread =
1955 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001957 }
1958 }
1959 }
1960
1961
1962 mPlaybackThreads.removeItem(output);
1963 // save all effects to the default thread
1964 if (mPlaybackThreads.size()) {
1965 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1966 if (dstThread != NULL) {
1967 // audioflinger lock is held here so the acquisition order of thread locks does not
1968 // matter
1969 Mutex::Autolock _dl(dstThread->mLock);
1970 Mutex::Autolock _sl(thread->mLock);
1971 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1972 for (size_t i = 0; i < effectChains.size(); i ++) {
1973 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 }
1975 }
1976 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001977 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1978 ioDesc->mIoHandle = output;
1979 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 }
1981 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001982 // The thread entity (active unit of execution) is no longer running here,
1983 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984
Eric Laurentf6870ae2015-05-08 10:50:03 -07001985 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07001986 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 }
Eric Laurent83b88082014-06-20 18:31:16 -07001988
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 return NO_ERROR;
1990}
1991
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001992void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07001993{
1994 AudioStreamOut *out = thread->clearOutput();
1995 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1996 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07001997 delete out;
1998}
1999
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002000void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002001{
2002 mPlaybackThreads.removeItem(thread->mId);
2003 thread->exit();
2004 closeOutputFinish(thread);
2005}
2006
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002007status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008{
2009 Mutex::Autolock _l(mLock);
2010 PlaybackThread *thread = checkPlaybackThread_l(output);
2011
2012 if (thread == NULL) {
2013 return BAD_VALUE;
2014 }
2015
Steve Block3856b092011-10-20 11:56:00 +01002016 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 thread->suspend();
2018
2019 return NO_ERROR;
2020}
2021
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002022status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023{
2024 Mutex::Autolock _l(mLock);
2025 PlaybackThread *thread = checkPlaybackThread_l(output);
2026
2027 if (thread == NULL) {
2028 return BAD_VALUE;
2029 }
2030
Steve Block3856b092011-10-20 11:56:00 +01002031 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032
2033 thread->restore();
2034
2035 return NO_ERROR;
2036}
2037
Eric Laurentcf2c0212014-07-25 16:20:43 -07002038status_t AudioFlinger::openInput(audio_module_handle_t module,
2039 audio_io_handle_t *input,
2040 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002041 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002042 const String8& address,
2043 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002044 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045{
Eric Laurent83b88082014-06-20 18:31:16 -07002046 Mutex::Autolock _l(mLock);
2047
Glenn Kastene7d66712015-03-05 13:46:52 -08002048 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002049 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002050 }
2051
Glenn Kastene7d66712015-03-05 13:46:52 -08002052 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002053
2054 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002055 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002056 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002057 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002059 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002060}
Dima Zavin799a70e2011-04-18 16:57:27 -07002061
Eric Laurent83b88082014-06-20 18:31:16 -07002062sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002063 audio_io_handle_t *input,
2064 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002065 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002066 const String8& address,
2067 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002068 audio_input_flags_t flags)
2069{
Glenn Kastene7d66712015-03-05 13:46:52 -08002070 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002071 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002072 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002073 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002074 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002075
Glenn Kasteneeecb982016-02-26 10:44:04 -08002076 // Audio Policy can request a specific handle for hardware hotword.
2077 // The goal here is not to re-open an already opened input.
2078 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002079 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002080 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2081 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2082 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2083 return 0;
2084 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2085 // This should not happen in a transient state with current design.
2086 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2087 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002088 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002089
Eric Laurentcf2c0212014-07-25 16:20:43 -07002090 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002091 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002092 sp<StreamInHalInterface> inStream;
2093 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002094 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002095 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002096 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002097 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002098 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 halconfig.sample_rate,
2100 halconfig.format,
2101 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002102 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002103 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002105 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002106 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002107 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002108 audio_is_linear_pcm(config->format) &&
2109 audio_is_linear_pcm(halconfig.format) &&
2110 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002111 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2112 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002113 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002115 inStream.clear();
2116 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002117 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002118 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 }
2120
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002121 if (status == NO_ERROR && inStream != 0) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002122
Glenn Kasten46909e72013-02-26 09:20:22 -08002123#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002124 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2125 // or (re-)create if current Pipe is idle and does not match the new format
2126 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002127 enum {
2128 TEE_SINK_NO, // don't copy input
2129 TEE_SINK_NEW, // copy input using a new pipe
2130 TEE_SINK_OLD, // copy input using an existing pipe
2131 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002132 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2133 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002134 if (!mTeeSinkInputEnabled) {
2135 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002136 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002137 kind = TEE_SINK_NO;
2138 } else if (mRecordTeeSink == 0) {
2139 kind = TEE_SINK_NEW;
2140 } else if (mRecordTeeSink->getStrongCount() != 1) {
2141 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002142 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002143 kind = TEE_SINK_OLD;
2144 } else {
2145 kind = TEE_SINK_NEW;
2146 }
2147 switch (kind) {
2148 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002149 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002150 size_t numCounterOffers = 0;
2151 const NBAIO_Format offers[1] = {format};
2152 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2153 ALOG_ASSERT(index == 0);
2154 PipeReader *pipeReader = new PipeReader(*pipe);
2155 numCounterOffers = 0;
2156 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2157 ALOG_ASSERT(index == 0);
2158 mRecordTeeSink = pipe;
2159 mRecordTeeSource = pipeReader;
2160 teeSink = pipe;
2161 }
2162 break;
2163 case TEE_SINK_OLD:
2164 teeSink = mRecordTeeSink;
2165 break;
2166 case TEE_SINK_NO:
2167 default:
2168 break;
2169 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002170#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002171
Eric Laurent05067782016-06-01 18:27:28 -07002172 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002174 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002175 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002176 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002177 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002178 inputStream,
2179 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002180 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002181 devices,
2182 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002183#ifdef TEE_SINK
2184 , teeSink
2185#endif
2186 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002187 mRecordThreads.add(*input, thread);
2188 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002189 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 }
2191
Eric Laurentcf2c0212014-07-25 16:20:43 -07002192 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 return 0;
2194}
2195
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002196status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197{
Glenn Kastend96c5722012-04-25 13:44:49 -07002198 return closeInput_nonvirtual(input);
2199}
2200
2201status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2202{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 // keep strong reference on the record thread so that
2204 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002205 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 {
2207 Mutex::Autolock _l(mLock);
2208 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002209 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210 return BAD_VALUE;
2211 }
2212
Steve Block3856b092011-10-20 11:56:00 +01002213 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002214
2215 // If we still have effect chains, it means that a client still holds a handle
2216 // on at least one effect. We must either move the chain to an existing thread with the
2217 // same session ID or put it aside in case a new record thread is opened for a
2218 // new capture on the same session
2219 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002220 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002221 Mutex::Autolock _sl(thread->mLock);
2222 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002223 // Note: maximum one chain per record thread
2224 if (effectChains.size() != 0) {
2225 chain = effectChains[0];
2226 }
2227 }
2228 if (chain != 0) {
2229 // first check if a record thread is already opened with a client on the same session.
2230 // This should only happen in case of overlap between one thread tear down and the
2231 // creation of its replacement
2232 size_t i;
2233 for (i = 0; i < mRecordThreads.size(); i++) {
2234 sp<RecordThread> t = mRecordThreads.valueAt(i);
2235 if (t == thread) {
2236 continue;
2237 }
2238 if (t->hasAudioSession(chain->sessionId()) != 0) {
2239 Mutex::Autolock _l(t->mLock);
2240 ALOGV("closeInput() found thread %d for effect session %d",
2241 t->id(), chain->sessionId());
2242 t->addEffectChain_l(chain);
2243 break;
2244 }
2245 }
2246 // put the chain aside if we could not find a record thread with the same session id.
2247 if (i == mRecordThreads.size()) {
2248 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002249 }
2250 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002251 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2252 ioDesc->mIoHandle = input;
2253 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 mRecordThreads.removeItem(input);
2255 }
Eric Laurent83b88082014-06-20 18:31:16 -07002256 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2257 // we have a different lock for notification client
2258 closeInputFinish(thread);
2259 return NO_ERROR;
2260}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002262void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002263{
2264 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002265 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002266 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002267 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002268 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002269}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002271void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002272{
2273 mRecordThreads.removeItem(thread->mId);
2274 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275}
2276
Glenn Kastend2304db2014-02-03 07:40:31 -08002277status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278{
2279 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002280 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281
2282 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2283 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002284 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286
2287 return NO_ERROR;
2288}
2289
2290
Glenn Kasteneeecb982016-02-26 10:44:04 -08002291audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292{
Glenn Kasten9d003132016-04-06 14:38:09 -07002293 // This is a binder API, so a malicious client could pass in a bad parameter.
2294 // Check for that before calling the internal API nextUniqueId().
2295 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2296 ALOGE("newAudioUniqueId invalid use %d", use);
2297 return AUDIO_UNIQUE_ID_ALLOCATE;
2298 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002299 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300}
2301
Glenn Kastend848eb42016-03-08 13:42:11 -08002302void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002303{
2304 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002305 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002306 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2307 if (pid != -1 && (caller == getpid_cached)) {
2308 caller = pid;
2309 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002310
Eric Laurent021cf962014-05-13 10:18:14 -07002311 {
2312 Mutex::Autolock _cl(mClientLock);
2313 // Ignore requests received from processes not known as notification client. The request
2314 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2315 // called from a different pid leaving a stale session reference. Also we don't know how
2316 // to clear this reference if the client process dies.
2317 if (mNotificationClients.indexOfKey(caller) < 0) {
2318 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2319 return;
2320 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002321 }
2322
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002323 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002324 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002325 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002326 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2327 ref->mCnt++;
2328 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002329 return;
2330 }
2331 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002332 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2333 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002334}
2335
Glenn Kastend848eb42016-03-08 13:42:11 -08002336void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002337{
2338 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002339 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002340 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2341 if (pid != -1 && (caller == getpid_cached)) {
2342 caller = pid;
2343 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002344 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002345 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002346 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002347 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2348 ref->mCnt--;
2349 ALOGV(" decremented refcount to %d", ref->mCnt);
2350 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002351 mAudioSessionRefs.removeAt(i);
2352 delete ref;
2353 purgeStaleEffects_l();
2354 }
2355 return;
2356 }
2357 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002358 // If the caller is mediaserver it is likely that the session being released was acquired
2359 // on behalf of a process not in notification clients and we ignore the warning.
2360 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002361}
2362
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002363bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2364{
2365 size_t num = mAudioSessionRefs.size();
2366 for (size_t i = 0; i < num; i++) {
2367 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2368 if (ref->mSessionid == audioSession) {
2369 return true;
2370 }
2371 }
2372 return false;
2373}
2374
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002375void AudioFlinger::purgeStaleEffects_l() {
2376
Steve Block3856b092011-10-20 11:56:00 +01002377 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002378
2379 Vector< sp<EffectChain> > chains;
2380
2381 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2382 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2383 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2384 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002385 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2386 chains.push(ec);
2387 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002388 }
2389 }
2390 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2391 sp<RecordThread> t = mRecordThreads.valueAt(i);
2392 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2393 sp<EffectChain> ec = t->mEffectChains[j];
2394 chains.push(ec);
2395 }
2396 }
2397
2398 for (size_t i = 0; i < chains.size(); i++) {
2399 sp<EffectChain> ec = chains[i];
2400 int sessionid = ec->sessionId();
2401 sp<ThreadBase> t = ec->mThread.promote();
2402 if (t == 0) {
2403 continue;
2404 }
2405 size_t numsessionrefs = mAudioSessionRefs.size();
2406 bool found = false;
2407 for (size_t k = 0; k < numsessionrefs; k++) {
2408 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002409 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002410 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002411 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002412 found = true;
2413 break;
2414 }
2415 }
2416 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002417 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002418 // remove all effects from the chain
2419 while (ec->mEffects.size()) {
2420 sp<EffectModule> effect = ec->mEffects[0];
2421 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002422 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002423 if (effect->purgeHandles()) {
2424 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002425 }
2426 AudioSystem::unregisterEffect(effect->id());
2427 }
2428 }
2429 }
2430 return;
2431}
2432
Glenn Kasteneeecb982016-02-26 10:44:04 -08002433// checkThread_l() must be called with AudioFlinger::mLock held
2434AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2435{
2436 ThreadBase *thread = NULL;
2437 switch (audio_unique_id_get_use(ioHandle)) {
2438 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2439 thread = checkPlaybackThread_l(ioHandle);
2440 break;
2441 case AUDIO_UNIQUE_ID_USE_INPUT:
2442 thread = checkRecordThread_l(ioHandle);
2443 break;
2444 default:
2445 break;
2446 }
2447 return thread;
2448}
2449
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002451AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452{
Glenn Kastena1117922012-01-26 10:53:32 -08002453 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454}
2455
2456// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002457AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458{
2459 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002460 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461}
2462
2463// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002464AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465{
Glenn Kastena1117922012-01-26 10:53:32 -08002466 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467}
2468
Glenn Kasteneeecb982016-02-26 10:44:04 -08002469audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470{
Glenn Kasten9d003132016-04-06 14:38:09 -07002471 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002472 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002473 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2474 for (int retry = 0; retry < maxRetries; retry++) {
2475 // The cast allows wraparound from max positive to min negative instead of abort
2476 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2477 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2478 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2479 // allow wrap by skipping 0 and -1 for session ids
2480 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2481 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2482 return (audio_unique_id_t) (base | use);
2483 }
2484 }
2485 // We have no way of recovering from wraparound
2486 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2487 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488}
2489
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002490AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002491{
2492 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2493 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002494 if(thread->isDuplicating()) {
2495 continue;
2496 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002497 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002498 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002499 return thread;
2500 }
2501 }
2502 return NULL;
2503}
2504
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002505audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002506{
2507 PlaybackThread *thread = primaryPlaybackThread_l();
2508
2509 if (thread == NULL) {
2510 return 0;
2511 }
2512
Eric Laurentf1c04f92012-08-28 14:26:53 -07002513 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002514}
2515
Glenn Kastena7335632016-06-09 17:09:53 -07002516AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2517{
2518 size_t minFrameCount = 0;
2519 PlaybackThread *minThread = NULL;
2520 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2521 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2522 if (!thread->isDuplicating()) {
2523 size_t frameCount = thread->frameCountHAL();
2524 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2525 (frameCount == minFrameCount && thread->hasFastMixer() &&
2526 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2527 minFrameCount = frameCount;
2528 minThread = thread;
2529 }
2530 }
2531 }
2532 return minThread;
2533}
2534
Eric Laurenta011e352012-03-29 15:51:43 -07002535sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002536 audio_session_t triggerSession,
2537 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002538 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002539 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002540{
2541 Mutex::Autolock _l(mLock);
2542
2543 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2544 status_t playStatus = NAME_NOT_FOUND;
2545 status_t recStatus = NAME_NOT_FOUND;
2546 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2547 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2548 if (playStatus == NO_ERROR) {
2549 return event;
2550 }
2551 }
2552 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2553 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2554 if (recStatus == NO_ERROR) {
2555 return event;
2556 }
2557 }
2558 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2559 mPendingSyncEvents.add(event);
2560 } else {
2561 ALOGV("createSyncEvent() invalid event %d", event->type());
2562 event.clear();
2563 }
2564 return event;
2565}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002566
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567// ----------------------------------------------------------------------------
2568// Effect management
2569// ----------------------------------------------------------------------------
2570
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002571sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2572 return mEffectsFactoryHal;
2573}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574
Glenn Kastenf587ba52012-01-26 16:25:10 -08002575status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576{
2577 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002578 if (mEffectsFactoryHal.get()) {
2579 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2580 } else {
2581 return -ENODEV;
2582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583}
2584
Glenn Kastenf587ba52012-01-26 16:25:10 -08002585status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586{
2587 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002588 if (mEffectsFactoryHal.get()) {
2589 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2590 } else {
2591 return -ENODEV;
2592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593}
2594
Glenn Kasten5e92a782012-01-30 07:40:52 -08002595status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002596 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597{
2598 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002599 if (mEffectsFactoryHal.get()) {
2600 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2601 } else {
2602 return -ENODEV;
2603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604}
2605
2606
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002607sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 effect_descriptor_t *pDesc,
2609 const sp<IEffectClient>& effectClient,
2610 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002611 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002612 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002613 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002614 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 status_t *status,
2616 int *id,
2617 int *enabled)
2618{
2619 status_t lStatus = NO_ERROR;
2620 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622
Eric Laurentb6436272016-12-07 19:24:50 -08002623 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2624 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2625 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2626 ALOGW_IF(pid != -1 && pid != callingPid,
2627 "%s uid %d pid %d tried to pass itself off as pid %d",
2628 __func__, callingUid, callingPid, pid);
2629 pid = callingPid;
2630 }
2631
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002632 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2633 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634
2635 if (pDesc == NULL) {
2636 lStatus = BAD_VALUE;
2637 goto Exit;
2638 }
2639
Eric Laurent84e9a102010-09-23 16:10:16 -07002640 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002641 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002642 lStatus = PERMISSION_DENIED;
2643 goto Exit;
2644 }
2645
Dima Zavinfce7a472011-04-19 22:30:36 -07002646 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002647 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002648 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002649 lStatus = PERMISSION_DENIED;
2650 goto Exit;
2651 }
2652
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002654 lStatus = NO_INIT;
2655 goto Exit;
2656 }
2657
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002659 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002661 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002663 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 goto Exit;
2665 }
2666 } else {
2667 // if uuid is not specified, look for an available implementation
2668 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002669 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002670 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 lStatus = BAD_VALUE;
2672 goto Exit;
2673 }
2674 uint32_t numEffects = 0;
2675 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002676 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 bool found = false;
2678
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002679 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002681 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 goto Exit;
2683 }
2684 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002685 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002687 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 continue;
2689 }
2690 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2691 // If matching type found save effect descriptor. If the session is
2692 // 0 and the effect is not auxiliary, continue enumeration in case
2693 // an auxiliary version of this effect type is available
2694 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002695 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002696 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2698 break;
2699 }
2700 }
2701 }
2702 if (!found) {
2703 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002704 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 goto Exit;
2706 }
2707 // For same effect type, chose auxiliary version over insert version if
2708 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002709 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002711 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 }
2713 }
2714
2715 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002716 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2718 lStatus = INVALID_OPERATION;
2719 goto Exit;
2720 }
2721
Eric Laurent59255e42011-07-27 19:49:51 -07002722 // check recording permission for visualizer
2723 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002724 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002725 lStatus = PERMISSION_DENIED;
2726 goto Exit;
2727 }
2728
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002730 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002731 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002732 // if the output returned by getOutputForEffect() is removed before we lock the
2733 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2734 // and we will exit safely
2735 io = AudioSystem::getOutputForEffect(&desc);
2736 ALOGV("createEffect got output %d", io);
2737 }
2738
2739 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740
2741 // If output is not specified try to find a matching audio session ID in one of the
2742 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002743 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2744 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002745 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002746 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002747 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2748 // output must be specified by AudioPolicyManager when using session
2749 // AUDIO_SESSION_OUTPUT_STAGE
2750 lStatus = BAD_VALUE;
2751 goto Exit;
2752 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002753 // look for the thread where the specified audio session is present
2754 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2755 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2756 io = mPlaybackThreads.keyAt(i);
2757 break;
2758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002760 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002761 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2762 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2763 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002764 break;
2765 }
2766 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002767 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002768 // If no output thread contains the requested session ID, default to
2769 // first output. The effect chain will be moved to the correct output
2770 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002771 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002772 io = mPlaybackThreads.keyAt(0);
2773 }
Steve Block3856b092011-10-20 11:56:00 +01002774 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002775 }
2776 ThreadBase *thread = checkRecordThread_l(io);
2777 if (thread == NULL) {
2778 thread = checkPlaybackThread_l(io);
2779 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002780 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002781 lStatus = BAD_VALUE;
2782 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002783 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002784 } else {
2785 // Check if one effect chain was awaiting for an effect to be created on this
2786 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002787 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002788 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002789 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002790 thread->addEffectChain_l(chain);
2791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002793
Eric Laurent021cf962014-05-13 10:18:14 -07002794 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002796 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002797 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002798 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002799 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 if (handle != 0 && id != NULL) {
2801 *id = handle->id();
2802 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002803 if (handle == 0) {
2804 // remove local strong reference to Client with mClientLock held
2805 Mutex::Autolock _cl(mClientLock);
2806 client.clear();
2807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 }
2809
2810Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002811 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 return handle;
2813}
2814
Glenn Kastend848eb42016-03-08 13:42:11 -08002815status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002816 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002817{
Steve Block3856b092011-10-20 11:56:00 +01002818 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002819 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002820 Mutex::Autolock _l(mLock);
2821 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002822 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002823 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 }
Eric Laurentde070132010-07-13 04:45:46 -07002825 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2826 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002827 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002828 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 }
Eric Laurentde070132010-07-13 04:45:46 -07002830 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2831 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002832 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002833 return BAD_VALUE;
2834 }
2835
2836 Mutex::Autolock _dl(dstThread->mLock);
2837 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002838 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839}
2840
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002841// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002842status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002843 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002844 AudioFlinger::PlaybackThread *dstThread,
2845 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002846{
Steve Block3856b092011-10-20 11:56:00 +01002847 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002848 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002849
Eric Laurent59255e42011-07-27 19:49:51 -07002850 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002851 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002852 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002853 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002854 return INVALID_OPERATION;
2855 }
2856
Eric Laurent4c415062016-06-17 16:14:16 -07002857 // Check whether the destination thread and all effects in the chain are compatible
2858 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002859 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002860 " destination thread %p is not compatible with effects in the chain",
2861 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002862 return INVALID_OPERATION;
2863 }
2864
Eric Laurent39e94f82010-07-28 01:32:47 -07002865 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002866 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002867 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002868 // removed.
2869 srcThread->removeEffectChain_l(chain);
2870
2871 // transfer all effects one by one so that new effect chain is created on new thread with
2872 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002873 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002874 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002875 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002876 Vector< sp<EffectModule> > removed;
2877 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002878 while (effect != 0) {
2879 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002880 removed.add(effect);
2881 status = dstThread->addEffect_l(effect);
2882 if (status != NO_ERROR) {
2883 break;
2884 }
Eric Laurentec35a142011-10-05 17:42:25 -07002885 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2886 if (effect->state() == EffectModule::ACTIVE ||
2887 effect->state() == EffectModule::STOPPING) {
2888 effect->start();
2889 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002890 // if the move request is not received from audio policy manager, the effect must be
2891 // re-registered with the new strategy and output
2892 if (dstChain == 0) {
2893 dstChain = effect->chain().promote();
2894 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002895 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002896 status = NO_INIT;
2897 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002898 }
2899 strategy = dstChain->strategy();
2900 }
2901 if (reRegister) {
2902 AudioSystem::unregisterEffect(effect->id());
2903 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002904 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002905 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002906 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002907 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002908 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002909 }
Eric Laurentde070132010-07-13 04:45:46 -07002910 effect = chain->getEffectFromId_l(0);
2911 }
2912
Eric Laurent5baf2af2013-09-12 17:37:00 -07002913 if (status != NO_ERROR) {
2914 for (size_t i = 0; i < removed.size(); i++) {
2915 srcThread->addEffect_l(removed[i]);
2916 if (dstChain != 0 && reRegister) {
2917 AudioSystem::unregisterEffect(removed[i]->id());
2918 AudioSystem::registerEffect(&removed[i]->desc(),
2919 srcThread->id(),
2920 strategy,
2921 sessionId,
2922 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002923 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002924 }
2925 }
2926 }
2927
2928 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929}
2930
Eric Laurent5baf2af2013-09-12 17:37:00 -07002931bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002932{
2933 if (mGlobalEffectEnableTime != 0 &&
2934 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2935 return true;
2936 }
2937
2938 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2939 sp<EffectChain> ec =
2940 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002941 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002942 return true;
2943 }
2944 }
2945 return false;
2946}
2947
Eric Laurent5baf2af2013-09-12 17:37:00 -07002948void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002949{
2950 Mutex::Autolock _l(mLock);
2951
2952 mGlobalEffectEnableTime = systemTime();
2953
2954 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2955 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2956 if (t->mType == ThreadBase::OFFLOAD) {
2957 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2958 }
2959 }
2960
2961}
2962
Eric Laurentaaa44472014-09-12 17:41:50 -07002963status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2964{
Glenn Kastend848eb42016-03-08 13:42:11 -08002965 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002966 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002967 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002968 if (index >= 0) {
2969 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2970 return ALREADY_EXISTS;
2971 }
2972 mOrphanEffectChains.add(session, chain);
2973 return NO_ERROR;
2974}
2975
2976sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2977{
2978 sp<EffectChain> chain;
2979 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002980 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002981 if (index >= 0) {
2982 chain = mOrphanEffectChains.valueAt(index);
2983 mOrphanEffectChains.removeItemsAt(index);
2984 }
2985 return chain;
2986}
2987
2988bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2989{
2990 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002991 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002992 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002993 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002994 if (index >= 0) {
2995 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002996 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002997 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002998 mOrphanEffectChains.removeItemsAt(index);
2999 }
3000 return true;
3001 }
3002 return false;
3003}
3004
3005
Glenn Kastenda6ef132013-01-10 12:31:01 -08003006struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003007#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3008 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003009};
3010
3011int comparEntry(const void *p1, const void *p2)
3012{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003013 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003014}
3015
Glenn Kasten46909e72013-02-26 09:20:22 -08003016#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003017void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018{
Eric Laurent81784c32012-11-19 14:55:58 -08003019 NBAIO_Source *teeSource = source.get();
3020 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003021 // .wav rotation
3022 // There is a benign race condition if 2 threads call this simultaneously.
3023 // They would both traverse the directory, but the result would simply be
3024 // failures at unlink() which are ignored. It's also unlikely since
3025 // normally dumpsys is only done by bugreport or from the command line.
3026 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003027 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003028 size_t teePathLen = strlen(teePath);
3029 DIR *dir = opendir(teePath);
3030 teePath[teePathLen++] = '/';
3031 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003032#define TEE_MAX_SORT 20 // number of entries to sort
3033#define TEE_MAX_KEEP 10 // number of entries to keep
3034 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003035 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003036 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003037 struct dirent de;
3038 struct dirent *result = NULL;
3039 int rc = readdir_r(dir, &de, &result);
3040 if (rc != 0) {
3041 ALOGW("readdir_r failed %d", rc);
3042 break;
3043 }
3044 if (result == NULL) {
3045 break;
3046 }
3047 if (result != &de) {
3048 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3049 break;
3050 }
3051 // ignore non .wav file entries
3052 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003053 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003054 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3055 continue;
3056 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003057 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003058 }
3059 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003060 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003061 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003062 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3063 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003064 (void) unlink(teePath);
3065 }
3066 }
3067 } else {
3068 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003069 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003070 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003071 }
3072 }
Eric Laurent81784c32012-11-19 14:55:58 -08003073 char teeTime[16];
3074 struct timeval tv;
3075 gettimeofday(&tv, NULL);
3076 struct tm tm;
3077 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003078 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3079 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3080 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3081 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003082 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003083 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003084 char wavHeader[44];
3085 memcpy(wavHeader,
3086 "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",
3087 sizeof(wavHeader));
3088 NBAIO_Format format = teeSource->format();
3089 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003090 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003091 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003092 wavHeader[22] = channelCount; // number of channels
3093 wavHeader[24] = sampleRate; // sample rate
3094 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003095 wavHeader[32] = frameSize; // block alignment
3096 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003097 write(teeFd, wavHeader, sizeof(wavHeader));
3098 size_t total = 0;
3099 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003100#define TEE_SINK_READ 1024 // frames per I/O operation
3101 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003102 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003103 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003104 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003105 bool wasFirstRead = firstRead;
3106 firstRead = false;
3107 if (actual <= 0) {
3108 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3109 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003110 }
Eric Laurent81784c32012-11-19 14:55:58 -08003111 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003112 }
Eric Laurent81784c32012-11-19 14:55:58 -08003113 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003114 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003115 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003116 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003117 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003118 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003119 uint32_t temp = 44 + total * frameSize - 8;
3120 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003121 write(teeFd, &temp, sizeof(temp));
3122 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003123 temp = total * frameSize;
3124 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003125 write(teeFd, &temp, sizeof(temp));
3126 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003127 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003128 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003129 }
Eric Laurent59255e42011-07-27 19:49:51 -07003130 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003131 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003132 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003133 }
Eric Laurent59255e42011-07-27 19:49:51 -07003134 }
3135 }
3136}
Glenn Kasten46909e72013-02-26 09:20:22 -08003137#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003138
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139// ----------------------------------------------------------------------------
3140
3141status_t AudioFlinger::onTransact(
3142 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3143{
3144 return BnAudioFlinger::onTransact(code, data, reply, flags);
3145}
3146
Glenn Kasten63238ef2015-03-02 15:50:29 -08003147} // namespace android