blob: b5ab7826c3d8a598b2b06ee58677c21d84b68ed0 [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>
Andy Hung35fec5f2016-04-13 14:21:48 -070034#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
Mikhail Naganove4f1f632016-08-31 11:35:10 -070047#include "DeviceHalInterface.h"
48#include "DevicesFactoryHalInterface.h"
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070049#include "EffectsFactoryHalInterface.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mikhail Naganove4f1f632016-08-31 11:35:10 -070051// FIXME: Remove after streams HAL is componentized
52#include "DeviceHalLocal.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Andy Hung6770c6f2015-04-07 13:43:36 -070054#include <media/AudioResamplerPublic.h>
55
Eric Laurent6d8b6942011-06-24 07:01:31 -070056#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070057#include <audio_effects/effect_ns.h>
58#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Glenn Kasten3b21c502011-12-15 09:52:39 -080060#include <audio_utils/primitives.h>
61
Eric Laurentfeb0db62011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080063
Glenn Kasten9e58b552013-01-18 15:09:48 -080064#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070065#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080066#include <media/nbaio/Pipe.h>
67#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070068#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080069#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070070#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080071
Mathias Agopian65ab4712010-07-14 17:59:35 -070072// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070073
John Grossman1c345192012-03-27 14:00:17 -070074// Note: the following macro is used for extremely verbose logging message. In
75// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
76// 0; but one side effect of this is to turn all LOGV's as well. Some messages
77// are so verbose that we want to suppress them even when we have ALOG_ASSERT
78// turned on. Do not uncomment the #def below unless you really know what you
79// are doing and want to see all of the extremely verbose messages.
80//#define VERY_VERY_VERBOSE_LOGGING
81#ifdef VERY_VERY_VERBOSE_LOGGING
82#define ALOGVV ALOGV
83#else
84#define ALOGVV(a...) do { } while(0)
85#endif
Eric Laurentde070132010-07-13 04:45:46 -070086
Mathias Agopian65ab4712010-07-14 17:59:35 -070087namespace android {
88
Glenn Kastenec1d6b52011-12-12 09:04:45 -080089static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
90static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070091static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070092static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten58912562012-04-03 10:45:00 -070094
John Grossman4ff14ba2012-02-08 16:37:41 -080095nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080096
Eric Laurent81784c32012-11-19 14:55:58 -080097uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070098
Glenn Kasten46909e72013-02-26 09:20:22 -080099#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800100bool AudioFlinger::mTeeSinkInputEnabled = false;
101bool AudioFlinger::mTeeSinkOutputEnabled = false;
102bool AudioFlinger::mTeeSinkTrackEnabled = false;
103
104size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
105size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
106size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800107#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800108
Eric Laurent813e2a72013-08-31 12:59:48 -0700109// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
110// we define a minimum time during which a global effect is considered enabled.
111static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113// ----------------------------------------------------------------------------
114
Marco Nelissenb2208842014-02-07 14:00:50 -0800115const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800116 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530117 case AUDIO_FORMAT_PCM:
118 switch (format) {
119 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
120 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
121 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
122 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
123 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
124 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
125 default:
126 break;
127 }
128 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800129 case AUDIO_FORMAT_MP3: return "mp3";
130 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
131 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
132 case AUDIO_FORMAT_AAC: return "aac";
133 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
134 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
135 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530136 case AUDIO_FORMAT_OPUS: return "opus";
137 case AUDIO_FORMAT_AC3: return "ac-3";
138 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800139 case AUDIO_FORMAT_IEC61937: return "iec61937";
Eric Laurente30f2092016-07-07 18:56:57 -0700140 case AUDIO_FORMAT_DTS: return "dts";
141 case AUDIO_FORMAT_DTS_HD: return "dts-hd";
142 case AUDIO_FORMAT_DOLBY_TRUEHD: return "dolby-truehd";
Marco Nelissenb2208842014-02-07 14:00:50 -0800143 default:
144 break;
145 }
146 return "unknown";
147}
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800153 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800154 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700155 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800156 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700158 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700160 mBtNrecIsOff(false),
161 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700162 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700163 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700164 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700166 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
167 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
168 // zero ID has a special meaning, so unavailable
169 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
170 }
171
Glenn Kasten949a9262013-04-16 12:35:20 -0700172 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800173 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800174 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800175 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
176 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700178
Wei Jia3f273d12015-11-24 09:06:49 -0800179 // reset battery stats.
180 // if the audio service has crashed, battery stats could be left
181 // in bad state, reset the state upon service start.
182 BatteryNotifier::getInstance().noteResetAudio();
183
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700184 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700185 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
186
Glenn Kasten46909e72013-02-26 09:20:22 -0800187#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800188 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800189 (void) property_get("ro.debuggable", value, "0");
190 int debuggable = atoi(value);
191 int teeEnabled = 0;
192 if (debuggable) {
193 (void) property_get("af.tee", value, "0");
194 teeEnabled = atoi(value);
195 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800196 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700197 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800198 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700199 }
200 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700202 }
203 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800204 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700205 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800206#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700207}
208
209void AudioFlinger::onFirstRef()
210{
Eric Laurent93575202011-01-18 18:39:02 -0800211 Mutex::Autolock _l(mLock);
212
Dima Zavin799a70e2011-04-18 16:57:27 -0700213 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800214 char val_str[PROPERTY_VALUE_MAX] = { 0 };
215 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
216 uint32_t int_val;
217 if (1 == sscanf(val_str, "%u", &int_val)) {
218 mStandbyTimeInNsecs = milliseconds(int_val);
219 ALOGI("Using %u mSec as standby time.", int_val);
220 } else {
221 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
222 ALOGI("Using default %u mSec as standby time.",
223 (uint32_t)(mStandbyTimeInNsecs / 1000000));
224 }
225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226
Eric Laurent1c333e22014-05-20 10:48:17 -0700227 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700228
Eric Laurenta4c5a552012-03-29 10:12:40 -0700229 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230}
231
232AudioFlinger::~AudioFlinger()
233{
234 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700235 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700236 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700237 }
238 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700239 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700240 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700242
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800243 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
244 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700245 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700247
248 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800249 if (mLogMemoryDealer != 0) {
250 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
251 if (binder != 0) {
252 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
253 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
254 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
255 mUnregisteredWriters.pop();
256 mediaLogService->unregisterWriter(iMemory);
257 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700258 }
259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260}
261
Eric Laurenta4c5a552012-03-29 10:12:40 -0700262static const char * const audio_interfaces[] = {
263 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
264 AUDIO_HARDWARE_MODULE_ID_A2DP,
265 AUDIO_HARDWARE_MODULE_ID_USB,
266};
267#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
268
Phil Burk062e67a2015-02-11 13:40:50 -0800269AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700270 audio_module_handle_t module,
271 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700272{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700273 // if module is 0, the request comes from an old policy manager and we should load
274 // well known modules
275 if (module == 0) {
276 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
277 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
278 loadHwModule_l(audio_interfaces[i]);
279 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700280 // then try to find a module supporting the requested device.
281 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
282 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700283 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
284 uint32_t supportedDevices;
285 if (dev->getSupportedDevices(&supportedDevices) == OK &&
286 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700287 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700288 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700289 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700290 } else {
291 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700292 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
293 if (audioHwDevice != NULL) {
294 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295 }
296 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700297
Dima Zavin799a70e2011-04-18 16:57:27 -0700298 return NULL;
299}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300
Glenn Kasten0f11b512014-01-31 16:18:54 -0800301void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306
307 result.append("Clients:\n");
308 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800309 sp<Client> client = mClients.valueAt(i).promote();
310 if (client != 0) {
311 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
312 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313 }
314 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700315
Eric Laurentd1b28d42013-09-18 18:47:13 -0700316 result.append("Notification Clients:\n");
317 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
318 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
319 result.append(buffer);
320 }
321
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800323 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
325 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800326 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327 result.append(buffer);
328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330}
331
332
Glenn Kasten0f11b512014-01-31 16:18:54 -0800333void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334{
335 const size_t SIZE = 256;
336 char buffer[SIZE];
337 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800338 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339
John Grossman4ff14ba2012-02-08 16:37:41 -0800340 snprintf(buffer, SIZE, "Hardware status: %d\n"
341 "Standby Time mSec: %u\n",
342 hardwareStatus,
343 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344 result.append(buffer);
345 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346}
347
Glenn Kasten0f11b512014-01-31 16:18:54 -0800348void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349{
350 const size_t SIZE = 256;
351 char buffer[SIZE];
352 String8 result;
353 snprintf(buffer, SIZE, "Permission Denial: "
354 "can't dump AudioFlinger from pid=%d, uid=%d\n",
355 IPCThreadState::self()->getCallingPid(),
356 IPCThreadState::self()->getCallingUid());
357 result.append(buffer);
358 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700359}
360
Eric Laurent81784c32012-11-19 14:55:58 -0800361bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362{
363 bool locked = false;
364 for (int i = 0; i < kDumpLockRetries; ++i) {
365 if (mutex.tryLock() == NO_ERROR) {
366 locked = true;
367 break;
368 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800369 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370 }
371 return locked;
372}
373
374status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
375{
Glenn Kasten44deb052012-02-05 18:09:08 -0800376 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377 dumpPermissionDenial(fd, args);
378 } else {
379 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800380 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381 if (!hardwareLocked) {
382 String8 result(kHardwareLockedString);
383 write(fd, result.string(), result.size());
384 } else {
385 mHardwareLock.unlock();
386 }
387
Eric Laurent81784c32012-11-19 14:55:58 -0800388 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389
390 // failed to lock - AudioFlinger is probably deadlocked
391 if (!locked) {
392 String8 result(kDeadlockedString);
393 write(fd, result.string(), result.size());
394 }
395
Eric Laurent021cf962014-05-13 10:18:14 -0700396 bool clientLocked = dumpTryLock(mClientLock);
397 if (!clientLocked) {
398 String8 result(kClientLockedString);
399 write(fd, result.string(), result.size());
400 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700401
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700402 if (mEffectsFactoryHal.get() != NULL) {
403 mEffectsFactoryHal->dumpEffects(fd);
404 } else {
405 String8 result(kNoEffectsFactory);
406 write(fd, result.string(), result.size());
407 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700408
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700410 if (clientLocked) {
411 mClientLock.unlock();
412 }
413
Mathias Agopian65ab4712010-07-14 17:59:35 -0700414 dumpInternals(fd, args);
415
416 // dump playback threads
417 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
418 mPlaybackThreads.valueAt(i)->dump(fd, args);
419 }
420
421 // dump record threads
422 for (size_t i = 0; i < mRecordThreads.size(); i++) {
423 mRecordThreads.valueAt(i)->dump(fd, args);
424 }
425
Eric Laurentaaa44472014-09-12 17:41:50 -0700426 // dump orphan effect chains
427 if (mOrphanEffectChains.size() != 0) {
428 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
429 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
430 mOrphanEffectChains.valueAt(i)->dump(fd, args);
431 }
432 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700433 // dump all hardware devs
434 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700435 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
436 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700438
Glenn Kasten46909e72013-02-26 09:20:22 -0800439#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700440 // dump the serially shared record tee sink
441 if (mRecordTeeSource != 0) {
442 dumpTee(fd, mRecordTeeSource);
443 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800444#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700445
Glenn Kastend65d73c2012-06-22 17:21:07 -0700446 if (locked) {
447 mLock.unlock();
448 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800449
450 // append a copy of media.log here by forwarding fd to it, but don't attempt
451 // to lookup the service if it's not running, as it will block for a second
452 if (mLogMemoryDealer != 0) {
453 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
454 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700455 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800456 Vector<String16> args;
457 binder->dump(fd, args);
458 }
459 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700460
461 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700462 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700463 bool unreachableMemory = false;
464 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700465 if (arg == String16("-m")) {
466 dumpMem = true;
467 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700468 unreachableMemory = true;
469 }
470 }
471
Andy Hung07b745e2016-05-23 16:21:07 -0700472 if (dumpMem) {
473 dprintf(fd, "\nDumping memory:\n");
474 std::string s = dumpMemoryAddresses(100 /* limit */);
475 write(fd, s.c_str(), s.size());
476 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700477 if (unreachableMemory) {
478 dprintf(fd, "\nDumping unreachable memory:\n");
479 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700480 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700481 write(fd, s.c_str(), s.size());
482 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700483 }
484 return NO_ERROR;
485}
486
Eric Laurent021cf962014-05-13 10:18:14 -0700487sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800488{
Eric Laurent021cf962014-05-13 10:18:14 -0700489 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800490 // If pid is already in the mClients wp<> map, then use that entry
491 // (for which promote() is always != 0), otherwise create a new entry and Client.
492 sp<Client> client = mClients.valueFor(pid).promote();
493 if (client == 0) {
494 client = new Client(this, pid);
495 mClients.add(pid, client);
496 }
497
498 return client;
499}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500
Glenn Kasten9e58b552013-01-18 15:09:48 -0800501sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
502{
Glenn Kasten481fb672013-09-30 14:39:28 -0700503 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800504 if (mLogMemoryDealer == 0) {
505 return new NBLog::Writer();
506 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800507 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700508 // Similarly if we can't contact the media.log service, also return a dummy writer
509 if (binder == 0) {
510 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800511 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700512 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
513 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
514 // If allocation fails, consult the vector of previously unregistered writers
515 // and garbage-collect one or more them until an allocation succeeds
516 if (shared == 0) {
517 Mutex::Autolock _l(mUnregisteredWritersLock);
518 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
519 {
520 // Pick the oldest stale writer to garbage-collect
521 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
522 mUnregisteredWriters.removeAt(0);
523 mediaLogService->unregisterWriter(iMemory);
524 // Now the media.log remote reference to IMemory is gone. When our last local
525 // reference to IMemory also drops to zero at end of this block,
526 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
527 }
528 // Re-attempt the allocation
529 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
530 if (shared != 0) {
531 goto success;
532 }
533 }
534 // Even after garbage-collecting all old writers, there is still not enough memory,
535 // so return a dummy writer
536 return new NBLog::Writer();
537 }
538success:
539 mediaLogService->registerWriter(shared, size, name);
540 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800541}
542
543void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
544{
Glenn Kasten685ef092013-02-04 08:15:34 -0800545 if (writer == 0) {
546 return;
547 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800548 sp<IMemory> iMemory(writer->getIMemory());
549 if (iMemory == 0) {
550 return;
551 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700552 // Rather than removing the writer immediately, append it to a queue of old writers to
553 // be garbage-collected later. This allows us to continue to view old logs for a while.
554 Mutex::Autolock _l(mUnregisteredWritersLock);
555 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800556}
557
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558// IAudioFlinger interface
559
560
561sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800562 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800564 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700565 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800566 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700567 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700570 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800571 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800572 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800573 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 status_t *status)
575{
576 sp<PlaybackThread::Track> track;
577 sp<TrackHandle> trackHandle;
578 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800580 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700582 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
583 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
584 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
585 ALOGW_IF(pid != -1 && pid != callingPid,
586 "%s uid %d pid %d tried to pass itself off as pid %d",
587 __func__, callingUid, callingPid, pid);
588 pid = callingPid;
589 }
590
Glenn Kasten263709e2012-01-06 08:40:01 -0800591 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
592 // but if someone uses binder directly they could bypass that and cause us to crash
593 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000594 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 lStatus = BAD_VALUE;
596 goto Exit;
597 }
598
Glenn Kasten53b5d092014-02-05 10:00:23 -0800599 // further sample rate checks are performed by createTrack_l() depending on the thread type
600 if (sampleRate == 0) {
601 ALOGE("createTrack() invalid sample rate %u", sampleRate);
602 lStatus = BAD_VALUE;
603 goto Exit;
604 }
605
606 // further channel mask checks are performed by createTrack_l() depending on the thread type
607 if (!audio_is_output_channel(channelMask)) {
608 ALOGE("createTrack() invalid channel mask %#x", channelMask);
609 lStatus = BAD_VALUE;
610 goto Exit;
611 }
612
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700613 // further format checks are performed by createTrack_l() depending on the thread type
614 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800615 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700616 lStatus = BAD_VALUE;
617 goto Exit;
618 }
619
Glenn Kasten663c2242013-09-24 11:52:37 -0700620 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
621 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
622 lStatus = BAD_VALUE;
623 goto Exit;
624 }
625
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 {
627 Mutex::Autolock _l(mLock);
628 PlaybackThread *thread = checkPlaybackThread_l(output);
629 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800630 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 lStatus = BAD_VALUE;
632 goto Exit;
633 }
634
Eric Laurent021cf962014-05-13 10:18:14 -0700635 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
Glenn Kastene848bd92014-03-13 15:00:32 -0700637 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700638 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800639 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
640 ALOGE("createTrack() invalid session ID %d", *sessionId);
641 lStatus = BAD_VALUE;
642 goto Exit;
643 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700644 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700645 // check if an effect chain with the same session ID is present on another
646 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700647 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700648 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
649 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700650 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700651 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700652 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700653 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700654 }
Eric Laurentde070132010-07-13 04:45:46 -0700655 }
656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700658 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800659 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 if (sessionId != NULL) {
661 *sessionId = lSessionId;
662 }
663 }
Steve Block3856b092011-10-20 11:56:00 +0100664 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665
666 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800667 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800668 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700669 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700670
671 // move effect chain to this output thread if an effect on same session was waiting
672 // for a track to be created
673 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700674 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700675 Mutex::Autolock _dl(thread->mLock);
676 Mutex::Autolock _sl(effectThread->mLock);
677 moveEffectChain_l(lSessionId, effectThread, thread, true);
678 }
Eric Laurenta011e352012-03-29 15:51:43 -0700679
680 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700681 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700682 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
683 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700684 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700685 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700686 } else {
687 mPendingSyncEvents[i]->cancel();
688 }
Eric Laurenta011e352012-03-29 15:51:43 -0700689 mPendingSyncEvents.removeAt(i);
690 i--;
691 }
692 }
693 }
Glenn Kastene198c362013-08-13 09:13:36 -0700694
Glenn Kastend848eb42016-03-08 13:42:11 -0800695 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 }
Glenn Kastene198c362013-08-13 09:13:36 -0700697
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700698 if (lStatus != NO_ERROR) {
699 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700700 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700701 // Don't hold mClientLock when releasing the reference on the track as the
702 // destructor will acquire it.
703 {
704 Mutex::Autolock _cl(mClientLock);
705 client.clear();
706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700708 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 }
710
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700711 // return handle to client
712 trackHandle = new TrackHandle(track);
713
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700715 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 return trackHandle;
717}
718
Glenn Kasten2c073da2016-02-26 09:14:08 -0800719uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720{
721 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800722 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800724 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 return 0;
726 }
727 return thread->sampleRate();
728}
729
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800730audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731{
732 Mutex::Autolock _l(mLock);
733 PlaybackThread *thread = checkPlaybackThread_l(output);
734 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000735 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800736 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 }
738 return thread->format();
739}
740
Glenn Kasten2c073da2016-02-26 09:14:08 -0800741size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742{
743 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800744 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800746 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 return 0;
748 }
Glenn Kasten58912562012-04-03 10:45:00 -0700749 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
750 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 return thread->frameCount();
752}
753
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700754size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
755{
756 Mutex::Autolock _l(mLock);
757 ThreadBase *thread = checkThread_l(ioHandle);
758 if (thread == NULL) {
759 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
760 return 0;
761 }
762 return thread->frameCountHAL();
763}
764
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800765uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766{
767 Mutex::Autolock _l(mLock);
768 PlaybackThread *thread = checkPlaybackThread_l(output);
769 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800770 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771 return 0;
772 }
773 return thread->latency();
774}
775
776status_t AudioFlinger::setMasterVolume(float value)
777{
Eric Laurenta1884f92011-08-23 08:25:03 -0700778 status_t ret = initCheck();
779 if (ret != NO_ERROR) {
780 return ret;
781 }
782
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 // check calling permissions
784 if (!settingsAllowed()) {
785 return PERMISSION_DENIED;
786 }
787
Eric Laurenta4c5a552012-03-29 10:12:40 -0700788 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700789 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700790
John Grossmanee578c02012-07-23 17:05:46 -0700791 // Set master volume in the HALs which support it.
792 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
793 AutoMutex lock(mHardwareLock);
794 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800795
John Grossmanee578c02012-07-23 17:05:46 -0700796 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
797 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700798 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800799 }
John Grossmanee578c02012-07-23 17:05:46 -0700800 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802
John Grossmanee578c02012-07-23 17:05:46 -0700803 // Now set the master volume in each playback thread. Playback threads
804 // assigned to HALs which do not have master volume support will apply
805 // master volume during the mix operation. Threads with HALs which do
806 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700807 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
808 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
809 continue;
810 }
John Grossmanee578c02012-07-23 17:05:46 -0700811 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813
814 return NO_ERROR;
815}
816
Glenn Kastenf78aee72012-01-04 11:00:47 -0800817status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818{
Eric Laurenta1884f92011-08-23 08:25:03 -0700819 status_t ret = initCheck();
820 if (ret != NO_ERROR) {
821 return ret;
822 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823
824 // check calling permissions
825 if (!settingsAllowed()) {
826 return PERMISSION_DENIED;
827 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800828 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000829 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 return BAD_VALUE;
831 }
832
833 { // scope for the lock
834 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700835 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700837 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 mHardwareStatus = AUDIO_HW_IDLE;
839 }
840
841 if (NO_ERROR == ret) {
842 Mutex::Autolock _l(mLock);
843 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800844 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700845 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 }
847
848 return ret;
849}
850
851status_t AudioFlinger::setMicMute(bool state)
852{
Eric Laurenta1884f92011-08-23 08:25:03 -0700853 status_t ret = initCheck();
854 if (ret != NO_ERROR) {
855 return ret;
856 }
857
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 // check calling permissions
859 if (!settingsAllowed()) {
860 return PERMISSION_DENIED;
861 }
862
863 AutoMutex lock(mHardwareLock);
864 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700865 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700866 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
867 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700868 if (result != NO_ERROR) {
869 ret = result;
870 }
871 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 mHardwareStatus = AUDIO_HW_IDLE;
873 return ret;
874}
875
876bool AudioFlinger::getMicMute() const
877{
Eric Laurenta1884f92011-08-23 08:25:03 -0700878 status_t ret = initCheck();
879 if (ret != NO_ERROR) {
880 return false;
881 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800882 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700883 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800884 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800886 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700887 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
888 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800889 if (result == NO_ERROR) {
890 mute = mute && state;
891 }
892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800894
895 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896}
897
898status_t AudioFlinger::setMasterMute(bool muted)
899{
John Grossmand8f178d2012-07-20 14:51:35 -0700900 status_t ret = initCheck();
901 if (ret != NO_ERROR) {
902 return ret;
903 }
904
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 // check calling permissions
906 if (!settingsAllowed()) {
907 return PERMISSION_DENIED;
908 }
909
John Grossmanee578c02012-07-23 17:05:46 -0700910 Mutex::Autolock _l(mLock);
911 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700912
John Grossmanee578c02012-07-23 17:05:46 -0700913 // Set master mute in the HALs which support it.
914 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
915 AutoMutex lock(mHardwareLock);
916 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700917
John Grossmanee578c02012-07-23 17:05:46 -0700918 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
919 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700920 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700921 }
John Grossmanee578c02012-07-23 17:05:46 -0700922 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700923 }
924
John Grossmanee578c02012-07-23 17:05:46 -0700925 // Now set the master mute in each playback thread. Playback threads
926 // assigned to HALs which do not have master mute support will apply master
927 // mute during the mix operation. Threads with HALs which do support master
928 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700929 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
930 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
931 continue;
932 }
John Grossmanee578c02012-07-23 17:05:46 -0700933 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700934 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935
936 return NO_ERROR;
937}
938
939float AudioFlinger::masterVolume() const
940{
Glenn Kasten98067102011-12-13 11:47:54 -0800941 Mutex::Autolock _l(mLock);
942 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943}
944
945bool AudioFlinger::masterMute() const
946{
Glenn Kasten98067102011-12-13 11:47:54 -0800947 Mutex::Autolock _l(mLock);
948 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949}
950
John Grossman4ff14ba2012-02-08 16:37:41 -0800951float AudioFlinger::masterVolume_l() const
952{
John Grossman4ff14ba2012-02-08 16:37:41 -0800953 return mMasterVolume;
954}
955
John Grossmand8f178d2012-07-20 14:51:35 -0700956bool AudioFlinger::masterMute_l() const
957{
John Grossmanee578c02012-07-23 17:05:46 -0700958 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700959}
960
Eric Laurent223fd5c2014-11-11 13:43:36 -0800961status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
962{
963 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
964 ALOGW("setStreamVolume() invalid stream %d", stream);
965 return BAD_VALUE;
966 }
967 pid_t caller = IPCThreadState::self()->getCallingPid();
968 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
969 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
970 return PERMISSION_DENIED;
971 }
972
973 return NO_ERROR;
974}
975
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800976status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
977 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978{
979 // check calling permissions
980 if (!settingsAllowed()) {
981 return PERMISSION_DENIED;
982 }
983
Eric Laurent223fd5c2014-11-11 13:43:36 -0800984 status_t status = checkStreamType(stream);
985 if (status != NO_ERROR) {
986 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800988 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989
990 AutoMutex lock(mLock);
991 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700992 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 thread = checkPlaybackThread_l(output);
994 if (thread == NULL) {
995 return BAD_VALUE;
996 }
997 }
998
999 mStreamTypes[stream].volume = value;
1000
1001 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001002 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001003 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 }
1005 } else {
1006 thread->setStreamVolume(stream, value);
1007 }
1008
1009 return NO_ERROR;
1010}
1011
Glenn Kastenfff6d712012-01-12 16:38:12 -08001012status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013{
1014 // check calling permissions
1015 if (!settingsAllowed()) {
1016 return PERMISSION_DENIED;
1017 }
1018
Eric Laurent223fd5c2014-11-11 13:43:36 -08001019 status_t status = checkStreamType(stream);
1020 if (status != NO_ERROR) {
1021 return status;
1022 }
1023 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1024
1025 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001026 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 return BAD_VALUE;
1028 }
1029
Eric Laurent93575202011-01-18 18:39:02 -08001030 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001032 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001033 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034
1035 return NO_ERROR;
1036}
1037
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001038float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001040 status_t status = checkStreamType(stream);
1041 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 return 0.0f;
1043 }
1044
1045 AutoMutex lock(mLock);
1046 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001047 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 PlaybackThread *thread = checkPlaybackThread_l(output);
1049 if (thread == NULL) {
1050 return 0.0f;
1051 }
1052 volume = thread->streamVolume(stream);
1053 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001054 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055 }
1056
1057 return volume;
1058}
1059
Glenn Kastenfff6d712012-01-12 16:38:12 -08001060bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001062 status_t status = checkStreamType(stream);
1063 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 return true;
1065 }
1066
Glenn Kasten6637baa2012-01-09 09:40:36 -08001067 AutoMutex lock(mLock);
1068 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069}
1070
Eric Laurent054d9d32015-04-24 08:48:48 -07001071
1072void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1073{
1074 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1075 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1076 }
1077}
1078
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001079status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001081 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1082 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001083
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 // check calling permissions
1085 if (!settingsAllowed()) {
1086 return PERMISSION_DENIED;
1087 }
1088
Glenn Kasten142f5192014-03-25 17:44:59 -07001089 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1090 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001091 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001092 // result will remain NO_INIT if no audio device is present
1093 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001094 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001095 AutoMutex lock(mHardwareLock);
1096 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1097 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001098 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1099 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001100 // return success if at least one audio device accepts the parameters as not all
1101 // HALs are requested to support all parameters. If no audio device supports the
1102 // requested parameters, the last error is reported.
1103 if (final_result != NO_ERROR) {
1104 final_result = result;
1105 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001106 }
1107 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001108 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001109 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1110 AudioParameter param = AudioParameter(keyValuePairs);
1111 String8 value;
1112 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001113 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1114 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001115 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1116 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001117 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001118 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1119 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001120 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001121 // suspend effects associated with those session IDs
1122 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001123 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001124 thread->setEffectSuspended(FX_IID_AEC,
1125 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001126 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001127 thread->setEffectSuspended(FX_IID_NS,
1128 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001129 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001130 }
1131 }
Eric Laurentbee53372011-08-29 12:42:48 -07001132 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001133 }
1134 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001135 String8 screenState;
1136 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1137 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001138 if (isOff != (AudioFlinger::mScreenState & 1)) {
1139 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001140 }
1141 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001142 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143 }
1144
1145 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1146 // and the thread is exited once the lock is released
1147 sp<ThreadBase> thread;
1148 {
1149 Mutex::Autolock _l(mLock);
1150 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001151 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001153 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001154 // indicate output device change to all input threads for pre processing
1155 AudioParameter param = AudioParameter(keyValuePairs);
1156 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001157 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1158 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001159 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 }
1162 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001163 if (thread != 0) {
1164 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 }
1166 return BAD_VALUE;
1167}
1168
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001169String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001171 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1172 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173
Eric Laurenta4c5a552012-03-29 10:12:40 -07001174 Mutex::Autolock _l(mLock);
1175
Glenn Kasten142f5192014-03-25 17:44:59 -07001176 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001177 String8 out_s8;
1178
Dima Zavin799a70e2011-04-18 16:57:27 -07001179 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001180 String8 s;
1181 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001182 {
1183 AutoMutex lock(mHardwareLock);
1184 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001185 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1186 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001187 mHardwareStatus = AUDIO_HW_IDLE;
1188 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001189 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001190 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001191 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 }
1193
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1195 if (playbackThread != NULL) {
1196 return playbackThread->getParameters(keys);
1197 }
1198 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1199 if (recordThread != NULL) {
1200 return recordThread->getParameters(keys);
1201 }
1202 return String8("");
1203}
1204
Glenn Kastendd8104c2012-07-02 12:42:44 -07001205size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1206 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207{
Eric Laurenta1884f92011-08-23 08:25:03 -07001208 status_t ret = initCheck();
1209 if (ret != NO_ERROR) {
1210 return 0;
1211 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001212 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001213 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001214 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001215 return 0;
1216 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001217
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001218 AutoMutex lock(mHardwareLock);
1219 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001220 audio_config_t config, proposed;
1221 memset(&proposed, 0, sizeof(proposed));
1222 proposed.sample_rate = sampleRate;
1223 proposed.channel_mask = channelMask;
1224 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001225
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001226 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001227 size_t frames;
1228 for (;;) {
1229 // Note: config is currently a const parameter for get_input_buffer_size()
1230 // but we use a copy from proposed in case config changes from the call.
1231 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001232 status_t result = dev->getInputBufferSize(&config, &frames);
1233 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001234 break; // hal success, config is the result
1235 }
1236 // change one parameter of the configuration each iteration to a more "common" value
1237 // to see if the device will support it.
1238 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1239 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1240 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1241 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1242 } else {
1243 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1244 "format %#x, channelMask 0x%X",
1245 sampleRate, format, channelMask);
1246 break; // retries failed, break out of loop with frames == 0.
1247 }
1248 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001249 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001250 if (frames > 0 && config.sample_rate != sampleRate) {
1251 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1252 }
1253 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254}
1255
Glenn Kasten5f972c02014-01-13 09:59:31 -08001256uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258 Mutex::Autolock _l(mLock);
1259
1260 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1261 if (recordThread != NULL) {
1262 return recordThread->getInputFramesLost();
1263 }
1264 return 0;
1265}
1266
1267status_t AudioFlinger::setVoiceVolume(float value)
1268{
Eric Laurenta1884f92011-08-23 08:25:03 -07001269 status_t ret = initCheck();
1270 if (ret != NO_ERROR) {
1271 return ret;
1272 }
1273
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 // check calling permissions
1275 if (!settingsAllowed()) {
1276 return PERMISSION_DENIED;
1277 }
1278
1279 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001280 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001281 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001282 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 mHardwareStatus = AUDIO_HW_IDLE;
1284
1285 return ret;
1286}
1287
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001288status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001289 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291 Mutex::Autolock _l(mLock);
1292
1293 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1294 if (playbackThread != NULL) {
1295 return playbackThread->getRenderPosition(halFrames, dspFrames);
1296 }
1297
1298 return BAD_VALUE;
1299}
1300
1301void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1302{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001304 if (client == 0) {
1305 return;
1306 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001307 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001308 {
1309 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001310 if (mNotificationClients.indexOfKey(pid) < 0) {
1311 sp<NotificationClient> notificationClient = new NotificationClient(this,
1312 client,
1313 pid);
1314 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315
Eric Laurent021cf962014-05-13 10:18:14 -07001316 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317
Marco Nelissen06b46062014-11-14 07:58:25 -08001318 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001319 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001320 }
1321 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322
Eric Laurent021cf962014-05-13 10:18:14 -07001323 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001324 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001325 // the config change is always sent from playback or record threads to avoid deadlock
1326 // with AudioSystem::gLock
1327 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1328 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001331 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1332 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333 }
1334}
1335
1336void AudioFlinger::removeNotificationClient(pid_t pid)
1337{
1338 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001339 {
1340 Mutex::Autolock _cl(mClientLock);
1341 mNotificationClients.removeItem(pid);
1342 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001343
Steve Block3856b092011-10-20 11:56:00 +01001344 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001345 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001346 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001347 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001348 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001349 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001350 if (ref->mPid == pid) {
1351 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001352 mAudioSessionRefs.removeAt(i);
1353 delete ref;
1354 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001355 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001356 } else {
1357 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001358 }
1359 }
1360 if (removed) {
1361 purgeStaleEffects_l();
1362 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363}
1364
Eric Laurent73e26b62015-04-27 16:55:58 -07001365void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001366 const sp<AudioIoDescriptor>& ioDesc,
1367 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368{
Eric Laurent021cf962014-05-13 10:18:14 -07001369 Mutex::Autolock _l(mClientLock);
1370 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1373 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1374 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375 }
1376}
1377
Eric Laurent021cf962014-05-13 10:18:14 -07001378// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379void AudioFlinger::removeClient_l(pid_t pid)
1380{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001381 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001382 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 mClients.removeItem(pid);
1384}
1385
Eric Laurent717e1282012-06-29 16:36:52 -07001386// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001387sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1388 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001389{
1390 sp<PlaybackThread> thread;
1391
1392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1393 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1394 ALOG_ASSERT(thread == 0);
1395 thread = mPlaybackThreads.valueAt(i);
1396 }
1397 }
1398
1399 return thread;
1400}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403
1404// ----------------------------------------------------------------------------
1405
1406AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1407 : RefBase(),
1408 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001409 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301411 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1412 heapSize *= 1024;
1413 if (!heapSize) {
1414 heapSize = kClientSharedHeapSizeBytes;
1415 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1416 // invalidated tracks
1417 if (!audioFlinger->isLowRamDevice()) {
1418 heapSize *= kClientSharedHeapSizeMultiplier;
1419 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001420 }
1421 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422}
1423
Eric Laurent021cf962014-05-13 10:18:14 -07001424// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425AudioFlinger::Client::~Client()
1426{
1427 mAudioFlinger->removeClient_l(mPid);
1428}
1429
Glenn Kasten435dbe62012-01-30 10:15:48 -08001430sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431{
1432 return mMemoryDealer;
1433}
1434
1435// ----------------------------------------------------------------------------
1436
1437AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1438 const sp<IAudioFlingerClient>& client,
1439 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001440 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441{
1442}
1443
1444AudioFlinger::NotificationClient::~NotificationClient()
1445{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446}
1447
Glenn Kasten0f11b512014-01-31 16:18:54 -08001448void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449{
1450 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001451 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452}
1453
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454
1455// ----------------------------------------------------------------------------
1456
1457sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001458 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001460 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001461 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001462 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001463 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001464 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001465 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001466 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001467 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001468 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001469 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001470 sp<IMemory>& cblk,
1471 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 status_t *status)
1473{
1474 sp<RecordThread::RecordTrack> recordTrack;
1475 sp<RecordHandle> recordHandle;
1476 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001478 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479
Glenn Kastend776ac62014-05-07 09:16:09 -07001480 cblk.clear();
1481 buffers.clear();
1482
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001483 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001484 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1485 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001486 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001487 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1488 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001489 updatePid = true;
1490 }
1491
1492 if (updatePid) {
1493 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1494 ALOGW_IF(pid != -1 && pid != callingPid,
1495 "%s uid %d pid %d tried to pass itself off as pid %d",
1496 __func__, callingUid, callingPid, pid);
1497 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001498 }
1499
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001501 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001502 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 lStatus = PERMISSION_DENIED;
1504 goto Exit;
1505 }
1506
Glenn Kasten53b5d092014-02-05 10:00:23 -08001507 // further sample rate checks are performed by createRecordTrack_l()
1508 if (sampleRate == 0) {
1509 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1510 lStatus = BAD_VALUE;
1511 goto Exit;
1512 }
1513
Andy Hung6770c6f2015-04-07 13:43:36 -07001514 // we don't yet support anything other than linear PCM
1515 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001516 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001517 lStatus = BAD_VALUE;
1518 goto Exit;
1519 }
1520
Glenn Kasten53b5d092014-02-05 10:00:23 -08001521 // further channel mask checks are performed by createRecordTrack_l()
1522 if (!audio_is_input_channel(channelMask)) {
1523 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1524 lStatus = BAD_VALUE;
1525 goto Exit;
1526 }
1527
Glenn Kasten05997e22014-03-13 15:08:33 -07001528 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001530 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001532 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536
Eric Laurent021cf962014-05-13 10:18:14 -07001537 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001539 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001540 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1541 lStatus = BAD_VALUE;
1542 goto Exit;
1543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 lSessionId = *sessionId;
1545 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001546 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001547 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548 if (sessionId != NULL) {
1549 *sessionId = lSessionId;
1550 }
1551 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001552 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001553
Glenn Kasten1879fff2012-07-11 15:36:59 -07001554 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001555 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001556 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001557 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001558
1559 if (lStatus == NO_ERROR) {
1560 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1561 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001562 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001563 if (chain != 0) {
1564 Mutex::Autolock _l(thread->mLock);
1565 thread->addEffectChain_l(chain);
1566 }
1567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
Glenn Kastene198c362013-08-13 09:13:36 -07001569
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001570 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001571 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001572 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001573 // Don't hold mClientLock when releasing the reference on the track as the
1574 // destructor will acquire it.
1575 {
1576 Mutex::Autolock _cl(mClientLock);
1577 client.clear();
1578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 goto Exit;
1581 }
1582
Glenn Kastend776ac62014-05-07 09:16:09 -07001583 cblk = recordTrack->getCblk();
1584 buffers = recordTrack->getBuffers();
1585
Glenn Kasten2fc14732013-08-05 14:58:14 -07001586 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588
1589Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001590 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 return recordHandle;
1592}
1593
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001594
1595
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596// ----------------------------------------------------------------------------
1597
Eric Laurenta4c5a552012-03-29 10:12:40 -07001598audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1599{
Eric Laurent44622db2014-08-01 19:00:33 -07001600 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001601 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001602 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001603 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001604 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001605 }
1606 Mutex::Autolock _l(mLock);
1607 return loadHwModule_l(name);
1608}
1609
1610// loadHwModule_l() must be called with AudioFlinger::mLock held
1611audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1612{
1613 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1614 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1615 ALOGW("loadHwModule() module %s already loaded", name);
1616 return mAudioHwDevs.keyAt(i);
1617 }
1618 }
1619
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001620 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001621
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001622 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001623 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001624 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001625 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001626 }
1627
1628 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001629 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001630 mHardwareStatus = AUDIO_HW_IDLE;
1631 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001632 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001633 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001634 }
1635
John Grossmanee578c02012-07-23 17:05:46 -07001636 // Check and cache this HAL's level of support for master mute and master
1637 // volume. If this is the first HAL opened, and it supports the get
1638 // methods, use the initial values provided by the HAL as the current
1639 // master mute and volume settings.
1640
1641 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1642 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001643 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001644
1645 if (0 == mAudioHwDevs.size()) {
1646 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001647 float mv;
1648 if (OK == dev->getMasterVolume(&mv)) {
1649 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001650 }
1651
1652 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001653 bool mm;
1654 if (OK == dev->getMasterMute(&mm)) {
1655 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001656 }
1657 }
1658
Eric Laurenta4c5a552012-03-29 10:12:40 -07001659 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001660 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001661 flags = static_cast<AudioHwDevice::Flags>(flags |
1662 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1663 }
1664
1665 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001666 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001667 flags = static_cast<AudioHwDevice::Flags>(flags |
1668 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1669 }
1670
Eric Laurenta4c5a552012-03-29 10:12:40 -07001671 mHardwareStatus = AUDIO_HW_IDLE;
1672 }
1673
Glenn Kastena13cde92016-03-28 15:26:02 -07001674 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001675 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001676
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001677 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001678
1679 return handle;
1680
1681}
1682
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001683// ----------------------------------------------------------------------------
1684
Glenn Kasten3b16c762012-11-14 08:44:39 -08001685uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001686{
1687 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001688 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001689 return thread != NULL ? thread->sampleRate() : 0;
1690}
1691
Glenn Kastene33054e2012-11-14 12:54:39 -08001692size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001693{
1694 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001695 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001696 return thread != NULL ? thread->frameCountHAL() : 0;
1697}
1698
1699// ----------------------------------------------------------------------------
1700
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001701status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1702{
1703 uid_t uid = IPCThreadState::self()->getCallingUid();
1704 if (uid != AID_SYSTEM) {
1705 return PERMISSION_DENIED;
1706 }
1707 Mutex::Autolock _l(mLock);
1708 if (mIsDeviceTypeKnown) {
1709 return INVALID_OPERATION;
1710 }
1711 mIsLowRamDevice = isLowRamDevice;
1712 mIsDeviceTypeKnown = true;
1713 return NO_ERROR;
1714}
1715
Eric Laurent93c3d412014-08-01 14:48:35 -07001716audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1717{
1718 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001719
1720 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1721 if (index >= 0) {
1722 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1723 mHwAvSyncIds.valueAt(index), sessionId);
1724 return mHwAvSyncIds.valueAt(index);
1725 }
1726
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001727 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001728 if (dev == NULL) {
1729 return AUDIO_HW_SYNC_INVALID;
1730 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001731 String8 reply;
1732 AudioParameter param;
1733 if (dev->getParameters(String8(AUDIO_PARAMETER_HW_AV_SYNC), &reply) == OK) {
1734 param = AudioParameter(reply);
1735 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001736
1737 int value;
1738 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1739 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1740 return AUDIO_HW_SYNC_INVALID;
1741 }
1742
1743 // allow only one session for a given HW A/V sync ID.
1744 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1745 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1746 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1747 value, mHwAvSyncIds.keyAt(i));
1748 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001749 break;
1750 }
1751 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001752
1753 mHwAvSyncIds.add(sessionId, value);
1754
1755 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1756 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1757 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001758 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001759 AudioParameter param = AudioParameter();
1760 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1761 thread->setParameters(param.toString());
1762 break;
1763 }
1764 }
1765
1766 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1767 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001768}
1769
Eric Laurent72e3f392015-05-20 14:43:50 -07001770status_t AudioFlinger::systemReady()
1771{
1772 Mutex::Autolock _l(mLock);
1773 ALOGI("%s", __FUNCTION__);
1774 if (mSystemReady) {
1775 ALOGW("%s called twice", __FUNCTION__);
1776 return NO_ERROR;
1777 }
1778 mSystemReady = true;
1779 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1780 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1781 thread->systemReady();
1782 }
1783 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1784 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1785 thread->systemReady();
1786 }
1787 return NO_ERROR;
1788}
1789
Eric Laurentfa90e842014-10-17 18:12:31 -07001790// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1791void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1792{
1793 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1794 if (index >= 0) {
1795 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1796 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1797 AudioParameter param = AudioParameter();
1798 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1799 thread->setParameters(param.toString());
1800 }
1801}
1802
1803
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001804// ----------------------------------------------------------------------------
1805
Eric Laurent83b88082014-06-20 18:31:16 -07001806
1807sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001808 audio_io_handle_t *output,
1809 audio_config_t *config,
1810 audio_devices_t devices,
1811 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001812 audio_output_flags_t flags)
1813{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001814 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001815 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001816 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001817 }
1818
Eric Laurentcf2c0212014-07-25 16:20:43 -07001819 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001820 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1821 } else {
1822 // Audio Policy does not currently request a specific output handle.
1823 // If this is ever needed, see openInput_l() for example code.
1824 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1825 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001826 }
Eric Laurent83b88082014-06-20 18:31:16 -07001827
1828 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1829
Eric Laurent83b88082014-06-20 18:31:16 -07001830 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001831 // This if statement allows overriding the audio policy settings
1832 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1833 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1834 // Check only for Normal Mixing mode
1835 if (kEnableExtendedPrecision) {
1836 // Specify format (uncomment one below to choose)
1837 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1838 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1839 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1840 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001841 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001842 }
1843 if (kEnableExtendedChannels) {
1844 // Specify channel mask (uncomment one below to choose)
1845 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1846 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1847 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1848 }
Eric Laurent83b88082014-06-20 18:31:16 -07001849 }
1850
Phil Burk062e67a2015-02-11 13:40:50 -08001851 AudioStreamOut *outputStream = NULL;
1852 status_t status = outHwDev->openOutputStream(
1853 &outputStream,
1854 *output,
1855 devices,
1856 flags,
1857 config,
1858 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001859
1860 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001861
Phil Burk062e67a2015-02-11 13:40:50 -08001862 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001863
1864 PlaybackThread *thread;
1865 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001866 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001867 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001868 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1869 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001870 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001871 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001872 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001873 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001874 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001875 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001876 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001877 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001878 return thread;
1879 }
1880
1881 return 0;
1882}
1883
Eric Laurentcf2c0212014-07-25 16:20:43 -07001884status_t AudioFlinger::openOutput(audio_module_handle_t module,
1885 audio_io_handle_t *output,
1886 audio_config_t *config,
1887 audio_devices_t *devices,
1888 const String8& address,
1889 uint32_t *latencyMs,
1890 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891{
Phil Burk062e67a2015-02-11 13:40:50 -08001892 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001893 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001894 (devices != NULL) ? *devices : 0,
1895 config->sample_rate,
1896 config->format,
1897 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001898 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899
Eric Laurentcf2c0212014-07-25 16:20:43 -07001900 if (*devices == AUDIO_DEVICE_NONE) {
1901 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001903
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 Mutex::Autolock _l(mLock);
1905
Eric Laurentcf2c0212014-07-25 16:20:43 -07001906 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001907 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909
1910 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001911 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001912
1913 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001914 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001915 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001916 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001917
1918 AutoMutex lock(mHardwareLock);
1919 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001920 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001922 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001923 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 }
1925
Eric Laurentcf2c0212014-07-25 16:20:43 -07001926 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927}
1928
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001929audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1930 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931{
1932 Mutex::Autolock _l(mLock);
1933 MixerThread *thread1 = checkMixerThread_l(output1);
1934 MixerThread *thread2 = checkMixerThread_l(output2);
1935
1936 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001937 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1938 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001939 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 }
1941
Glenn Kasteneeecb982016-02-26 10:44:04 -08001942 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001943 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 thread->addOutputTrack(thread2);
1945 mPlaybackThreads.add(id, thread);
1946 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001947 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 return id;
1949}
1950
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001951status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952{
Glenn Kastend96c5722012-04-25 13:44:49 -07001953 return closeOutput_nonvirtual(output);
1954}
1955
1956status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1957{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 // keep strong reference on the playback thread so that
1959 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001960 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 {
1962 Mutex::Autolock _l(mLock);
1963 thread = checkPlaybackThread_l(output);
1964 if (thread == NULL) {
1965 return BAD_VALUE;
1966 }
1967
Steve Block3856b092011-10-20 11:56:00 +01001968 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001970 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001972 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001973 DuplicatingThread *dupThread =
1974 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976 }
1977 }
1978 }
1979
1980
1981 mPlaybackThreads.removeItem(output);
1982 // save all effects to the default thread
1983 if (mPlaybackThreads.size()) {
1984 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1985 if (dstThread != NULL) {
1986 // audioflinger lock is held here so the acquisition order of thread locks does not
1987 // matter
1988 Mutex::Autolock _dl(dstThread->mLock);
1989 Mutex::Autolock _sl(thread->mLock);
1990 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1991 for (size_t i = 0; i < effectChains.size(); i ++) {
1992 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 }
1994 }
1995 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001996 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1997 ioDesc->mIoHandle = output;
1998 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 }
2000 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002001 // The thread entity (active unit of execution) is no longer running here,
2002 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003
Eric Laurentf6870ae2015-05-08 10:50:03 -07002004 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002005 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 }
Eric Laurent83b88082014-06-20 18:31:16 -07002007
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 return NO_ERROR;
2009}
2010
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002011void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002012{
2013 AudioStreamOut *out = thread->clearOutput();
2014 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2015 // from now on thread->mOutput is NULL
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002016 static_cast<DeviceHalLocal*>(out->hwDev().get())->closeOutputStream(out->stream);
Eric Laurent83b88082014-06-20 18:31:16 -07002017 delete out;
2018}
2019
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002020void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002021{
2022 mPlaybackThreads.removeItem(thread->mId);
2023 thread->exit();
2024 closeOutputFinish(thread);
2025}
2026
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002027status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028{
2029 Mutex::Autolock _l(mLock);
2030 PlaybackThread *thread = checkPlaybackThread_l(output);
2031
2032 if (thread == NULL) {
2033 return BAD_VALUE;
2034 }
2035
Steve Block3856b092011-10-20 11:56:00 +01002036 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 thread->suspend();
2038
2039 return NO_ERROR;
2040}
2041
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002042status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043{
2044 Mutex::Autolock _l(mLock);
2045 PlaybackThread *thread = checkPlaybackThread_l(output);
2046
2047 if (thread == NULL) {
2048 return BAD_VALUE;
2049 }
2050
Steve Block3856b092011-10-20 11:56:00 +01002051 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052
2053 thread->restore();
2054
2055 return NO_ERROR;
2056}
2057
Eric Laurentcf2c0212014-07-25 16:20:43 -07002058status_t AudioFlinger::openInput(audio_module_handle_t module,
2059 audio_io_handle_t *input,
2060 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002061 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002062 const String8& address,
2063 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002064 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065{
Eric Laurent83b88082014-06-20 18:31:16 -07002066 Mutex::Autolock _l(mLock);
2067
Glenn Kastene7d66712015-03-05 13:46:52 -08002068 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002069 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002070 }
2071
Glenn Kastene7d66712015-03-05 13:46:52 -08002072 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002073
2074 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002075 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002076 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002077 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002079 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002080}
Dima Zavin799a70e2011-04-18 16:57:27 -07002081
Eric Laurent83b88082014-06-20 18:31:16 -07002082sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002083 audio_io_handle_t *input,
2084 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002085 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086 const String8& address,
2087 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002088 audio_input_flags_t flags)
2089{
Glenn Kastene7d66712015-03-05 13:46:52 -08002090 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002091 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002092 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002093 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002094 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002095
Glenn Kasteneeecb982016-02-26 10:44:04 -08002096 // Audio Policy can request a specific handle for hardware hotword.
2097 // The goal here is not to re-open an already opened input.
2098 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002100 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2101 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2102 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2103 return 0;
2104 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2105 // This should not happen in a transient state with current design.
2106 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2107 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002108 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002109
Eric Laurentcf2c0212014-07-25 16:20:43 -07002110 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002111 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002112 audio_stream_in_t *inStream = NULL;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002113 status_t status = static_cast<DeviceHalLocal*>(inHwHal.get())->openInputStream(
2114 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002115 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002116 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002117 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002118 halconfig.sample_rate,
2119 halconfig.format,
2120 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002121 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002122 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002124 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002125 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002126 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002127 audio_is_linear_pcm(config->format) &&
2128 audio_is_linear_pcm(halconfig.format) &&
2129 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002130 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2131 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002132 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002133 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002134 inStream = NULL;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002135 status = static_cast<DeviceHalLocal*>(inHwHal.get())->openInputStream(
2136 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002137 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 }
2139
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002140 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002141
Glenn Kasten46909e72013-02-26 09:20:22 -08002142#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002143 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2144 // or (re-)create if current Pipe is idle and does not match the new format
2145 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002146 enum {
2147 TEE_SINK_NO, // don't copy input
2148 TEE_SINK_NEW, // copy input using a new pipe
2149 TEE_SINK_OLD, // copy input using an existing pipe
2150 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002151 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2152 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002153 if (!mTeeSinkInputEnabled) {
2154 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002155 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002156 kind = TEE_SINK_NO;
2157 } else if (mRecordTeeSink == 0) {
2158 kind = TEE_SINK_NEW;
2159 } else if (mRecordTeeSink->getStrongCount() != 1) {
2160 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002161 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002162 kind = TEE_SINK_OLD;
2163 } else {
2164 kind = TEE_SINK_NEW;
2165 }
2166 switch (kind) {
2167 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002168 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002169 size_t numCounterOffers = 0;
2170 const NBAIO_Format offers[1] = {format};
2171 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2172 ALOG_ASSERT(index == 0);
2173 PipeReader *pipeReader = new PipeReader(*pipe);
2174 numCounterOffers = 0;
2175 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2176 ALOG_ASSERT(index == 0);
2177 mRecordTeeSink = pipe;
2178 mRecordTeeSource = pipeReader;
2179 teeSink = pipe;
2180 }
2181 break;
2182 case TEE_SINK_OLD:
2183 teeSink = mRecordTeeSink;
2184 break;
2185 case TEE_SINK_NO:
2186 default:
2187 break;
2188 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002189#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002190
Eric Laurent05067782016-06-01 18:27:28 -07002191 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002192
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002193 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002194 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002195 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002196 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002197 inputStream,
2198 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002199 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002200 devices,
2201 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002202#ifdef TEE_SINK
2203 , teeSink
2204#endif
2205 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002206 mRecordThreads.add(*input, thread);
2207 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002208 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 }
2210
Eric Laurentcf2c0212014-07-25 16:20:43 -07002211 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212 return 0;
2213}
2214
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002215status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216{
Glenn Kastend96c5722012-04-25 13:44:49 -07002217 return closeInput_nonvirtual(input);
2218}
2219
2220status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2221{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 // keep strong reference on the record thread so that
2223 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002224 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 {
2226 Mutex::Autolock _l(mLock);
2227 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002228 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 return BAD_VALUE;
2230 }
2231
Steve Block3856b092011-10-20 11:56:00 +01002232 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002233
2234 // If we still have effect chains, it means that a client still holds a handle
2235 // on at least one effect. We must either move the chain to an existing thread with the
2236 // same session ID or put it aside in case a new record thread is opened for a
2237 // new capture on the same session
2238 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002239 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002240 Mutex::Autolock _sl(thread->mLock);
2241 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002242 // Note: maximum one chain per record thread
2243 if (effectChains.size() != 0) {
2244 chain = effectChains[0];
2245 }
2246 }
2247 if (chain != 0) {
2248 // first check if a record thread is already opened with a client on the same session.
2249 // This should only happen in case of overlap between one thread tear down and the
2250 // creation of its replacement
2251 size_t i;
2252 for (i = 0; i < mRecordThreads.size(); i++) {
2253 sp<RecordThread> t = mRecordThreads.valueAt(i);
2254 if (t == thread) {
2255 continue;
2256 }
2257 if (t->hasAudioSession(chain->sessionId()) != 0) {
2258 Mutex::Autolock _l(t->mLock);
2259 ALOGV("closeInput() found thread %d for effect session %d",
2260 t->id(), chain->sessionId());
2261 t->addEffectChain_l(chain);
2262 break;
2263 }
2264 }
2265 // put the chain aside if we could not find a record thread with the same session id.
2266 if (i == mRecordThreads.size()) {
2267 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002268 }
2269 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002270 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2271 ioDesc->mIoHandle = input;
2272 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002273 mRecordThreads.removeItem(input);
2274 }
Eric Laurent83b88082014-06-20 18:31:16 -07002275 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2276 // we have a different lock for notification client
2277 closeInputFinish(thread);
2278 return NO_ERROR;
2279}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002281void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002282{
2283 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002284 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002285 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002286 // from now on thread->mInput is NULL
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002287 static_cast<DeviceHalLocal*>(in->hwDev().get())->closeInputStream(in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002288 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002289}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002291void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002292{
2293 mRecordThreads.removeItem(thread->mId);
2294 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295}
2296
Glenn Kastend2304db2014-02-03 07:40:31 -08002297status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298{
2299 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002300 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301
2302 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2303 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002304 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002305 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306
2307 return NO_ERROR;
2308}
2309
2310
Glenn Kasteneeecb982016-02-26 10:44:04 -08002311audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312{
Glenn Kasten9d003132016-04-06 14:38:09 -07002313 // This is a binder API, so a malicious client could pass in a bad parameter.
2314 // Check for that before calling the internal API nextUniqueId().
2315 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2316 ALOGE("newAudioUniqueId invalid use %d", use);
2317 return AUDIO_UNIQUE_ID_ALLOCATE;
2318 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002319 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320}
2321
Glenn Kastend848eb42016-03-08 13:42:11 -08002322void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002323{
2324 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002325 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002326 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2327 if (pid != -1 && (caller == getpid_cached)) {
2328 caller = pid;
2329 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002330
Eric Laurent021cf962014-05-13 10:18:14 -07002331 {
2332 Mutex::Autolock _cl(mClientLock);
2333 // Ignore requests received from processes not known as notification client. The request
2334 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2335 // called from a different pid leaving a stale session reference. Also we don't know how
2336 // to clear this reference if the client process dies.
2337 if (mNotificationClients.indexOfKey(caller) < 0) {
2338 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2339 return;
2340 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002341 }
2342
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002343 size_t num = mAudioSessionRefs.size();
2344 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002345 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002346 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2347 ref->mCnt++;
2348 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002349 return;
2350 }
2351 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002352 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2353 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002354}
2355
Glenn Kastend848eb42016-03-08 13:42:11 -08002356void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002357{
2358 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002359 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002360 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2361 if (pid != -1 && (caller == getpid_cached)) {
2362 caller = pid;
2363 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002364 size_t num = mAudioSessionRefs.size();
2365 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002366 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002367 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2368 ref->mCnt--;
2369 ALOGV(" decremented refcount to %d", ref->mCnt);
2370 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002371 mAudioSessionRefs.removeAt(i);
2372 delete ref;
2373 purgeStaleEffects_l();
2374 }
2375 return;
2376 }
2377 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002378 // If the caller is mediaserver it is likely that the session being released was acquired
2379 // on behalf of a process not in notification clients and we ignore the warning.
2380 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002381}
2382
2383void AudioFlinger::purgeStaleEffects_l() {
2384
Steve Block3856b092011-10-20 11:56:00 +01002385 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002386
2387 Vector< sp<EffectChain> > chains;
2388
2389 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2390 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2391 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2392 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002393 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2394 chains.push(ec);
2395 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002396 }
2397 }
2398 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2399 sp<RecordThread> t = mRecordThreads.valueAt(i);
2400 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2401 sp<EffectChain> ec = t->mEffectChains[j];
2402 chains.push(ec);
2403 }
2404 }
2405
2406 for (size_t i = 0; i < chains.size(); i++) {
2407 sp<EffectChain> ec = chains[i];
2408 int sessionid = ec->sessionId();
2409 sp<ThreadBase> t = ec->mThread.promote();
2410 if (t == 0) {
2411 continue;
2412 }
2413 size_t numsessionrefs = mAudioSessionRefs.size();
2414 bool found = false;
2415 for (size_t k = 0; k < numsessionrefs; k++) {
2416 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002417 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002418 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002419 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002420 found = true;
2421 break;
2422 }
2423 }
2424 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002425 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002426 // remove all effects from the chain
2427 while (ec->mEffects.size()) {
2428 sp<EffectModule> effect = ec->mEffects[0];
2429 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002430 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002431 if (effect->purgeHandles()) {
2432 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002433 }
2434 AudioSystem::unregisterEffect(effect->id());
2435 }
2436 }
2437 }
2438 return;
2439}
2440
Glenn Kasteneeecb982016-02-26 10:44:04 -08002441// checkThread_l() must be called with AudioFlinger::mLock held
2442AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2443{
2444 ThreadBase *thread = NULL;
2445 switch (audio_unique_id_get_use(ioHandle)) {
2446 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2447 thread = checkPlaybackThread_l(ioHandle);
2448 break;
2449 case AUDIO_UNIQUE_ID_USE_INPUT:
2450 thread = checkRecordThread_l(ioHandle);
2451 break;
2452 default:
2453 break;
2454 }
2455 return thread;
2456}
2457
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002459AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460{
Glenn Kastena1117922012-01-26 10:53:32 -08002461 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462}
2463
2464// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002465AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466{
2467 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002468 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469}
2470
2471// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002472AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473{
Glenn Kastena1117922012-01-26 10:53:32 -08002474 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475}
2476
Glenn Kasteneeecb982016-02-26 10:44:04 -08002477audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478{
Glenn Kasten9d003132016-04-06 14:38:09 -07002479 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002480 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002481 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2482 for (int retry = 0; retry < maxRetries; retry++) {
2483 // The cast allows wraparound from max positive to min negative instead of abort
2484 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2485 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2486 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2487 // allow wrap by skipping 0 and -1 for session ids
2488 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2489 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2490 return (audio_unique_id_t) (base | use);
2491 }
2492 }
2493 // We have no way of recovering from wraparound
2494 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2495 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496}
2497
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002498AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002499{
2500 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2501 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002502 if(thread->isDuplicating()) {
2503 continue;
2504 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002505 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002506 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002507 return thread;
2508 }
2509 }
2510 return NULL;
2511}
2512
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002513audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002514{
2515 PlaybackThread *thread = primaryPlaybackThread_l();
2516
2517 if (thread == NULL) {
2518 return 0;
2519 }
2520
Eric Laurentf1c04f92012-08-28 14:26:53 -07002521 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002522}
2523
Glenn Kastena7335632016-06-09 17:09:53 -07002524AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2525{
2526 size_t minFrameCount = 0;
2527 PlaybackThread *minThread = NULL;
2528 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2529 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2530 if (!thread->isDuplicating()) {
2531 size_t frameCount = thread->frameCountHAL();
2532 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2533 (frameCount == minFrameCount && thread->hasFastMixer() &&
2534 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2535 minFrameCount = frameCount;
2536 minThread = thread;
2537 }
2538 }
2539 }
2540 return minThread;
2541}
2542
Eric Laurenta011e352012-03-29 15:51:43 -07002543sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002544 audio_session_t triggerSession,
2545 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002546 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002547 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002548{
2549 Mutex::Autolock _l(mLock);
2550
2551 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2552 status_t playStatus = NAME_NOT_FOUND;
2553 status_t recStatus = NAME_NOT_FOUND;
2554 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2555 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2556 if (playStatus == NO_ERROR) {
2557 return event;
2558 }
2559 }
2560 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2561 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2562 if (recStatus == NO_ERROR) {
2563 return event;
2564 }
2565 }
2566 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2567 mPendingSyncEvents.add(event);
2568 } else {
2569 ALOGV("createSyncEvent() invalid event %d", event->type());
2570 event.clear();
2571 }
2572 return event;
2573}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002574
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575// ----------------------------------------------------------------------------
2576// Effect management
2577// ----------------------------------------------------------------------------
2578
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002579sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2580 return mEffectsFactoryHal;
2581}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582
Glenn Kastenf587ba52012-01-26 16:25:10 -08002583status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584{
2585 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002586 if (mEffectsFactoryHal.get()) {
2587 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2588 } else {
2589 return -ENODEV;
2590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591}
2592
Glenn Kastenf587ba52012-01-26 16:25:10 -08002593status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594{
2595 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002596 if (mEffectsFactoryHal.get()) {
2597 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2598 } else {
2599 return -ENODEV;
2600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601}
2602
Glenn Kasten5e92a782012-01-30 07:40:52 -08002603status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002604 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605{
2606 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002607 if (mEffectsFactoryHal.get()) {
2608 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2609 } else {
2610 return -ENODEV;
2611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612}
2613
2614
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002615sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 effect_descriptor_t *pDesc,
2617 const sp<IEffectClient>& effectClient,
2618 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002619 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002620 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002621 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 status_t *status,
2623 int *id,
2624 int *enabled)
2625{
2626 status_t lStatus = NO_ERROR;
2627 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002630 pid_t pid = IPCThreadState::self()->getCallingPid();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002631 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2632 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633
2634 if (pDesc == NULL) {
2635 lStatus = BAD_VALUE;
2636 goto Exit;
2637 }
2638
Eric Laurent84e9a102010-09-23 16:10:16 -07002639 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002640 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002641 lStatus = PERMISSION_DENIED;
2642 goto Exit;
2643 }
2644
Dima Zavinfce7a472011-04-19 22:30:36 -07002645 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002646 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002647 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002648 lStatus = PERMISSION_DENIED;
2649 goto Exit;
2650 }
2651
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002652 if (mEffectsFactoryHal.get() == NULL) {
2653 lStatus = NO_INIT;
2654 goto Exit;
2655 }
2656
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002658 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002660 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002662 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 goto Exit;
2664 }
2665 } else {
2666 // if uuid is not specified, look for an available implementation
2667 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002668 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002669 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
2673 uint32_t numEffects = 0;
2674 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002675 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 bool found = false;
2677
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002678 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002680 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 goto Exit;
2682 }
2683 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002684 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002686 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 continue;
2688 }
2689 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2690 // If matching type found save effect descriptor. If the session is
2691 // 0 and the effect is not auxiliary, continue enumeration in case
2692 // an auxiliary version of this effect type is available
2693 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002694 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002695 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2697 break;
2698 }
2699 }
2700 }
2701 if (!found) {
2702 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002703 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 goto Exit;
2705 }
2706 // For same effect type, chose auxiliary version over insert version if
2707 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002708 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002710 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 }
2712 }
2713
2714 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002715 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2717 lStatus = INVALID_OPERATION;
2718 goto Exit;
2719 }
2720
Eric Laurent59255e42011-07-27 19:49:51 -07002721 // check recording permission for visualizer
2722 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002723 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002724 lStatus = PERMISSION_DENIED;
2725 goto Exit;
2726 }
2727
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002729 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002730 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002731 // if the output returned by getOutputForEffect() is removed before we lock the
2732 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2733 // and we will exit safely
2734 io = AudioSystem::getOutputForEffect(&desc);
2735 ALOGV("createEffect got output %d", io);
2736 }
2737
2738 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739
2740 // If output is not specified try to find a matching audio session ID in one of the
2741 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002742 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2743 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002744 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002745 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002746 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2747 // output must be specified by AudioPolicyManager when using session
2748 // AUDIO_SESSION_OUTPUT_STAGE
2749 lStatus = BAD_VALUE;
2750 goto Exit;
2751 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002752 // look for the thread where the specified audio session is present
2753 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2754 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2755 io = mPlaybackThreads.keyAt(i);
2756 break;
2757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002759 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002760 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2761 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2762 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002763 break;
2764 }
2765 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002766 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002767 // If no output thread contains the requested session ID, default to
2768 // first output. The effect chain will be moved to the correct output
2769 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002770 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002771 io = mPlaybackThreads.keyAt(0);
2772 }
Steve Block3856b092011-10-20 11:56:00 +01002773 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002774 }
2775 ThreadBase *thread = checkRecordThread_l(io);
2776 if (thread == NULL) {
2777 thread = checkPlaybackThread_l(io);
2778 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002779 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002780 lStatus = BAD_VALUE;
2781 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002782 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002783 } else {
2784 // Check if one effect chain was awaiting for an effect to be created on this
2785 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002786 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002787 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002788 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002789 thread->addEffectChain_l(chain);
2790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002792
Eric Laurent021cf962014-05-13 10:18:14 -07002793 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002795 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002796 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2797 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 if (handle != 0 && id != NULL) {
2799 *id = handle->id();
2800 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002801 if (handle == 0) {
2802 // remove local strong reference to Client with mClientLock held
2803 Mutex::Autolock _cl(mClientLock);
2804 client.clear();
2805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 }
2807
2808Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002809 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 return handle;
2811}
2812
Glenn Kastend848eb42016-03-08 13:42:11 -08002813status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002814 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002815{
Steve Block3856b092011-10-20 11:56:00 +01002816 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002817 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002818 Mutex::Autolock _l(mLock);
2819 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002820 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002821 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 }
Eric Laurentde070132010-07-13 04:45:46 -07002823 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2824 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002825 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002826 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 }
Eric Laurentde070132010-07-13 04:45:46 -07002828 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2829 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002830 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002831 return BAD_VALUE;
2832 }
2833
2834 Mutex::Autolock _dl(dstThread->mLock);
2835 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002836 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837}
2838
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002839// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002840status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002841 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002842 AudioFlinger::PlaybackThread *dstThread,
2843 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002844{
Steve Block3856b092011-10-20 11:56:00 +01002845 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002846 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002847
Eric Laurent59255e42011-07-27 19:49:51 -07002848 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002849 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002850 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002851 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002852 return INVALID_OPERATION;
2853 }
2854
Eric Laurent4c415062016-06-17 16:14:16 -07002855 // Check whether the destination thread and all effects in the chain are compatible
2856 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002857 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002858 " destination thread %p is not compatible with effects in the chain",
2859 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002860 return INVALID_OPERATION;
2861 }
2862
Eric Laurent39e94f82010-07-28 01:32:47 -07002863 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002864 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002865 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002866 // removed.
2867 srcThread->removeEffectChain_l(chain);
2868
2869 // transfer all effects one by one so that new effect chain is created on new thread with
2870 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002871 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002872 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002873 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002874 Vector< sp<EffectModule> > removed;
2875 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002876 while (effect != 0) {
2877 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002878 removed.add(effect);
2879 status = dstThread->addEffect_l(effect);
2880 if (status != NO_ERROR) {
2881 break;
2882 }
Eric Laurentec35a142011-10-05 17:42:25 -07002883 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2884 if (effect->state() == EffectModule::ACTIVE ||
2885 effect->state() == EffectModule::STOPPING) {
2886 effect->start();
2887 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002888 // if the move request is not received from audio policy manager, the effect must be
2889 // re-registered with the new strategy and output
2890 if (dstChain == 0) {
2891 dstChain = effect->chain().promote();
2892 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002893 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002894 status = NO_INIT;
2895 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002896 }
2897 strategy = dstChain->strategy();
2898 }
2899 if (reRegister) {
2900 AudioSystem::unregisterEffect(effect->id());
2901 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002902 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002903 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002904 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002905 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002906 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002907 }
Eric Laurentde070132010-07-13 04:45:46 -07002908 effect = chain->getEffectFromId_l(0);
2909 }
2910
Eric Laurent5baf2af2013-09-12 17:37:00 -07002911 if (status != NO_ERROR) {
2912 for (size_t i = 0; i < removed.size(); i++) {
2913 srcThread->addEffect_l(removed[i]);
2914 if (dstChain != 0 && reRegister) {
2915 AudioSystem::unregisterEffect(removed[i]->id());
2916 AudioSystem::registerEffect(&removed[i]->desc(),
2917 srcThread->id(),
2918 strategy,
2919 sessionId,
2920 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002921 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002922 }
2923 }
2924 }
2925
2926 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927}
2928
Eric Laurent5baf2af2013-09-12 17:37:00 -07002929bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002930{
2931 if (mGlobalEffectEnableTime != 0 &&
2932 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2933 return true;
2934 }
2935
2936 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2937 sp<EffectChain> ec =
2938 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002939 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002940 return true;
2941 }
2942 }
2943 return false;
2944}
2945
Eric Laurent5baf2af2013-09-12 17:37:00 -07002946void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002947{
2948 Mutex::Autolock _l(mLock);
2949
2950 mGlobalEffectEnableTime = systemTime();
2951
2952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2953 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2954 if (t->mType == ThreadBase::OFFLOAD) {
2955 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2956 }
2957 }
2958
2959}
2960
Eric Laurentaaa44472014-09-12 17:41:50 -07002961status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2962{
Glenn Kastend848eb42016-03-08 13:42:11 -08002963 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002964 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002965 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002966 if (index >= 0) {
2967 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2968 return ALREADY_EXISTS;
2969 }
2970 mOrphanEffectChains.add(session, chain);
2971 return NO_ERROR;
2972}
2973
2974sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2975{
2976 sp<EffectChain> chain;
2977 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002978 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002979 if (index >= 0) {
2980 chain = mOrphanEffectChains.valueAt(index);
2981 mOrphanEffectChains.removeItemsAt(index);
2982 }
2983 return chain;
2984}
2985
2986bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2987{
2988 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002989 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002990 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002991 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002992 if (index >= 0) {
2993 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2994 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002995 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002996 mOrphanEffectChains.removeItemsAt(index);
2997 }
2998 return true;
2999 }
3000 return false;
3001}
3002
3003
Glenn Kastenda6ef132013-01-10 12:31:01 -08003004struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003005#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3006 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003007};
3008
3009int comparEntry(const void *p1, const void *p2)
3010{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003011 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003012}
3013
Glenn Kasten46909e72013-02-26 09:20:22 -08003014#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003015void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016{
Eric Laurent81784c32012-11-19 14:55:58 -08003017 NBAIO_Source *teeSource = source.get();
3018 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003019 // .wav rotation
3020 // There is a benign race condition if 2 threads call this simultaneously.
3021 // They would both traverse the directory, but the result would simply be
3022 // failures at unlink() which are ignored. It's also unlikely since
3023 // normally dumpsys is only done by bugreport or from the command line.
3024 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003025 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003026 size_t teePathLen = strlen(teePath);
3027 DIR *dir = opendir(teePath);
3028 teePath[teePathLen++] = '/';
3029 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003030#define TEE_MAX_SORT 20 // number of entries to sort
3031#define TEE_MAX_KEEP 10 // number of entries to keep
3032 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003033 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003034 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003035 struct dirent de;
3036 struct dirent *result = NULL;
3037 int rc = readdir_r(dir, &de, &result);
3038 if (rc != 0) {
3039 ALOGW("readdir_r failed %d", rc);
3040 break;
3041 }
3042 if (result == NULL) {
3043 break;
3044 }
3045 if (result != &de) {
3046 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3047 break;
3048 }
3049 // ignore non .wav file entries
3050 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003051 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003052 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3053 continue;
3054 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003055 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003056 }
3057 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003058 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003059 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003060 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3061 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003062 (void) unlink(teePath);
3063 }
3064 }
3065 } else {
3066 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003067 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003068 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003069 }
3070 }
Eric Laurent81784c32012-11-19 14:55:58 -08003071 char teeTime[16];
3072 struct timeval tv;
3073 gettimeofday(&tv, NULL);
3074 struct tm tm;
3075 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003076 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3077 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3078 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3079 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003080 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003081 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003082 char wavHeader[44];
3083 memcpy(wavHeader,
3084 "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",
3085 sizeof(wavHeader));
3086 NBAIO_Format format = teeSource->format();
3087 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003088 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003089 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003090 wavHeader[22] = channelCount; // number of channels
3091 wavHeader[24] = sampleRate; // sample rate
3092 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003093 wavHeader[32] = frameSize; // block alignment
3094 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003095 write(teeFd, wavHeader, sizeof(wavHeader));
3096 size_t total = 0;
3097 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003098#define TEE_SINK_READ 1024 // frames per I/O operation
3099 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003100 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003101 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003102 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003103 bool wasFirstRead = firstRead;
3104 firstRead = false;
3105 if (actual <= 0) {
3106 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3107 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003108 }
Eric Laurent81784c32012-11-19 14:55:58 -08003109 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003110 }
Eric Laurent81784c32012-11-19 14:55:58 -08003111 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003112 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003113 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003114 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003115 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003116 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003117 uint32_t temp = 44 + total * frameSize - 8;
3118 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003119 write(teeFd, &temp, sizeof(temp));
3120 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003121 temp = total * frameSize;
3122 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003123 write(teeFd, &temp, sizeof(temp));
3124 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003125 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003126 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003127 }
Eric Laurent59255e42011-07-27 19:49:51 -07003128 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003129 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003130 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003131 }
Eric Laurent59255e42011-07-27 19:49:51 -07003132 }
3133 }
3134}
Glenn Kasten46909e72013-02-26 09:20:22 -08003135#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003136
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137// ----------------------------------------------------------------------------
3138
3139status_t AudioFlinger::onTransact(
3140 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3141{
3142 return BnAudioFlinger::onTransact(code, data, reply, flags);
3143}
3144
Glenn Kasten63238ef2015-03-02 15:50:29 -08003145} // namespace android