blob: 3d1f268583722555ef4dc906378e1fd25a1424cd [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
Dima Zavinfce7a472011-04-19 22:30:36 -070044#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080073#include "TypedLogger.h"
74
Mathias Agopian65ab4712010-07-14 17:59:35 -070075// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
John Grossman1c345192012-03-27 14:00:17 -070077// Note: the following macro is used for extremely verbose logging message. In
78// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
79// 0; but one side effect of this is to turn all LOGV's as well. Some messages
80// are so verbose that we want to suppress them even when we have ALOG_ASSERT
81// turned on. Do not uncomment the #def below unless you really know what you
82// are doing and want to see all of the extremely verbose messages.
83//#define VERY_VERY_VERBOSE_LOGGING
84#ifdef VERY_VERY_VERBOSE_LOGGING
85#define ALOGVV ALOGV
86#else
87#define ALOGVV(a...) do { } while(0)
88#endif
Eric Laurentde070132010-07-13 04:45:46 -070089
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Glenn Kastenec1d6b52011-12-12 09:04:45 -080092static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
93static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070094static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070095static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070096
Glenn Kasten58912562012-04-03 10:45:00 -070097
John Grossman4ff14ba2012-02-08 16:37:41 -080098nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700101
Eric Laurentfc235202016-12-20 18:48:17 -0800102
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104bool AudioFlinger::mTeeSinkInputEnabled = false;
105bool AudioFlinger::mTeeSinkOutputEnabled = false;
106bool AudioFlinger::mTeeSinkTrackEnabled = false;
107
108size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
109size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
110size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800111#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800112
Eric Laurent813e2a72013-08-31 12:59:48 -0700113// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
114// we define a minimum time during which a global effect is considered enabled.
115static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
116
Eric Laurentfc235202016-12-20 18:48:17 -0800117Mutex gLock;
118wp<AudioFlinger> gAudioFlinger;
119
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120// ----------------------------------------------------------------------------
121
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700122std::string formatToString(audio_format_t format) {
123 std::string result;
124 FormatConverter::toString(format, result);
125 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800126}
127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128// ----------------------------------------------------------------------------
129
130AudioFlinger::AudioFlinger()
131 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800132 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800133 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700134 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800135 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800136 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700137 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800138 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700139 mBtNrecIsOff(false),
140 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700141 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700142 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700143 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700145 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
146 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
147 // zero ID has a special meaning, so unavailable
148 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
149 }
150
Glenn Kasten949a9262013-04-16 12:35:20 -0700151 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800152 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800153 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800154 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
155 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800156 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700157
Wei Jia3f273d12015-11-24 09:06:49 -0800158 // reset battery stats.
159 // if the audio service has crashed, battery stats could be left
160 // in bad state, reset the state upon service start.
161 BatteryNotifier::getInstance().noteResetAudio();
162
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700163 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700164 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
165
Glenn Kasten46909e72013-02-26 09:20:22 -0800166#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800167 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800168 (void) property_get("ro.debuggable", value, "0");
169 int debuggable = atoi(value);
170 int teeEnabled = 0;
171 if (debuggable) {
172 (void) property_get("af.tee", value, "0");
173 teeEnabled = atoi(value);
174 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800175 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700176 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800177 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700178 }
179 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700181 }
182 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700184 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800185#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700186}
187
188void AudioFlinger::onFirstRef()
189{
Eric Laurent93575202011-01-18 18:39:02 -0800190 Mutex::Autolock _l(mLock);
191
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800193 char val_str[PROPERTY_VALUE_MAX] = { 0 };
194 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
195 uint32_t int_val;
196 if (1 == sscanf(val_str, "%u", &int_val)) {
197 mStandbyTimeInNsecs = milliseconds(int_val);
198 ALOGI("Using %u mSec as standby time.", int_val);
199 } else {
200 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
201 ALOGI("Using default %u mSec as standby time.",
202 (uint32_t)(mStandbyTimeInNsecs / 1000000));
203 }
204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700205
Eric Laurent1c333e22014-05-20 10:48:17 -0700206 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700207
Eric Laurenta4c5a552012-03-29 10:12:40 -0700208 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800209
210 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211}
212
213AudioFlinger::~AudioFlinger()
214{
215 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700216 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700217 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
219 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700220 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700221 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700223
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
225 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700226 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700228
229 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800230 if (mLogMemoryDealer != 0) {
231 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
232 if (binder != 0) {
233 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
234 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
235 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
236 mUnregisteredWriters.pop();
237 mediaLogService->unregisterWriter(iMemory);
238 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700239 }
240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241}
242
Eric Laurentfc235202016-12-20 18:48:17 -0800243//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800244__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800245status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
246 const audio_attributes_t *attr,
247 audio_config_base_t *config,
248 const MmapStreamInterface::Client& client,
249 audio_port_handle_t *deviceId,
250 const sp<MmapStreamCallback>& callback,
251 sp<MmapStreamInterface>& interface)
252{
253 sp<AudioFlinger> af;
254 {
255 Mutex::Autolock _l(gLock);
256 af = gAudioFlinger.promote();
257 }
258 status_t ret = NO_INIT;
259 if (af != 0) {
260 ret = af->openMmapStream(
261 direction, attr, config, client, deviceId, callback, interface);
262 }
263 return ret;
264}
265
Eric Laurent6acd1d42017-01-04 14:23:29 -0800266status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
267 const audio_attributes_t *attr,
268 audio_config_base_t *config,
269 const MmapStreamInterface::Client& client,
270 audio_port_handle_t *deviceId,
271 const sp<MmapStreamCallback>& callback,
272 sp<MmapStreamInterface>& interface)
Eric Laurentfc235202016-12-20 18:48:17 -0800273{
274 status_t ret = initCheck();
275 if (ret != NO_ERROR) {
276 return ret;
277 }
278
Eric Laurent6acd1d42017-01-04 14:23:29 -0800279 audio_session_t sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
280 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
281 audio_io_handle_t io;
282 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
283 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
284 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
285 fullConfig.sample_rate = config->sample_rate;
286 fullConfig.channel_mask = config->channel_mask;
287 fullConfig.format = config->format;
288 ret = AudioSystem::getOutputForAttr(attr, &io,
289 sessionId,
290 &streamType, client.clientUid,
291 &fullConfig,
292 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT),
293 *deviceId, &portId);
294 } else {
295 ret = AudioSystem::getInputForAttr(attr, &io,
296 sessionId,
297 client.clientPid,
298 client.clientUid,
299 config,
300 AUDIO_INPUT_FLAG_MMAP_NOIRQ, *deviceId, &portId);
301 }
302 if (ret != NO_ERROR) {
303 return ret;
304 }
305
306 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
307 // audio policy manager and we can retrieve it
308 sp<MmapThread> thread = mMmapThreads.valueFor(io);
309 if (thread != 0) {
310 interface = new MmapThreadHandle(thread);
311 thread->configure(attr, streamType, sessionId, callback, portId);
312 } else {
313 ret = NO_INIT;
314 }
315
316 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
317
Eric Laurentfc235202016-12-20 18:48:17 -0800318 return ret;
319}
320
Eric Laurenta4c5a552012-03-29 10:12:40 -0700321static const char * const audio_interfaces[] = {
322 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
323 AUDIO_HARDWARE_MODULE_ID_A2DP,
324 AUDIO_HARDWARE_MODULE_ID_USB,
325};
326#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
327
Phil Burk062e67a2015-02-11 13:40:50 -0800328AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700329 audio_module_handle_t module,
330 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700331{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700332 // if module is 0, the request comes from an old policy manager and we should load
333 // well known modules
334 if (module == 0) {
335 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
336 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
337 loadHwModule_l(audio_interfaces[i]);
338 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700339 // then try to find a module supporting the requested device.
340 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
341 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700342 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
343 uint32_t supportedDevices;
344 if (dev->getSupportedDevices(&supportedDevices) == OK &&
345 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700346 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700347 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700348 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700349 } else {
350 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700351 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
352 if (audioHwDevice != NULL) {
353 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700354 }
355 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700356
Dima Zavin799a70e2011-04-18 16:57:27 -0700357 return NULL;
358}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700359
Glenn Kasten0f11b512014-01-31 16:18:54 -0800360void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361{
362 const size_t SIZE = 256;
363 char buffer[SIZE];
364 String8 result;
365
366 result.append("Clients:\n");
367 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800368 sp<Client> client = mClients.valueAt(i).promote();
369 if (client != 0) {
370 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
371 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 }
373 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700374
Eric Laurentd1b28d42013-09-18 18:47:13 -0700375 result.append("Notification Clients:\n");
376 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
377 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
378 result.append(buffer);
379 }
380
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700381 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800382 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700383 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
384 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800385 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700386 result.append(buffer);
387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389}
390
391
Glenn Kasten0f11b512014-01-31 16:18:54 -0800392void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393{
394 const size_t SIZE = 256;
395 char buffer[SIZE];
396 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800397 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700398
John Grossman4ff14ba2012-02-08 16:37:41 -0800399 snprintf(buffer, SIZE, "Hardware status: %d\n"
400 "Standby Time mSec: %u\n",
401 hardwareStatus,
402 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 result.append(buffer);
404 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405}
406
Glenn Kasten0f11b512014-01-31 16:18:54 -0800407void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408{
409 const size_t SIZE = 256;
410 char buffer[SIZE];
411 String8 result;
412 snprintf(buffer, SIZE, "Permission Denial: "
413 "can't dump AudioFlinger from pid=%d, uid=%d\n",
414 IPCThreadState::self()->getCallingPid(),
415 IPCThreadState::self()->getCallingUid());
416 result.append(buffer);
417 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418}
419
Eric Laurent81784c32012-11-19 14:55:58 -0800420bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421{
422 bool locked = false;
423 for (int i = 0; i < kDumpLockRetries; ++i) {
424 if (mutex.tryLock() == NO_ERROR) {
425 locked = true;
426 break;
427 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800428 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429 }
430 return locked;
431}
432
433status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
434{
Glenn Kasten44deb052012-02-05 18:09:08 -0800435 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 dumpPermissionDenial(fd, args);
437 } else {
438 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800439 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 if (!hardwareLocked) {
441 String8 result(kHardwareLockedString);
442 write(fd, result.string(), result.size());
443 } else {
444 mHardwareLock.unlock();
445 }
446
Eric Laurent81784c32012-11-19 14:55:58 -0800447 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448
449 // failed to lock - AudioFlinger is probably deadlocked
450 if (!locked) {
451 String8 result(kDeadlockedString);
452 write(fd, result.string(), result.size());
453 }
454
Eric Laurent021cf962014-05-13 10:18:14 -0700455 bool clientLocked = dumpTryLock(mClientLock);
456 if (!clientLocked) {
457 String8 result(kClientLockedString);
458 write(fd, result.string(), result.size());
459 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700460
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700461 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700462 mEffectsFactoryHal->dumpEffects(fd);
463 } else {
464 String8 result(kNoEffectsFactory);
465 write(fd, result.string(), result.size());
466 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700467
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700469 if (clientLocked) {
470 mClientLock.unlock();
471 }
472
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 dumpInternals(fd, args);
474
475 // dump playback threads
476 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
477 mPlaybackThreads.valueAt(i)->dump(fd, args);
478 }
479
480 // dump record threads
481 for (size_t i = 0; i < mRecordThreads.size(); i++) {
482 mRecordThreads.valueAt(i)->dump(fd, args);
483 }
484
Eric Laurent6acd1d42017-01-04 14:23:29 -0800485 // dump mmap threads
486 for (size_t i = 0; i < mMmapThreads.size(); i++) {
487 mMmapThreads.valueAt(i)->dump(fd, args);
488 }
489
Eric Laurentaaa44472014-09-12 17:41:50 -0700490 // dump orphan effect chains
491 if (mOrphanEffectChains.size() != 0) {
492 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
493 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
494 mOrphanEffectChains.valueAt(i)->dump(fd, args);
495 }
496 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700497 // dump all hardware devs
498 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700499 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
500 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700502
Glenn Kasten46909e72013-02-26 09:20:22 -0800503#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700504 // dump the serially shared record tee sink
505 if (mRecordTeeSource != 0) {
506 dumpTee(fd, mRecordTeeSource);
507 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800508#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700509
rago3bd1c872016-09-26 12:58:14 -0700510 BUFLOG_RESET;
511
Glenn Kastend65d73c2012-06-22 17:21:07 -0700512 if (locked) {
513 mLock.unlock();
514 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800515
516 // append a copy of media.log here by forwarding fd to it, but don't attempt
517 // to lookup the service if it's not running, as it will block for a second
518 if (mLogMemoryDealer != 0) {
519 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
520 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700521 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800522 Vector<String16> args;
523 binder->dump(fd, args);
524 }
525 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700526
527 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700528 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700529 bool unreachableMemory = false;
530 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700531 if (arg == String16("-m")) {
532 dumpMem = true;
533 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700534 unreachableMemory = true;
535 }
536 }
537
Andy Hung07b745e2016-05-23 16:21:07 -0700538 if (dumpMem) {
539 dprintf(fd, "\nDumping memory:\n");
540 std::string s = dumpMemoryAddresses(100 /* limit */);
541 write(fd, s.c_str(), s.size());
542 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700543 if (unreachableMemory) {
544 dprintf(fd, "\nDumping unreachable memory:\n");
545 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700546 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700547 write(fd, s.c_str(), s.size());
548 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549 }
550 return NO_ERROR;
551}
552
Eric Laurent021cf962014-05-13 10:18:14 -0700553sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800554{
Eric Laurent021cf962014-05-13 10:18:14 -0700555 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800556 // If pid is already in the mClients wp<> map, then use that entry
557 // (for which promote() is always != 0), otherwise create a new entry and Client.
558 sp<Client> client = mClients.valueFor(pid).promote();
559 if (client == 0) {
560 client = new Client(this, pid);
561 mClients.add(pid, client);
562 }
563
564 return client;
565}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566
Glenn Kasten9e58b552013-01-18 15:09:48 -0800567sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
568{
Glenn Kasten481fb672013-09-30 14:39:28 -0700569 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800570 if (mLogMemoryDealer == 0) {
571 return new NBLog::Writer();
572 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800573 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700574 // Similarly if we can't contact the media.log service, also return a dummy writer
575 if (binder == 0) {
576 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800577 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700578 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
579 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
580 // If allocation fails, consult the vector of previously unregistered writers
581 // and garbage-collect one or more them until an allocation succeeds
582 if (shared == 0) {
583 Mutex::Autolock _l(mUnregisteredWritersLock);
584 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
585 {
586 // Pick the oldest stale writer to garbage-collect
587 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
588 mUnregisteredWriters.removeAt(0);
589 mediaLogService->unregisterWriter(iMemory);
590 // Now the media.log remote reference to IMemory is gone. When our last local
591 // reference to IMemory also drops to zero at end of this block,
592 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
593 }
594 // Re-attempt the allocation
595 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
596 if (shared != 0) {
597 goto success;
598 }
599 }
600 // Even after garbage-collecting all old writers, there is still not enough memory,
601 // so return a dummy writer
602 return new NBLog::Writer();
603 }
604success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800605 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
606 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
607 // explicit destructor not needed since it is POD
Glenn Kasten481fb672013-09-30 14:39:28 -0700608 mediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800609 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800610}
611
612void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
613{
Glenn Kasten685ef092013-02-04 08:15:34 -0800614 if (writer == 0) {
615 return;
616 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800617 sp<IMemory> iMemory(writer->getIMemory());
618 if (iMemory == 0) {
619 return;
620 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700621 // Rather than removing the writer immediately, append it to a queue of old writers to
622 // be garbage-collected later. This allows us to continue to view old logs for a while.
623 Mutex::Autolock _l(mUnregisteredWritersLock);
624 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800625}
626
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627// IAudioFlinger interface
628
629
630sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800631 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800633 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700634 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800635 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700636 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800638 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700639 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800640 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800641 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800642 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800643 status_t *status,
644 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645{
646 sp<PlaybackThread::Track> track;
647 sp<TrackHandle> trackHandle;
648 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800650 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700652 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
653 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
654 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
655 ALOGW_IF(pid != -1 && pid != callingPid,
656 "%s uid %d pid %d tried to pass itself off as pid %d",
657 __func__, callingUid, callingPid, pid);
658 pid = callingPid;
659 }
660
Glenn Kasten263709e2012-01-06 08:40:01 -0800661 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
662 // but if someone uses binder directly they could bypass that and cause us to crash
663 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000664 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665 lStatus = BAD_VALUE;
666 goto Exit;
667 }
668
Glenn Kasten53b5d092014-02-05 10:00:23 -0800669 // further sample rate checks are performed by createTrack_l() depending on the thread type
670 if (sampleRate == 0) {
671 ALOGE("createTrack() invalid sample rate %u", sampleRate);
672 lStatus = BAD_VALUE;
673 goto Exit;
674 }
675
676 // further channel mask checks are performed by createTrack_l() depending on the thread type
677 if (!audio_is_output_channel(channelMask)) {
678 ALOGE("createTrack() invalid channel mask %#x", channelMask);
679 lStatus = BAD_VALUE;
680 goto Exit;
681 }
682
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700683 // further format checks are performed by createTrack_l() depending on the thread type
684 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800685 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700686 lStatus = BAD_VALUE;
687 goto Exit;
688 }
689
Glenn Kasten663c2242013-09-24 11:52:37 -0700690 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
691 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
692 lStatus = BAD_VALUE;
693 goto Exit;
694 }
695
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 {
697 Mutex::Autolock _l(mLock);
698 PlaybackThread *thread = checkPlaybackThread_l(output);
699 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800700 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 lStatus = BAD_VALUE;
702 goto Exit;
703 }
704
Eric Laurent021cf962014-05-13 10:18:14 -0700705 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706
Glenn Kastene848bd92014-03-13 15:00:32 -0700707 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700708 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800709 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
710 ALOGE("createTrack() invalid session ID %d", *sessionId);
711 lStatus = BAD_VALUE;
712 goto Exit;
713 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700714 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700715 // check if an effect chain with the same session ID is present on another
716 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700717 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700718 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
719 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700720 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700721 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700722 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700723 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700724 }
Eric Laurentde070132010-07-13 04:45:46 -0700725 }
726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700728 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800729 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 if (sessionId != NULL) {
731 *sessionId = lSessionId;
732 }
733 }
Steve Block3856b092011-10-20 11:56:00 +0100734 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735
736 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800737 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
738 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800739 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700740 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700741
742 // move effect chain to this output thread if an effect on same session was waiting
743 // for a track to be created
744 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700745 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700746 Mutex::Autolock _dl(thread->mLock);
747 Mutex::Autolock _sl(effectThread->mLock);
748 moveEffectChain_l(lSessionId, effectThread, thread, true);
749 }
Eric Laurenta011e352012-03-29 15:51:43 -0700750
751 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700752 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700753 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
754 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700755 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700756 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700757 } else {
758 mPendingSyncEvents[i]->cancel();
759 }
Eric Laurenta011e352012-03-29 15:51:43 -0700760 mPendingSyncEvents.removeAt(i);
761 i--;
762 }
763 }
764 }
Glenn Kastene198c362013-08-13 09:13:36 -0700765
Glenn Kastend848eb42016-03-08 13:42:11 -0800766 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767 }
Glenn Kastene198c362013-08-13 09:13:36 -0700768
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700769 if (lStatus != NO_ERROR) {
770 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700771 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700772 // Don't hold mClientLock when releasing the reference on the track as the
773 // destructor will acquire it.
774 {
775 Mutex::Autolock _cl(mClientLock);
776 client.clear();
777 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700779 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 }
781
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700782 // return handle to client
783 trackHandle = new TrackHandle(track);
784
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700786 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 return trackHandle;
788}
789
Glenn Kasten2c073da2016-02-26 09:14:08 -0800790uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791{
792 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800793 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800795 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return 0;
797 }
798 return thread->sampleRate();
799}
800
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800801audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802{
803 Mutex::Autolock _l(mLock);
804 PlaybackThread *thread = checkPlaybackThread_l(output);
805 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000806 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800807 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 }
809 return thread->format();
810}
811
Glenn Kasten2c073da2016-02-26 09:14:08 -0800812size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813{
814 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800815 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800817 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return 0;
819 }
Glenn Kasten58912562012-04-03 10:45:00 -0700820 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
821 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822 return thread->frameCount();
823}
824
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700825size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
826{
827 Mutex::Autolock _l(mLock);
828 ThreadBase *thread = checkThread_l(ioHandle);
829 if (thread == NULL) {
830 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
831 return 0;
832 }
833 return thread->frameCountHAL();
834}
835
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800836uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837{
838 Mutex::Autolock _l(mLock);
839 PlaybackThread *thread = checkPlaybackThread_l(output);
840 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800841 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return 0;
843 }
844 return thread->latency();
845}
846
847status_t AudioFlinger::setMasterVolume(float value)
848{
Eric Laurenta1884f92011-08-23 08:25:03 -0700849 status_t ret = initCheck();
850 if (ret != NO_ERROR) {
851 return ret;
852 }
853
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 // check calling permissions
855 if (!settingsAllowed()) {
856 return PERMISSION_DENIED;
857 }
858
Eric Laurenta4c5a552012-03-29 10:12:40 -0700859 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700860 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700861
John Grossmanee578c02012-07-23 17:05:46 -0700862 // Set master volume in the HALs which support it.
863 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
864 AutoMutex lock(mHardwareLock);
865 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800866
John Grossmanee578c02012-07-23 17:05:46 -0700867 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
868 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700869 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800870 }
John Grossmanee578c02012-07-23 17:05:46 -0700871 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873
John Grossmanee578c02012-07-23 17:05:46 -0700874 // Now set the master volume in each playback thread. Playback threads
875 // assigned to HALs which do not have master volume support will apply
876 // master volume during the mix operation. Threads with HALs which do
877 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700878 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
879 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
880 continue;
881 }
John Grossmanee578c02012-07-23 17:05:46 -0700882 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884
885 return NO_ERROR;
886}
887
Glenn Kastenf78aee72012-01-04 11:00:47 -0800888status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889{
Eric Laurenta1884f92011-08-23 08:25:03 -0700890 status_t ret = initCheck();
891 if (ret != NO_ERROR) {
892 return ret;
893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894
895 // check calling permissions
896 if (!settingsAllowed()) {
897 return PERMISSION_DENIED;
898 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800899 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000900 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 return BAD_VALUE;
902 }
903
904 { // scope for the lock
905 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700906 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700908 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909 mHardwareStatus = AUDIO_HW_IDLE;
910 }
911
912 if (NO_ERROR == ret) {
913 Mutex::Autolock _l(mLock);
914 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800915 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700916 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 }
918
919 return ret;
920}
921
922status_t AudioFlinger::setMicMute(bool state)
923{
Eric Laurenta1884f92011-08-23 08:25:03 -0700924 status_t ret = initCheck();
925 if (ret != NO_ERROR) {
926 return ret;
927 }
928
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 // check calling permissions
930 if (!settingsAllowed()) {
931 return PERMISSION_DENIED;
932 }
933
934 AutoMutex lock(mHardwareLock);
935 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700936 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700937 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
938 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700939 if (result != NO_ERROR) {
940 ret = result;
941 }
942 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943 mHardwareStatus = AUDIO_HW_IDLE;
944 return ret;
945}
946
947bool AudioFlinger::getMicMute() const
948{
Eric Laurenta1884f92011-08-23 08:25:03 -0700949 status_t ret = initCheck();
950 if (ret != NO_ERROR) {
951 return false;
952 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800953 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700954 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800955 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800957 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700958 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
959 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800960 if (result == NO_ERROR) {
961 mute = mute && state;
962 }
963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800965
966 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967}
968
969status_t AudioFlinger::setMasterMute(bool muted)
970{
John Grossmand8f178d2012-07-20 14:51:35 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
John Grossmanee578c02012-07-23 17:05:46 -0700981 Mutex::Autolock _l(mLock);
982 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700983
John Grossmanee578c02012-07-23 17:05:46 -0700984 // Set master mute in the HALs which support it.
985 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
986 AutoMutex lock(mHardwareLock);
987 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700988
John Grossmanee578c02012-07-23 17:05:46 -0700989 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
990 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700991 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700992 }
John Grossmanee578c02012-07-23 17:05:46 -0700993 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700994 }
995
John Grossmanee578c02012-07-23 17:05:46 -0700996 // Now set the master mute in each playback thread. Playback threads
997 // assigned to HALs which do not have master mute support will apply master
998 // mute during the mix operation. Threads with HALs which do support master
999 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001000 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1001 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1002 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004
1005 return NO_ERROR;
1006}
1007
1008float AudioFlinger::masterVolume() const
1009{
Glenn Kasten98067102011-12-13 11:47:54 -08001010 Mutex::Autolock _l(mLock);
1011 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012}
1013
1014bool AudioFlinger::masterMute() const
1015{
Glenn Kasten98067102011-12-13 11:47:54 -08001016 Mutex::Autolock _l(mLock);
1017 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018}
1019
John Grossman4ff14ba2012-02-08 16:37:41 -08001020float AudioFlinger::masterVolume_l() const
1021{
John Grossman4ff14ba2012-02-08 16:37:41 -08001022 return mMasterVolume;
1023}
1024
John Grossmand8f178d2012-07-20 14:51:35 -07001025bool AudioFlinger::masterMute_l() const
1026{
John Grossmanee578c02012-07-23 17:05:46 -07001027 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001028}
1029
Eric Laurent223fd5c2014-11-11 13:43:36 -08001030status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1031{
1032 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001033 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001034 return BAD_VALUE;
1035 }
1036 pid_t caller = IPCThreadState::self()->getCallingPid();
1037 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001038 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001039 return PERMISSION_DENIED;
1040 }
1041
1042 return NO_ERROR;
1043}
1044
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001045status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1046 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047{
1048 // check calling permissions
1049 if (!settingsAllowed()) {
1050 return PERMISSION_DENIED;
1051 }
1052
Eric Laurent223fd5c2014-11-11 13:43:36 -08001053 status_t status = checkStreamType(stream);
1054 if (status != NO_ERROR) {
1055 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001057 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058
1059 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001060 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001061 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001062 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1063 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 return BAD_VALUE;
1065 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001066 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
1069 mStreamTypes[stream].volume = value;
1070
Eric Laurent6acd1d42017-01-04 14:23:29 -08001071 if (volumeInterfaces.size() == 0) {
1072 volumeInterfaces = getAllVolumeInterfaces_l();
1073 }
1074 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1075 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 }
1077
1078 return NO_ERROR;
1079}
1080
Glenn Kastenfff6d712012-01-12 16:38:12 -08001081status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 // check calling permissions
1084 if (!settingsAllowed()) {
1085 return PERMISSION_DENIED;
1086 }
1087
Eric Laurent223fd5c2014-11-11 13:43:36 -08001088 status_t status = checkStreamType(stream);
1089 if (status != NO_ERROR) {
1090 return status;
1091 }
1092 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1093
1094 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001095 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 return BAD_VALUE;
1097 }
1098
Eric Laurent93575202011-01-18 18:39:02 -08001099 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001101 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1102 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1103 volumeInterfaces[i]->setStreamMute(stream, muted);
1104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105
1106 return NO_ERROR;
1107}
1108
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001109float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001111 status_t status = checkStreamType(stream);
1112 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 return 0.0f;
1114 }
1115
1116 AutoMutex lock(mLock);
1117 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001118 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001119 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1120 if (volumeInterface != NULL) {
1121 volume = volumeInterface->streamVolume(stream);
1122 } else {
1123 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001126 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
1128
1129 return volume;
1130}
1131
Glenn Kastenfff6d712012-01-12 16:38:12 -08001132bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001134 status_t status = checkStreamType(stream);
1135 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 return true;
1137 }
1138
Glenn Kasten6637baa2012-01-09 09:40:36 -08001139 AutoMutex lock(mLock);
1140 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141}
1142
Eric Laurent054d9d32015-04-24 08:48:48 -07001143
1144void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1145{
1146 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1147 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1148 }
1149}
1150
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001151status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001153 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1154 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001155
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 // check calling permissions
1157 if (!settingsAllowed()) {
1158 return PERMISSION_DENIED;
1159 }
1160
Glenn Kasten142f5192014-03-25 17:44:59 -07001161 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1162 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001163 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001164 // result will remain NO_INIT if no audio device is present
1165 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001166 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001167 AutoMutex lock(mHardwareLock);
1168 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1169 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001170 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1171 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001172 // return success if at least one audio device accepts the parameters as not all
1173 // HALs are requested to support all parameters. If no audio device supports the
1174 // requested parameters, the last error is reported.
1175 if (final_result != NO_ERROR) {
1176 final_result = result;
1177 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001178 }
1179 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001180 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001181 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1182 AudioParameter param = AudioParameter(keyValuePairs);
1183 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001184 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1185 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001186 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001187 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1188 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001189 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001190 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1191 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001192 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001193 // suspend effects associated with those session IDs
1194 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001195 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001196 thread->setEffectSuspended(FX_IID_AEC,
1197 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001198 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001199 thread->setEffectSuspended(FX_IID_NS,
1200 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001201 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001202 }
1203 }
Eric Laurentbee53372011-08-29 12:42:48 -07001204 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001205 }
1206 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001207 String8 screenState;
1208 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001209 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001210 if (isOff != (AudioFlinger::mScreenState & 1)) {
1211 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001212 }
1213 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001214 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 }
1216
1217 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1218 // and the thread is exited once the lock is released
1219 sp<ThreadBase> thread;
1220 {
1221 Mutex::Autolock _l(mLock);
1222 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001223 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001225 if (thread == 0) {
1226 thread = checkMmapThread_l(ioHandle);
1227 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001228 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001229 // indicate output device change to all input threads for pre processing
1230 AudioParameter param = AudioParameter(keyValuePairs);
1231 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001232 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1233 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001234 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 }
1237 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001238 if (thread != 0) {
1239 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 }
1241 return BAD_VALUE;
1242}
1243
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001244String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001246 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1247 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248
Eric Laurenta4c5a552012-03-29 10:12:40 -07001249 Mutex::Autolock _l(mLock);
1250
Glenn Kasten142f5192014-03-25 17:44:59 -07001251 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001252 String8 out_s8;
1253
Dima Zavin799a70e2011-04-18 16:57:27 -07001254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001255 String8 s;
1256 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001257 {
1258 AutoMutex lock(mHardwareLock);
1259 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001260 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1261 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001262 mHardwareStatus = AUDIO_HW_IDLE;
1263 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001264 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001265 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001266 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 }
1268
Eric Laurent6acd1d42017-01-04 14:23:29 -08001269 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1270 if (thread == NULL) {
1271 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1272 if (thread == NULL) {
1273 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1274 if (thread == NULL) {
1275 String8("");
1276 }
1277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001279 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280}
1281
Glenn Kastendd8104c2012-07-02 12:42:44 -07001282size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1283 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284{
Eric Laurenta1884f92011-08-23 08:25:03 -07001285 status_t ret = initCheck();
1286 if (ret != NO_ERROR) {
1287 return 0;
1288 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001289 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001290 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001291 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001292 return 0;
1293 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001294
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001295 AutoMutex lock(mHardwareLock);
1296 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001297 audio_config_t config, proposed;
1298 memset(&proposed, 0, sizeof(proposed));
1299 proposed.sample_rate = sampleRate;
1300 proposed.channel_mask = channelMask;
1301 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001302
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001303 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001304 size_t frames;
1305 for (;;) {
1306 // Note: config is currently a const parameter for get_input_buffer_size()
1307 // but we use a copy from proposed in case config changes from the call.
1308 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001309 status_t result = dev->getInputBufferSize(&config, &frames);
1310 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001311 break; // hal success, config is the result
1312 }
1313 // change one parameter of the configuration each iteration to a more "common" value
1314 // to see if the device will support it.
1315 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1316 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1317 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1318 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1319 } else {
1320 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1321 "format %#x, channelMask 0x%X",
1322 sampleRate, format, channelMask);
1323 break; // retries failed, break out of loop with frames == 0.
1324 }
1325 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001326 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001327 if (frames > 0 && config.sample_rate != sampleRate) {
1328 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1329 }
1330 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331}
1332
Glenn Kasten5f972c02014-01-13 09:59:31 -08001333uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001335 Mutex::Autolock _l(mLock);
1336
1337 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1338 if (recordThread != NULL) {
1339 return recordThread->getInputFramesLost();
1340 }
1341 return 0;
1342}
1343
1344status_t AudioFlinger::setVoiceVolume(float value)
1345{
Eric Laurenta1884f92011-08-23 08:25:03 -07001346 status_t ret = initCheck();
1347 if (ret != NO_ERROR) {
1348 return ret;
1349 }
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351 // check calling permissions
1352 if (!settingsAllowed()) {
1353 return PERMISSION_DENIED;
1354 }
1355
1356 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001357 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001358 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001359 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360 mHardwareStatus = AUDIO_HW_IDLE;
1361
1362 return ret;
1363}
1364
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001365status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001366 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001367{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368 Mutex::Autolock _l(mLock);
1369
1370 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1371 if (playbackThread != NULL) {
1372 return playbackThread->getRenderPosition(halFrames, dspFrames);
1373 }
1374
1375 return BAD_VALUE;
1376}
1377
1378void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1379{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001381 if (client == 0) {
1382 return;
1383 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001384 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001385 {
1386 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001387 if (mNotificationClients.indexOfKey(pid) < 0) {
1388 sp<NotificationClient> notificationClient = new NotificationClient(this,
1389 client,
1390 pid);
1391 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392
Eric Laurent021cf962014-05-13 10:18:14 -07001393 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394
Marco Nelissen06b46062014-11-14 07:58:25 -08001395 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001396 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001397 }
1398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399
Eric Laurent021cf962014-05-13 10:18:14 -07001400 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001401 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001402 // the config change is always sent from playback or record threads to avoid deadlock
1403 // with AudioSystem::gLock
1404 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1405 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001408 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1409 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 }
1411}
1412
1413void AudioFlinger::removeNotificationClient(pid_t pid)
1414{
1415 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001416 {
1417 Mutex::Autolock _cl(mClientLock);
1418 mNotificationClients.removeItem(pid);
1419 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001420
Steve Block3856b092011-10-20 11:56:00 +01001421 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001422 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001423 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001424 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001425 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001426 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001427 if (ref->mPid == pid) {
1428 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001429 mAudioSessionRefs.removeAt(i);
1430 delete ref;
1431 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001432 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001433 } else {
1434 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001435 }
1436 }
1437 if (removed) {
1438 purgeStaleEffects_l();
1439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440}
1441
Eric Laurent73e26b62015-04-27 16:55:58 -07001442void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001443 const sp<AudioIoDescriptor>& ioDesc,
1444 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445{
Eric Laurent021cf962014-05-13 10:18:14 -07001446 Mutex::Autolock _l(mClientLock);
1447 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001449 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1450 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 }
1453}
1454
Eric Laurent021cf962014-05-13 10:18:14 -07001455// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456void AudioFlinger::removeClient_l(pid_t pid)
1457{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001458 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001459 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 mClients.removeItem(pid);
1461}
1462
Eric Laurent717e1282012-06-29 16:36:52 -07001463// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001464sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1465 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001466{
1467 sp<PlaybackThread> thread;
1468
1469 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1470 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1471 ALOG_ASSERT(thread == 0);
1472 thread = mPlaybackThreads.valueAt(i);
1473 }
1474 }
1475
1476 return thread;
1477}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480
1481// ----------------------------------------------------------------------------
1482
1483AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1484 : RefBase(),
1485 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001486 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301488 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1489 heapSize *= 1024;
1490 if (!heapSize) {
1491 heapSize = kClientSharedHeapSizeBytes;
1492 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1493 // invalidated tracks
1494 if (!audioFlinger->isLowRamDevice()) {
1495 heapSize *= kClientSharedHeapSizeMultiplier;
1496 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001497 }
1498 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499}
1500
Eric Laurent021cf962014-05-13 10:18:14 -07001501// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502AudioFlinger::Client::~Client()
1503{
1504 mAudioFlinger->removeClient_l(mPid);
1505}
1506
Glenn Kasten435dbe62012-01-30 10:15:48 -08001507sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508{
1509 return mMemoryDealer;
1510}
1511
1512// ----------------------------------------------------------------------------
1513
1514AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1515 const sp<IAudioFlingerClient>& client,
1516 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001517 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518{
1519}
1520
1521AudioFlinger::NotificationClient::~NotificationClient()
1522{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523}
1524
Glenn Kasten0f11b512014-01-31 16:18:54 -08001525void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526{
1527 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001528 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529}
1530
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531
1532// ----------------------------------------------------------------------------
1533
1534sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001535 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001537 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001538 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001539 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001540 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001541 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001542 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001543 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001544 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001545 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001546 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001547 sp<IMemory>& cblk,
1548 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001549 status_t *status,
1550 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551{
1552 sp<RecordThread::RecordTrack> recordTrack;
1553 sp<RecordHandle> recordHandle;
1554 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001556 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557
Glenn Kastend776ac62014-05-07 09:16:09 -07001558 cblk.clear();
1559 buffers.clear();
1560
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001561 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001562 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1563 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001564 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001565 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1566 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001567 updatePid = true;
1568 }
1569
1570 if (updatePid) {
1571 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1572 ALOGW_IF(pid != -1 && pid != callingPid,
1573 "%s uid %d pid %d tried to pass itself off as pid %d",
1574 __func__, callingUid, callingPid, pid);
1575 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001576 }
1577
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001579 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001580 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 lStatus = PERMISSION_DENIED;
1582 goto Exit;
1583 }
1584
Glenn Kasten53b5d092014-02-05 10:00:23 -08001585 // further sample rate checks are performed by createRecordTrack_l()
1586 if (sampleRate == 0) {
1587 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1588 lStatus = BAD_VALUE;
1589 goto Exit;
1590 }
1591
Andy Hung6770c6f2015-04-07 13:43:36 -07001592 // we don't yet support anything other than linear PCM
1593 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001594 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001595 lStatus = BAD_VALUE;
1596 goto Exit;
1597 }
1598
Glenn Kasten53b5d092014-02-05 10:00:23 -08001599 // further channel mask checks are performed by createRecordTrack_l()
1600 if (!audio_is_input_channel(channelMask)) {
1601 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1602 lStatus = BAD_VALUE;
1603 goto Exit;
1604 }
1605
Glenn Kasten05997e22014-03-13 15:08:33 -07001606 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001608 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001610 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611 lStatus = BAD_VALUE;
1612 goto Exit;
1613 }
1614
Eric Laurent021cf962014-05-13 10:18:14 -07001615 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001617 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001618 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1619 lStatus = BAD_VALUE;
1620 goto Exit;
1621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 lSessionId = *sessionId;
1623 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001624 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001625 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 if (sessionId != NULL) {
1627 *sessionId = lSessionId;
1628 }
1629 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001630 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001631
Glenn Kasten1879fff2012-07-11 15:36:59 -07001632 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001633 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001634 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001635 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001636
1637 if (lStatus == NO_ERROR) {
1638 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1639 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001640 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001641 if (chain != 0) {
1642 Mutex::Autolock _l(thread->mLock);
1643 thread->addEffectChain_l(chain);
1644 }
1645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 }
Glenn Kastene198c362013-08-13 09:13:36 -07001647
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001648 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001649 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001650 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001651 // Don't hold mClientLock when releasing the reference on the track as the
1652 // destructor will acquire it.
1653 {
1654 Mutex::Autolock _cl(mClientLock);
1655 client.clear();
1656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 goto Exit;
1659 }
1660
Glenn Kastend776ac62014-05-07 09:16:09 -07001661 cblk = recordTrack->getCblk();
1662 buffers = recordTrack->getBuffers();
1663
Glenn Kasten2fc14732013-08-05 14:58:14 -07001664 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666
1667Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001668 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 return recordHandle;
1670}
1671
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001672
1673
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674// ----------------------------------------------------------------------------
1675
Eric Laurenta4c5a552012-03-29 10:12:40 -07001676audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1677{
Eric Laurent44622db2014-08-01 19:00:33 -07001678 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001679 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001680 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001681 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001682 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001683 }
1684 Mutex::Autolock _l(mLock);
1685 return loadHwModule_l(name);
1686}
1687
1688// loadHwModule_l() must be called with AudioFlinger::mLock held
1689audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1690{
1691 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1692 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1693 ALOGW("loadHwModule() module %s already loaded", name);
1694 return mAudioHwDevs.keyAt(i);
1695 }
1696 }
1697
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001698 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001699
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001700 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001701 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001702 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001703 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001704 }
1705
1706 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001707 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001708 mHardwareStatus = AUDIO_HW_IDLE;
1709 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001710 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001711 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001712 }
1713
John Grossmanee578c02012-07-23 17:05:46 -07001714 // Check and cache this HAL's level of support for master mute and master
1715 // volume. If this is the first HAL opened, and it supports the get
1716 // methods, use the initial values provided by the HAL as the current
1717 // master mute and volume settings.
1718
1719 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1720 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001721 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001722
1723 if (0 == mAudioHwDevs.size()) {
1724 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001725 float mv;
1726 if (OK == dev->getMasterVolume(&mv)) {
1727 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001728 }
1729
1730 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001731 bool mm;
1732 if (OK == dev->getMasterMute(&mm)) {
1733 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001734 }
1735 }
1736
Eric Laurenta4c5a552012-03-29 10:12:40 -07001737 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001738 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001739 flags = static_cast<AudioHwDevice::Flags>(flags |
1740 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1741 }
1742
1743 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001744 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001745 flags = static_cast<AudioHwDevice::Flags>(flags |
1746 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1747 }
1748
Eric Laurenta4c5a552012-03-29 10:12:40 -07001749 mHardwareStatus = AUDIO_HW_IDLE;
1750 }
1751
Glenn Kastena13cde92016-03-28 15:26:02 -07001752 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001753 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001754
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001755 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001756
1757 return handle;
1758
1759}
1760
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001761// ----------------------------------------------------------------------------
1762
Glenn Kasten3b16c762012-11-14 08:44:39 -08001763uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001764{
1765 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001766 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001767 return thread != NULL ? thread->sampleRate() : 0;
1768}
1769
Glenn Kastene33054e2012-11-14 12:54:39 -08001770size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001771{
1772 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001773 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001774 return thread != NULL ? thread->frameCountHAL() : 0;
1775}
1776
1777// ----------------------------------------------------------------------------
1778
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001779status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1780{
1781 uid_t uid = IPCThreadState::self()->getCallingUid();
1782 if (uid != AID_SYSTEM) {
1783 return PERMISSION_DENIED;
1784 }
1785 Mutex::Autolock _l(mLock);
1786 if (mIsDeviceTypeKnown) {
1787 return INVALID_OPERATION;
1788 }
1789 mIsLowRamDevice = isLowRamDevice;
1790 mIsDeviceTypeKnown = true;
1791 return NO_ERROR;
1792}
1793
Eric Laurent93c3d412014-08-01 14:48:35 -07001794audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1795{
1796 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001797
1798 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1799 if (index >= 0) {
1800 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1801 mHwAvSyncIds.valueAt(index), sessionId);
1802 return mHwAvSyncIds.valueAt(index);
1803 }
1804
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001805 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001806 if (dev == NULL) {
1807 return AUDIO_HW_SYNC_INVALID;
1808 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001809 String8 reply;
1810 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001811 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001812 param = AudioParameter(reply);
1813 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001814
1815 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001816 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001817 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1818 return AUDIO_HW_SYNC_INVALID;
1819 }
1820
1821 // allow only one session for a given HW A/V sync ID.
1822 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1823 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1824 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1825 value, mHwAvSyncIds.keyAt(i));
1826 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001827 break;
1828 }
1829 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001830
1831 mHwAvSyncIds.add(sessionId, value);
1832
1833 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1834 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1835 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001836 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001837 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001838 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001839 thread->setParameters(param.toString());
1840 break;
1841 }
1842 }
1843
1844 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1845 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001846}
1847
Eric Laurent72e3f392015-05-20 14:43:50 -07001848status_t AudioFlinger::systemReady()
1849{
1850 Mutex::Autolock _l(mLock);
1851 ALOGI("%s", __FUNCTION__);
1852 if (mSystemReady) {
1853 ALOGW("%s called twice", __FUNCTION__);
1854 return NO_ERROR;
1855 }
1856 mSystemReady = true;
1857 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1858 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1859 thread->systemReady();
1860 }
1861 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1862 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1863 thread->systemReady();
1864 }
1865 return NO_ERROR;
1866}
1867
Eric Laurentfa90e842014-10-17 18:12:31 -07001868// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1869void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1870{
1871 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1872 if (index >= 0) {
1873 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1874 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1875 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001876 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001877 thread->setParameters(param.toString());
1878 }
1879}
1880
1881
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001882// ----------------------------------------------------------------------------
1883
Eric Laurent83b88082014-06-20 18:31:16 -07001884
Eric Laurent6acd1d42017-01-04 14:23:29 -08001885sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001886 audio_io_handle_t *output,
1887 audio_config_t *config,
1888 audio_devices_t devices,
1889 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001890 audio_output_flags_t flags)
1891{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001893 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001894 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001895 }
1896
Eric Laurentcf2c0212014-07-25 16:20:43 -07001897 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001898 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1899 } else {
1900 // Audio Policy does not currently request a specific output handle.
1901 // If this is ever needed, see openInput_l() for example code.
1902 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1903 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001904 }
Eric Laurent83b88082014-06-20 18:31:16 -07001905
1906 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1907
Eric Laurent83b88082014-06-20 18:31:16 -07001908 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001909 // This if statement allows overriding the audio policy settings
1910 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1911 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1912 // Check only for Normal Mixing mode
1913 if (kEnableExtendedPrecision) {
1914 // Specify format (uncomment one below to choose)
1915 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1916 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1917 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1918 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001919 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001920 }
1921 if (kEnableExtendedChannels) {
1922 // Specify channel mask (uncomment one below to choose)
1923 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1924 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1925 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1926 }
Eric Laurent83b88082014-06-20 18:31:16 -07001927 }
1928
Phil Burk062e67a2015-02-11 13:40:50 -08001929 AudioStreamOut *outputStream = NULL;
1930 status_t status = outHwDev->openOutputStream(
1931 &outputStream,
1932 *output,
1933 devices,
1934 flags,
1935 config,
1936 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001937
1938 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001939
Phil Burk062e67a2015-02-11 13:40:50 -08001940 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001941 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
1942 sp<MmapPlaybackThread> thread =
1943 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
1944 devices, AUDIO_DEVICE_NONE, mSystemReady);
1945 mMmapThreads.add(*output, thread);
1946 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
1947 *output, thread.get());
1948 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07001949 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001950 sp<PlaybackThread> thread;
1951 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1952 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
1953 ALOGV("openOutput_l() created offload output: ID %d thread %p",
1954 *output, thread.get());
1955 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1956 || !isValidPcmSinkFormat(config->format)
1957 || !isValidPcmSinkChannelMask(config->channel_mask)) {
1958 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
1959 ALOGV("openOutput_l() created direct output: ID %d thread %p",
1960 *output, thread.get());
1961 } else {
1962 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
1963 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
1964 *output, thread.get());
1965 }
1966 mPlaybackThreads.add(*output, thread);
1967 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07001968 }
Eric Laurent83b88082014-06-20 18:31:16 -07001969 }
1970
1971 return 0;
1972}
1973
Eric Laurentcf2c0212014-07-25 16:20:43 -07001974status_t AudioFlinger::openOutput(audio_module_handle_t module,
1975 audio_io_handle_t *output,
1976 audio_config_t *config,
1977 audio_devices_t *devices,
1978 const String8& address,
1979 uint32_t *latencyMs,
1980 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001982 ALOGI("openOutput() this %p, module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
1983 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001984 (devices != NULL) ? *devices : 0,
1985 config->sample_rate,
1986 config->format,
1987 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001988 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989
Yunlian Jiang32ba9862017-01-31 15:55:00 -08001990 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001991 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001993
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 Mutex::Autolock _l(mLock);
1995
Eric Laurent6acd1d42017-01-04 14:23:29 -08001996 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001997 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001998 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
1999 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2000 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001
Eric Laurent6acd1d42017-01-04 14:23:29 -08002002 // notify client processes of the new output creation
2003 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002004
Eric Laurent6acd1d42017-01-04 14:23:29 -08002005 // the first primary output opened designates the primary hw device
2006 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2007 ALOGI("Using module %d has the primary audio interface", module);
2008 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002009
Eric Laurent6acd1d42017-01-04 14:23:29 -08002010 AutoMutex lock(mHardwareLock);
2011 mHardwareStatus = AUDIO_HW_SET_MODE;
2012 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2013 mHardwareStatus = AUDIO_HW_IDLE;
2014 }
2015 } else {
2016 MmapThread *mmapThread = (MmapThread *)thread.get();
2017 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002018 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002019 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
2021
Eric Laurentcf2c0212014-07-25 16:20:43 -07002022 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023}
2024
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002025audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2026 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027{
2028 Mutex::Autolock _l(mLock);
2029 MixerThread *thread1 = checkMixerThread_l(output1);
2030 MixerThread *thread2 = checkMixerThread_l(output2);
2031
2032 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002033 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2034 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002035 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 }
2037
Glenn Kasteneeecb982016-02-26 10:44:04 -08002038 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002039 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 thread->addOutputTrack(thread2);
2041 mPlaybackThreads.add(id, thread);
2042 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002043 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 return id;
2045}
2046
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002047status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048{
Glenn Kastend96c5722012-04-25 13:44:49 -07002049 return closeOutput_nonvirtual(output);
2050}
2051
2052status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2053{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 // keep strong reference on the playback thread so that
2055 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002056 sp<PlaybackThread> playbackThread;
2057 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 {
2059 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002060 playbackThread = checkPlaybackThread_l(output);
2061 if (playbackThread != NULL) {
2062 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063
Eric Laurent6acd1d42017-01-04 14:23:29 -08002064 if (playbackThread->type() == ThreadBase::MIXER) {
2065 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2066 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2067 DuplicatingThread *dupThread =
2068 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2069 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2070 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002071 }
2072 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073
2074
Eric Laurent6acd1d42017-01-04 14:23:29 -08002075 mPlaybackThreads.removeItem(output);
2076 // save all effects to the default thread
2077 if (mPlaybackThreads.size()) {
2078 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2079 if (dstThread != NULL) {
2080 // audioflinger lock is held here so the acquisition order of thread locks does not
2081 // matter
2082 Mutex::Autolock _dl(dstThread->mLock);
2083 Mutex::Autolock _sl(playbackThread->mLock);
2084 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2085 for (size_t i = 0; i < effectChains.size(); i ++) {
2086 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(), dstThread, true);
2087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 }
2089 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002090 } else {
2091 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2092 if (mmapThread == 0) {
2093 return BAD_VALUE;
2094 }
2095 mMmapThreads.removeItem(output);
2096 ALOGV("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002098 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2099 ioDesc->mIoHandle = output;
2100 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002102 // The thread entity (active unit of execution) is no longer running here,
2103 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104
Eric Laurent6acd1d42017-01-04 14:23:29 -08002105 if (playbackThread != 0) {
2106 playbackThread->exit();
2107 if (!playbackThread->isDuplicating()) {
2108 closeOutputFinish(playbackThread);
2109 }
2110 } else if (mmapThread != 0) {
2111 ALOGV("mmapThread exit()");
2112 mmapThread->exit();
2113 AudioStreamOut *out = mmapThread->clearOutput();
2114 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2115 // from now on thread->mOutput is NULL
2116 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 }
2118 return NO_ERROR;
2119}
2120
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002121void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002122{
2123 AudioStreamOut *out = thread->clearOutput();
2124 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2125 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002126 delete out;
2127}
2128
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002129void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002130{
2131 mPlaybackThreads.removeItem(thread->mId);
2132 thread->exit();
2133 closeOutputFinish(thread);
2134}
2135
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002136status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137{
2138 Mutex::Autolock _l(mLock);
2139 PlaybackThread *thread = checkPlaybackThread_l(output);
2140
2141 if (thread == NULL) {
2142 return BAD_VALUE;
2143 }
2144
Steve Block3856b092011-10-20 11:56:00 +01002145 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 thread->suspend();
2147
2148 return NO_ERROR;
2149}
2150
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002151status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152{
2153 Mutex::Autolock _l(mLock);
2154 PlaybackThread *thread = checkPlaybackThread_l(output);
2155
2156 if (thread == NULL) {
2157 return BAD_VALUE;
2158 }
2159
Steve Block3856b092011-10-20 11:56:00 +01002160 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161
2162 thread->restore();
2163
2164 return NO_ERROR;
2165}
2166
Eric Laurentcf2c0212014-07-25 16:20:43 -07002167status_t AudioFlinger::openInput(audio_module_handle_t module,
2168 audio_io_handle_t *input,
2169 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002170 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002171 const String8& address,
2172 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002173 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174{
Eric Laurent83b88082014-06-20 18:31:16 -07002175 Mutex::Autolock _l(mLock);
2176
Glenn Kastene7d66712015-03-05 13:46:52 -08002177 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002178 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002179 }
2180
Eric Laurent6acd1d42017-01-04 14:23:29 -08002181 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002182
2183 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002184 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002185 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002186 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002188 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002189}
Dima Zavin799a70e2011-04-18 16:57:27 -07002190
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002192 audio_io_handle_t *input,
2193 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002194 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002195 const String8& address,
2196 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002197 audio_input_flags_t flags)
2198{
Glenn Kastene7d66712015-03-05 13:46:52 -08002199 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002200 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002201 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002202 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002203 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002204
Glenn Kasteneeecb982016-02-26 10:44:04 -08002205 // Audio Policy can request a specific handle for hardware hotword.
2206 // The goal here is not to re-open an already opened input.
2207 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002208 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002209 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2210 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2211 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2212 return 0;
2213 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2214 // This should not happen in a transient state with current design.
2215 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2216 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002217 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002218
Eric Laurentcf2c0212014-07-25 16:20:43 -07002219 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002220 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002221 sp<StreamInHalInterface> inStream;
2222 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002223 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002224 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002225 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002226 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002227 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002228 halconfig.sample_rate,
2229 halconfig.format,
2230 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002231 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002232 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002234 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002235 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002236 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002237 audio_is_linear_pcm(config->format) &&
2238 audio_is_linear_pcm(halconfig.format) &&
2239 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002240 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2241 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002242 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002243 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002244 inStream.clear();
2245 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002246 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002247 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 }
2249
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002250 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002251 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002252 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2253 sp<MmapCaptureThread> thread =
2254 new MmapCaptureThread(this, *input,
2255 inHwDev, inputStream,
2256 primaryOutputDevice_l(), devices, mSystemReady);
2257 mMmapThreads.add(*input, thread);
2258 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input, thread.get());
2259 return thread;
2260 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002261#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002262 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2263 // or (re-)create if current Pipe is idle and does not match the new format
2264 sp<NBAIO_Sink> teeSink;
2265 enum {
2266 TEE_SINK_NO, // don't copy input
2267 TEE_SINK_NEW, // copy input using a new pipe
2268 TEE_SINK_OLD, // copy input using an existing pipe
2269 } kind;
2270 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2271 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2272 if (!mTeeSinkInputEnabled) {
2273 kind = TEE_SINK_NO;
2274 } else if (!Format_isValid(format)) {
2275 kind = TEE_SINK_NO;
2276 } else if (mRecordTeeSink == 0) {
2277 kind = TEE_SINK_NEW;
2278 } else if (mRecordTeeSink->getStrongCount() != 1) {
2279 kind = TEE_SINK_NO;
2280 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2281 kind = TEE_SINK_OLD;
2282 } else {
2283 kind = TEE_SINK_NEW;
2284 }
2285 switch (kind) {
2286 case TEE_SINK_NEW: {
2287 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2288 size_t numCounterOffers = 0;
2289 const NBAIO_Format offers[1] = {format};
2290 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2291 ALOG_ASSERT(index == 0);
2292 PipeReader *pipeReader = new PipeReader(*pipe);
2293 numCounterOffers = 0;
2294 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2295 ALOG_ASSERT(index == 0);
2296 mRecordTeeSink = pipe;
2297 mRecordTeeSource = pipeReader;
2298 teeSink = pipe;
2299 }
2300 break;
2301 case TEE_SINK_OLD:
2302 teeSink = mRecordTeeSink;
2303 break;
2304 case TEE_SINK_NO:
2305 default:
2306 break;
2307 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002308#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002309
2310 // Start record thread
2311 // RecordThread requires both input and output device indication to forward to audio
2312 // pre processing modules
2313 sp<RecordThread> thread = new RecordThread(this,
2314 inputStream,
2315 *input,
2316 primaryOutputDevice_l(),
2317 devices,
2318 mSystemReady
2319#ifdef TEE_SINK
2320 , teeSink
2321#endif
2322 );
2323 mRecordThreads.add(*input, thread);
2324 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2325 return thread;
2326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 }
2328
Eric Laurentcf2c0212014-07-25 16:20:43 -07002329 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 return 0;
2331}
2332
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002333status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334{
Glenn Kastend96c5722012-04-25 13:44:49 -07002335 return closeInput_nonvirtual(input);
2336}
2337
2338status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2339{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 // keep strong reference on the record thread so that
2341 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002342 sp<RecordThread> recordThread;
2343 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 {
2345 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002346 recordThread = checkRecordThread_l(input);
2347 if (recordThread != 0) {
2348 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
Eric Laurent6acd1d42017-01-04 14:23:29 -08002350 // If we still have effect chains, it means that a client still holds a handle
2351 // on at least one effect. We must either move the chain to an existing thread with the
2352 // same session ID or put it aside in case a new record thread is opened for a
2353 // new capture on the same session
2354 sp<EffectChain> chain;
2355 {
2356 Mutex::Autolock _sl(recordThread->mLock);
2357 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2358 // Note: maximum one chain per record thread
2359 if (effectChains.size() != 0) {
2360 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002361 }
2362 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002363 if (chain != 0) {
2364 // first check if a record thread is already opened with a client on the same session.
2365 // This should only happen in case of overlap between one thread tear down and the
2366 // creation of its replacement
2367 size_t i;
2368 for (i = 0; i < mRecordThreads.size(); i++) {
2369 sp<RecordThread> t = mRecordThreads.valueAt(i);
2370 if (t == recordThread) {
2371 continue;
2372 }
2373 if (t->hasAudioSession(chain->sessionId()) != 0) {
2374 Mutex::Autolock _l(t->mLock);
2375 ALOGV("closeInput() found thread %d for effect session %d",
2376 t->id(), chain->sessionId());
2377 t->addEffectChain_l(chain);
2378 break;
2379 }
2380 }
2381 // put the chain aside if we could not find a record thread with the same session id.
2382 if (i == mRecordThreads.size()) {
2383 putOrphanEffectChain_l(chain);
2384 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002385 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002386 mRecordThreads.removeItem(input);
2387 } else {
2388 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2389 if (mmapThread == 0) {
2390 return BAD_VALUE;
2391 }
2392 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002393 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002394 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2395 ioDesc->mIoHandle = input;
2396 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 }
Eric Laurent83b88082014-06-20 18:31:16 -07002398 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2399 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002400 if (recordThread != 0) {
2401 closeInputFinish(recordThread);
2402 } else if (mmapThread != 0) {
2403 mmapThread->exit();
2404 AudioStreamIn *in = mmapThread->clearInput();
2405 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2406 // from now on thread->mInput is NULL
2407 delete in;
2408 }
Eric Laurent83b88082014-06-20 18:31:16 -07002409 return NO_ERROR;
2410}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002412void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002413{
2414 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002415 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002416 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002417 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002418 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002419}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002421void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002422{
2423 mRecordThreads.removeItem(thread->mId);
2424 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425}
2426
Glenn Kastend2304db2014-02-03 07:40:31 -08002427status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428{
2429 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002430 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431
2432 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2433 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002434 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002435 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002436 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2437 mMmapThreads[i]->invalidateTracks(stream);
2438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 return NO_ERROR;
2440}
2441
2442
Glenn Kasteneeecb982016-02-26 10:44:04 -08002443audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444{
Glenn Kasten9d003132016-04-06 14:38:09 -07002445 // This is a binder API, so a malicious client could pass in a bad parameter.
2446 // Check for that before calling the internal API nextUniqueId().
2447 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2448 ALOGE("newAudioUniqueId invalid use %d", use);
2449 return AUDIO_UNIQUE_ID_ALLOCATE;
2450 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002451 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452}
2453
Glenn Kastend848eb42016-03-08 13:42:11 -08002454void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002455{
2456 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002457 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002458 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2459 if (pid != -1 && (caller == getpid_cached)) {
2460 caller = pid;
2461 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002462
Eric Laurent021cf962014-05-13 10:18:14 -07002463 {
2464 Mutex::Autolock _cl(mClientLock);
2465 // Ignore requests received from processes not known as notification client. The request
2466 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2467 // called from a different pid leaving a stale session reference. Also we don't know how
2468 // to clear this reference if the client process dies.
2469 if (mNotificationClients.indexOfKey(caller) < 0) {
2470 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2471 return;
2472 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002473 }
2474
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002475 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002476 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002477 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002478 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2479 ref->mCnt++;
2480 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002481 return;
2482 }
2483 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002484 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2485 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002486}
2487
Glenn Kastend848eb42016-03-08 13:42:11 -08002488void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002489{
2490 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002491 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002492 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2493 if (pid != -1 && (caller == getpid_cached)) {
2494 caller = pid;
2495 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002496 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002497 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002498 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002499 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2500 ref->mCnt--;
2501 ALOGV(" decremented refcount to %d", ref->mCnt);
2502 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002503 mAudioSessionRefs.removeAt(i);
2504 delete ref;
2505 purgeStaleEffects_l();
2506 }
2507 return;
2508 }
2509 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002510 // If the caller is mediaserver it is likely that the session being released was acquired
2511 // on behalf of a process not in notification clients and we ignore the warning.
2512 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002513}
2514
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002515bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2516{
2517 size_t num = mAudioSessionRefs.size();
2518 for (size_t i = 0; i < num; i++) {
2519 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2520 if (ref->mSessionid == audioSession) {
2521 return true;
2522 }
2523 }
2524 return false;
2525}
2526
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002527void AudioFlinger::purgeStaleEffects_l() {
2528
Steve Block3856b092011-10-20 11:56:00 +01002529 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002530
2531 Vector< sp<EffectChain> > chains;
2532
2533 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2534 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2535 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2536 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002537 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2538 chains.push(ec);
2539 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002540 }
2541 }
2542 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2543 sp<RecordThread> t = mRecordThreads.valueAt(i);
2544 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2545 sp<EffectChain> ec = t->mEffectChains[j];
2546 chains.push(ec);
2547 }
2548 }
2549
2550 for (size_t i = 0; i < chains.size(); i++) {
2551 sp<EffectChain> ec = chains[i];
2552 int sessionid = ec->sessionId();
2553 sp<ThreadBase> t = ec->mThread.promote();
2554 if (t == 0) {
2555 continue;
2556 }
2557 size_t numsessionrefs = mAudioSessionRefs.size();
2558 bool found = false;
2559 for (size_t k = 0; k < numsessionrefs; k++) {
2560 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002561 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002562 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002563 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002564 found = true;
2565 break;
2566 }
2567 }
2568 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002569 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002570 // remove all effects from the chain
2571 while (ec->mEffects.size()) {
2572 sp<EffectModule> effect = ec->mEffects[0];
2573 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002574 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002575 if (effect->purgeHandles()) {
2576 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002577 }
2578 AudioSystem::unregisterEffect(effect->id());
2579 }
2580 }
2581 }
2582 return;
2583}
2584
Glenn Kasteneeecb982016-02-26 10:44:04 -08002585// checkThread_l() must be called with AudioFlinger::mLock held
2586AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2587{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002588 ThreadBase *thread = checkMmapThread_l(ioHandle);
2589 if (thread == 0) {
2590 switch (audio_unique_id_get_use(ioHandle)) {
2591 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2592 thread = checkPlaybackThread_l(ioHandle);
2593 break;
2594 case AUDIO_UNIQUE_ID_USE_INPUT:
2595 thread = checkRecordThread_l(ioHandle);
2596 break;
2597 default:
2598 break;
2599 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002600 }
2601 return thread;
2602}
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002605AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606{
Glenn Kastena1117922012-01-26 10:53:32 -08002607 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608}
2609
2610// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002611AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612{
2613 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002614 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615}
2616
2617// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002618AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619{
Glenn Kastena1117922012-01-26 10:53:32 -08002620 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621}
2622
Eric Laurent6acd1d42017-01-04 14:23:29 -08002623// checkMmapThread_l() must be called with AudioFlinger::mLock held
2624AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2625{
2626 return mMmapThreads.valueFor(io).get();
2627}
2628
2629
2630// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2631AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2632{
2633 VolumeInterface *volumeInterface = (VolumeInterface *)mPlaybackThreads.valueFor(output).get();
2634 if (volumeInterface == nullptr) {
2635 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2636 if (mmapThread != nullptr) {
2637 if (mmapThread->isOutput()) {
2638 volumeInterface = (VolumeInterface *)mmapThread;
2639 }
2640 }
2641 }
2642 return volumeInterface;
2643}
2644
2645Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2646{
2647 Vector <VolumeInterface *> volumeInterfaces;
2648 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2649 volumeInterfaces.add((VolumeInterface *)mPlaybackThreads.valueAt(i).get());
2650 }
2651 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2652 if (mMmapThreads.valueAt(i)->isOutput()) {
2653 volumeInterfaces.add((VolumeInterface *)mMmapThreads.valueAt(i).get());
2654 }
2655 }
2656 return volumeInterfaces;
2657}
2658
Glenn Kasteneeecb982016-02-26 10:44:04 -08002659audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660{
Glenn Kasten9d003132016-04-06 14:38:09 -07002661 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002662 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002663 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2664 for (int retry = 0; retry < maxRetries; retry++) {
2665 // The cast allows wraparound from max positive to min negative instead of abort
2666 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2667 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2668 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2669 // allow wrap by skipping 0 and -1 for session ids
2670 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2671 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2672 return (audio_unique_id_t) (base | use);
2673 }
2674 }
2675 // We have no way of recovering from wraparound
2676 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2677 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678}
2679
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002680AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002681{
2682 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2683 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002684 if(thread->isDuplicating()) {
2685 continue;
2686 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002687 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002688 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002689 return thread;
2690 }
2691 }
2692 return NULL;
2693}
2694
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002695audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002696{
2697 PlaybackThread *thread = primaryPlaybackThread_l();
2698
2699 if (thread == NULL) {
2700 return 0;
2701 }
2702
Eric Laurentf1c04f92012-08-28 14:26:53 -07002703 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002704}
2705
Glenn Kastena7335632016-06-09 17:09:53 -07002706AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2707{
2708 size_t minFrameCount = 0;
2709 PlaybackThread *minThread = NULL;
2710 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2711 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2712 if (!thread->isDuplicating()) {
2713 size_t frameCount = thread->frameCountHAL();
2714 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2715 (frameCount == minFrameCount && thread->hasFastMixer() &&
2716 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2717 minFrameCount = frameCount;
2718 minThread = thread;
2719 }
2720 }
2721 }
2722 return minThread;
2723}
2724
Eric Laurenta011e352012-03-29 15:51:43 -07002725sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002726 audio_session_t triggerSession,
2727 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002728 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002729 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002730{
2731 Mutex::Autolock _l(mLock);
2732
2733 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2734 status_t playStatus = NAME_NOT_FOUND;
2735 status_t recStatus = NAME_NOT_FOUND;
2736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2737 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2738 if (playStatus == NO_ERROR) {
2739 return event;
2740 }
2741 }
2742 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2743 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2744 if (recStatus == NO_ERROR) {
2745 return event;
2746 }
2747 }
2748 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2749 mPendingSyncEvents.add(event);
2750 } else {
2751 ALOGV("createSyncEvent() invalid event %d", event->type());
2752 event.clear();
2753 }
2754 return event;
2755}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002756
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757// ----------------------------------------------------------------------------
2758// Effect management
2759// ----------------------------------------------------------------------------
2760
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002761sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2762 return mEffectsFactoryHal;
2763}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764
Glenn Kastenf587ba52012-01-26 16:25:10 -08002765status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766{
2767 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002768 if (mEffectsFactoryHal.get()) {
2769 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2770 } else {
2771 return -ENODEV;
2772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773}
2774
Glenn Kastenf587ba52012-01-26 16:25:10 -08002775status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776{
2777 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002778 if (mEffectsFactoryHal.get()) {
2779 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2780 } else {
2781 return -ENODEV;
2782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783}
2784
Glenn Kasten5e92a782012-01-30 07:40:52 -08002785status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002786 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787{
2788 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002789 if (mEffectsFactoryHal.get()) {
2790 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2791 } else {
2792 return -ENODEV;
2793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794}
2795
2796
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002797sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 effect_descriptor_t *pDesc,
2799 const sp<IEffectClient>& effectClient,
2800 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002801 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002802 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002803 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002804 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 status_t *status,
2806 int *id,
2807 int *enabled)
2808{
2809 status_t lStatus = NO_ERROR;
2810 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812
Eric Laurentb6436272016-12-07 19:24:50 -08002813 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2814 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2815 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2816 ALOGW_IF(pid != -1 && pid != callingPid,
2817 "%s uid %d pid %d tried to pass itself off as pid %d",
2818 __func__, callingUid, callingPid, pid);
2819 pid = callingPid;
2820 }
2821
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002822 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2823 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824
2825 if (pDesc == NULL) {
2826 lStatus = BAD_VALUE;
2827 goto Exit;
2828 }
2829
Eric Laurent84e9a102010-09-23 16:10:16 -07002830 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002831 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002832 lStatus = PERMISSION_DENIED;
2833 goto Exit;
2834 }
2835
Dima Zavinfce7a472011-04-19 22:30:36 -07002836 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002837 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002838 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002839 lStatus = PERMISSION_DENIED;
2840 goto Exit;
2841 }
2842
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002843 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002844 lStatus = NO_INIT;
2845 goto Exit;
2846 }
2847
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002849 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002851 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002853 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 goto Exit;
2855 }
2856 } else {
2857 // if uuid is not specified, look for an available implementation
2858 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002859 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002860 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 lStatus = BAD_VALUE;
2862 goto Exit;
2863 }
2864 uint32_t numEffects = 0;
2865 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002866 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 bool found = false;
2868
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002869 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002871 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 goto Exit;
2873 }
2874 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002875 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002877 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 continue;
2879 }
2880 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2881 // If matching type found save effect descriptor. If the session is
2882 // 0 and the effect is not auxiliary, continue enumeration in case
2883 // an auxiliary version of this effect type is available
2884 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002885 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002886 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2888 break;
2889 }
2890 }
2891 }
2892 if (!found) {
2893 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002894 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 goto Exit;
2896 }
2897 // For same effect type, chose auxiliary version over insert version if
2898 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002899 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002901 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 }
2903 }
2904
2905 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002906 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2908 lStatus = INVALID_OPERATION;
2909 goto Exit;
2910 }
2911
Eric Laurent59255e42011-07-27 19:49:51 -07002912 // check recording permission for visualizer
2913 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002914 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002915 lStatus = PERMISSION_DENIED;
2916 goto Exit;
2917 }
2918
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002920 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002921 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002922 // if the output returned by getOutputForEffect() is removed before we lock the
2923 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2924 // and we will exit safely
2925 io = AudioSystem::getOutputForEffect(&desc);
2926 ALOGV("createEffect got output %d", io);
2927 }
2928
2929 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930
2931 // If output is not specified try to find a matching audio session ID in one of the
2932 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002933 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2934 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002935 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002936 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002937 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2938 // output must be specified by AudioPolicyManager when using session
2939 // AUDIO_SESSION_OUTPUT_STAGE
2940 lStatus = BAD_VALUE;
2941 goto Exit;
2942 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002943 // look for the thread where the specified audio session is present
2944 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2945 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2946 io = mPlaybackThreads.keyAt(i);
2947 break;
2948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002950 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002951 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2952 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2953 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002954 break;
2955 }
2956 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002957 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002958 if (io == AUDIO_IO_HANDLE_NONE) {
2959 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2960 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2961 io = mMmapThreads.keyAt(i);
2962 break;
2963 }
2964 }
2965 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002966 // If no output thread contains the requested session ID, default to
2967 // first output. The effect chain will be moved to the correct output
2968 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002969 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002970 io = mPlaybackThreads.keyAt(0);
2971 }
Steve Block3856b092011-10-20 11:56:00 +01002972 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002973 }
2974 ThreadBase *thread = checkRecordThread_l(io);
2975 if (thread == NULL) {
2976 thread = checkPlaybackThread_l(io);
2977 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002978 thread = checkMmapThread_l(io);
2979 if (thread == NULL) {
2980 ALOGE("createEffect() unknown output thread");
2981 lStatus = BAD_VALUE;
2982 goto Exit;
2983 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002984 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002985 } else {
2986 // Check if one effect chain was awaiting for an effect to be created on this
2987 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002988 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002989 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002990 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002991 thread->addEffectChain_l(chain);
2992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002994
Eric Laurent021cf962014-05-13 10:18:14 -07002995 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002997 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002998 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002999 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003000 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 if (handle != 0 && id != NULL) {
3002 *id = handle->id();
3003 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003004 if (handle == 0) {
3005 // remove local strong reference to Client with mClientLock held
3006 Mutex::Autolock _cl(mClientLock);
3007 client.clear();
3008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 }
3010
3011Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003012 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 return handle;
3014}
3015
Glenn Kastend848eb42016-03-08 13:42:11 -08003016status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003017 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003018{
Steve Block3856b092011-10-20 11:56:00 +01003019 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003020 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003021 Mutex::Autolock _l(mLock);
3022 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003023 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003024 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025 }
Eric Laurentde070132010-07-13 04:45:46 -07003026 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3027 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003028 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003029 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 }
Eric Laurentde070132010-07-13 04:45:46 -07003031 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3032 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003033 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003034 return BAD_VALUE;
3035 }
3036
3037 Mutex::Autolock _dl(dstThread->mLock);
3038 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003039 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040}
3041
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003042// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003043status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003044 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003045 AudioFlinger::PlaybackThread *dstThread,
3046 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003047{
Steve Block3856b092011-10-20 11:56:00 +01003048 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003049 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003050
Eric Laurent59255e42011-07-27 19:49:51 -07003051 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003052 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003053 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003054 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003055 return INVALID_OPERATION;
3056 }
3057
Eric Laurent4c415062016-06-17 16:14:16 -07003058 // Check whether the destination thread and all effects in the chain are compatible
3059 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003060 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003061 " destination thread %p is not compatible with effects in the chain",
3062 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003063 return INVALID_OPERATION;
3064 }
3065
Eric Laurent39e94f82010-07-28 01:32:47 -07003066 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003067 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003068 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003069 // removed.
3070 srcThread->removeEffectChain_l(chain);
3071
3072 // transfer all effects one by one so that new effect chain is created on new thread with
3073 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003074 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003075 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003076 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003077 Vector< sp<EffectModule> > removed;
3078 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003079 while (effect != 0) {
3080 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003081 removed.add(effect);
3082 status = dstThread->addEffect_l(effect);
3083 if (status != NO_ERROR) {
3084 break;
3085 }
Eric Laurentec35a142011-10-05 17:42:25 -07003086 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3087 if (effect->state() == EffectModule::ACTIVE ||
3088 effect->state() == EffectModule::STOPPING) {
3089 effect->start();
3090 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003091 // if the move request is not received from audio policy manager, the effect must be
3092 // re-registered with the new strategy and output
3093 if (dstChain == 0) {
3094 dstChain = effect->chain().promote();
3095 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003096 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003097 status = NO_INIT;
3098 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003099 }
3100 strategy = dstChain->strategy();
3101 }
3102 if (reRegister) {
3103 AudioSystem::unregisterEffect(effect->id());
3104 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003105 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003106 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003107 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003108 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003109 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003110 }
Eric Laurentde070132010-07-13 04:45:46 -07003111 effect = chain->getEffectFromId_l(0);
3112 }
3113
Eric Laurent5baf2af2013-09-12 17:37:00 -07003114 if (status != NO_ERROR) {
3115 for (size_t i = 0; i < removed.size(); i++) {
3116 srcThread->addEffect_l(removed[i]);
3117 if (dstChain != 0 && reRegister) {
3118 AudioSystem::unregisterEffect(removed[i]->id());
3119 AudioSystem::registerEffect(&removed[i]->desc(),
3120 srcThread->id(),
3121 strategy,
3122 sessionId,
3123 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003124 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003125 }
3126 }
3127 }
3128
3129 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130}
3131
Eric Laurent5baf2af2013-09-12 17:37:00 -07003132bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003133{
3134 if (mGlobalEffectEnableTime != 0 &&
3135 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3136 return true;
3137 }
3138
3139 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3140 sp<EffectChain> ec =
3141 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003142 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003143 return true;
3144 }
3145 }
3146 return false;
3147}
3148
Eric Laurent5baf2af2013-09-12 17:37:00 -07003149void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003150{
3151 Mutex::Autolock _l(mLock);
3152
3153 mGlobalEffectEnableTime = systemTime();
3154
3155 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3156 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3157 if (t->mType == ThreadBase::OFFLOAD) {
3158 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3159 }
3160 }
3161
3162}
3163
Eric Laurentaaa44472014-09-12 17:41:50 -07003164status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3165{
Glenn Kastend848eb42016-03-08 13:42:11 -08003166 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003167 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003168 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003169 if (index >= 0) {
3170 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3171 return ALREADY_EXISTS;
3172 }
3173 mOrphanEffectChains.add(session, chain);
3174 return NO_ERROR;
3175}
3176
3177sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3178{
3179 sp<EffectChain> chain;
3180 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003181 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003182 if (index >= 0) {
3183 chain = mOrphanEffectChains.valueAt(index);
3184 mOrphanEffectChains.removeItemsAt(index);
3185 }
3186 return chain;
3187}
3188
3189bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3190{
3191 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003192 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003193 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003194 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003195 if (index >= 0) {
3196 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003197 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003198 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003199 mOrphanEffectChains.removeItemsAt(index);
3200 }
3201 return true;
3202 }
3203 return false;
3204}
3205
3206
Glenn Kastenda6ef132013-01-10 12:31:01 -08003207struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003208#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3209 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003210};
3211
3212int comparEntry(const void *p1, const void *p2)
3213{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003214 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003215}
3216
Glenn Kasten46909e72013-02-26 09:20:22 -08003217#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003218void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219{
Eric Laurent81784c32012-11-19 14:55:58 -08003220 NBAIO_Source *teeSource = source.get();
3221 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003222 // .wav rotation
3223 // There is a benign race condition if 2 threads call this simultaneously.
3224 // They would both traverse the directory, but the result would simply be
3225 // failures at unlink() which are ignored. It's also unlikely since
3226 // normally dumpsys is only done by bugreport or from the command line.
3227 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003228 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003229 size_t teePathLen = strlen(teePath);
3230 DIR *dir = opendir(teePath);
3231 teePath[teePathLen++] = '/';
3232 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003233#define TEE_MAX_SORT 20 // number of entries to sort
3234#define TEE_MAX_KEEP 10 // number of entries to keep
3235 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003236 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003237 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003238 struct dirent de;
3239 struct dirent *result = NULL;
3240 int rc = readdir_r(dir, &de, &result);
3241 if (rc != 0) {
3242 ALOGW("readdir_r failed %d", rc);
3243 break;
3244 }
3245 if (result == NULL) {
3246 break;
3247 }
3248 if (result != &de) {
3249 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3250 break;
3251 }
3252 // ignore non .wav file entries
3253 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003254 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003255 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3256 continue;
3257 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003258 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003259 }
3260 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003261 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003262 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003263 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3264 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003265 (void) unlink(teePath);
3266 }
3267 }
3268 } else {
3269 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003270 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003271 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003272 }
3273 }
Eric Laurent81784c32012-11-19 14:55:58 -08003274 char teeTime[16];
3275 struct timeval tv;
3276 gettimeofday(&tv, NULL);
3277 struct tm tm;
3278 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003279 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3280 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3281 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3282 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003283 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003284 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003285 char wavHeader[44];
3286 memcpy(wavHeader,
3287 "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",
3288 sizeof(wavHeader));
3289 NBAIO_Format format = teeSource->format();
3290 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003291 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003292 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003293 wavHeader[22] = channelCount; // number of channels
3294 wavHeader[24] = sampleRate; // sample rate
3295 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003296 wavHeader[32] = frameSize; // block alignment
3297 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003298 write(teeFd, wavHeader, sizeof(wavHeader));
3299 size_t total = 0;
3300 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003301#define TEE_SINK_READ 1024 // frames per I/O operation
3302 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003303 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003304 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003305 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003306 bool wasFirstRead = firstRead;
3307 firstRead = false;
3308 if (actual <= 0) {
3309 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3310 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003311 }
Eric Laurent81784c32012-11-19 14:55:58 -08003312 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003313 }
Eric Laurent81784c32012-11-19 14:55:58 -08003314 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003315 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003316 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003317 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003318 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003319 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003320 uint32_t temp = 44 + total * frameSize - 8;
3321 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003322 write(teeFd, &temp, sizeof(temp));
3323 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003324 temp = total * frameSize;
3325 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003326 write(teeFd, &temp, sizeof(temp));
3327 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003328 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003329 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003330 }
Eric Laurent59255e42011-07-27 19:49:51 -07003331 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003332 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003333 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003334 }
Eric Laurent59255e42011-07-27 19:49:51 -07003335 }
3336 }
3337}
Glenn Kasten46909e72013-02-26 09:20:22 -08003338#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340// ----------------------------------------------------------------------------
3341
3342status_t AudioFlinger::onTransact(
3343 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3344{
3345 return BnAudioFlinger::onTransact(code, data, reply, flags);
3346}
3347
Glenn Kasten63238ef2015-03-02 15:50:29 -08003348} // namespace android