blob: c0918d4fd0bb189e436b80e7ca9d4605d2403f22 [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(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800132 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800133 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800134 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700135 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800136 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800137 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700138 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800139 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700140 mBtNrecIsOff(false),
141 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700142 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700143 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700144 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700146 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
147 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
148 // zero ID has a special meaning, so unavailable
149 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
150 }
151
Glenn Kasten949a9262013-04-16 12:35:20 -0700152 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800153 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800154 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800155 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
156 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800157 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700158
Wei Jia3f273d12015-11-24 09:06:49 -0800159 // reset battery stats.
160 // if the audio service has crashed, battery stats could be left
161 // in bad state, reset the state upon service start.
162 BatteryNotifier::getInstance().noteResetAudio();
163
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700164 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700165 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
166
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800167 mMediaLogNotifier->run("MediaLogNotifier");
168
Glenn Kasten46909e72013-02-26 09:20:22 -0800169#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800170 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800171 (void) property_get("ro.debuggable", value, "0");
172 int debuggable = atoi(value);
173 int teeEnabled = 0;
174 if (debuggable) {
175 (void) property_get("af.tee", value, "0");
176 teeEnabled = atoi(value);
177 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800178 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700179 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800180 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700181 }
182 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800183 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700184 }
185 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800186 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700187 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800188#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700189}
190
191void AudioFlinger::onFirstRef()
192{
Eric Laurent93575202011-01-18 18:39:02 -0800193 Mutex::Autolock _l(mLock);
194
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800196 char val_str[PROPERTY_VALUE_MAX] = { 0 };
197 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
198 uint32_t int_val;
199 if (1 == sscanf(val_str, "%u", &int_val)) {
200 mStandbyTimeInNsecs = milliseconds(int_val);
201 ALOGI("Using %u mSec as standby time.", int_val);
202 } else {
203 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
204 ALOGI("Using default %u mSec as standby time.",
205 (uint32_t)(mStandbyTimeInNsecs / 1000000));
206 }
207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208
Eric Laurent1c333e22014-05-20 10:48:17 -0700209 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700210
Eric Laurenta4c5a552012-03-29 10:12:40 -0700211 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800212
213 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700214}
215
216AudioFlinger::~AudioFlinger()
217{
218 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700219 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700220 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221 }
222 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700223 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700224 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700226
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800227 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
228 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700229 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700230 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700231
232 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800233 if (mLogMemoryDealer != 0) {
234 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
235 if (binder != 0) {
236 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
237 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
238 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
239 mUnregisteredWriters.pop();
240 mediaLogService->unregisterWriter(iMemory);
241 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700242 }
243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244}
245
Eric Laurentfc235202016-12-20 18:48:17 -0800246//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800247__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800248status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
249 const audio_attributes_t *attr,
250 audio_config_base_t *config,
251 const MmapStreamInterface::Client& client,
252 audio_port_handle_t *deviceId,
253 const sp<MmapStreamCallback>& callback,
254 sp<MmapStreamInterface>& interface)
255{
256 sp<AudioFlinger> af;
257 {
258 Mutex::Autolock _l(gLock);
259 af = gAudioFlinger.promote();
260 }
261 status_t ret = NO_INIT;
262 if (af != 0) {
263 ret = af->openMmapStream(
264 direction, attr, config, client, deviceId, callback, interface);
265 }
266 return ret;
267}
268
Eric Laurent6acd1d42017-01-04 14:23:29 -0800269status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
270 const audio_attributes_t *attr,
271 audio_config_base_t *config,
272 const MmapStreamInterface::Client& client,
273 audio_port_handle_t *deviceId,
274 const sp<MmapStreamCallback>& callback,
275 sp<MmapStreamInterface>& interface)
Eric Laurentfc235202016-12-20 18:48:17 -0800276{
277 status_t ret = initCheck();
278 if (ret != NO_ERROR) {
279 return ret;
280 }
281
Eric Laurent6acd1d42017-01-04 14:23:29 -0800282 audio_session_t sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
283 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
284 audio_io_handle_t io;
285 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
286 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
287 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
288 fullConfig.sample_rate = config->sample_rate;
289 fullConfig.channel_mask = config->channel_mask;
290 fullConfig.format = config->format;
291 ret = AudioSystem::getOutputForAttr(attr, &io,
292 sessionId,
293 &streamType, client.clientUid,
294 &fullConfig,
295 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT),
296 *deviceId, &portId);
297 } else {
298 ret = AudioSystem::getInputForAttr(attr, &io,
299 sessionId,
300 client.clientPid,
301 client.clientUid,
302 config,
303 AUDIO_INPUT_FLAG_MMAP_NOIRQ, *deviceId, &portId);
304 }
305 if (ret != NO_ERROR) {
306 return ret;
307 }
308
309 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
310 // audio policy manager and we can retrieve it
311 sp<MmapThread> thread = mMmapThreads.valueFor(io);
312 if (thread != 0) {
313 interface = new MmapThreadHandle(thread);
314 thread->configure(attr, streamType, sessionId, callback, portId);
315 } else {
316 ret = NO_INIT;
317 }
318
319 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
320
Eric Laurentfc235202016-12-20 18:48:17 -0800321 return ret;
322}
323
Eric Laurenta4c5a552012-03-29 10:12:40 -0700324static const char * const audio_interfaces[] = {
325 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
326 AUDIO_HARDWARE_MODULE_ID_A2DP,
327 AUDIO_HARDWARE_MODULE_ID_USB,
328};
329#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
330
Phil Burk062e67a2015-02-11 13:40:50 -0800331AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700332 audio_module_handle_t module,
333 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700334{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700335 // if module is 0, the request comes from an old policy manager and we should load
336 // well known modules
337 if (module == 0) {
338 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
339 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
340 loadHwModule_l(audio_interfaces[i]);
341 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700342 // then try to find a module supporting the requested device.
343 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
344 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700345 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
346 uint32_t supportedDevices;
347 if (dev->getSupportedDevices(&supportedDevices) == OK &&
348 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700349 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700350 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700351 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700352 } else {
353 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700354 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
355 if (audioHwDevice != NULL) {
356 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700357 }
358 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700359
Dima Zavin799a70e2011-04-18 16:57:27 -0700360 return NULL;
361}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362
Glenn Kasten0f11b512014-01-31 16:18:54 -0800363void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364{
365 const size_t SIZE = 256;
366 char buffer[SIZE];
367 String8 result;
368
369 result.append("Clients:\n");
370 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800371 sp<Client> client = mClients.valueAt(i).promote();
372 if (client != 0) {
373 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
374 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 }
376 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700377
Eric Laurentd1b28d42013-09-18 18:47:13 -0700378 result.append("Notification Clients:\n");
379 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
380 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
381 result.append(buffer);
382 }
383
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700384 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800385 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700386 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
387 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800388 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700389 result.append(buffer);
390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392}
393
394
Glenn Kasten0f11b512014-01-31 16:18:54 -0800395void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700396{
397 const size_t SIZE = 256;
398 char buffer[SIZE];
399 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800400 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401
John Grossman4ff14ba2012-02-08 16:37:41 -0800402 snprintf(buffer, SIZE, "Hardware status: %d\n"
403 "Standby Time mSec: %u\n",
404 hardwareStatus,
405 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406 result.append(buffer);
407 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408}
409
Glenn Kasten0f11b512014-01-31 16:18:54 -0800410void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411{
412 const size_t SIZE = 256;
413 char buffer[SIZE];
414 String8 result;
415 snprintf(buffer, SIZE, "Permission Denial: "
416 "can't dump AudioFlinger from pid=%d, uid=%d\n",
417 IPCThreadState::self()->getCallingPid(),
418 IPCThreadState::self()->getCallingUid());
419 result.append(buffer);
420 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421}
422
Eric Laurent81784c32012-11-19 14:55:58 -0800423bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424{
425 bool locked = false;
426 for (int i = 0; i < kDumpLockRetries; ++i) {
427 if (mutex.tryLock() == NO_ERROR) {
428 locked = true;
429 break;
430 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800431 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 }
433 return locked;
434}
435
436status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
437{
Glenn Kasten44deb052012-02-05 18:09:08 -0800438 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 dumpPermissionDenial(fd, args);
440 } else {
441 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800442 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 if (!hardwareLocked) {
444 String8 result(kHardwareLockedString);
445 write(fd, result.string(), result.size());
446 } else {
447 mHardwareLock.unlock();
448 }
449
Eric Laurent81784c32012-11-19 14:55:58 -0800450 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451
452 // failed to lock - AudioFlinger is probably deadlocked
453 if (!locked) {
454 String8 result(kDeadlockedString);
455 write(fd, result.string(), result.size());
456 }
457
Eric Laurent021cf962014-05-13 10:18:14 -0700458 bool clientLocked = dumpTryLock(mClientLock);
459 if (!clientLocked) {
460 String8 result(kClientLockedString);
461 write(fd, result.string(), result.size());
462 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700463
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700464 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700465 mEffectsFactoryHal->dumpEffects(fd);
466 } else {
467 String8 result(kNoEffectsFactory);
468 write(fd, result.string(), result.size());
469 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700470
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700472 if (clientLocked) {
473 mClientLock.unlock();
474 }
475
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 dumpInternals(fd, args);
477
478 // dump playback threads
479 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
480 mPlaybackThreads.valueAt(i)->dump(fd, args);
481 }
482
483 // dump record threads
484 for (size_t i = 0; i < mRecordThreads.size(); i++) {
485 mRecordThreads.valueAt(i)->dump(fd, args);
486 }
487
Eric Laurent6acd1d42017-01-04 14:23:29 -0800488 // dump mmap threads
489 for (size_t i = 0; i < mMmapThreads.size(); i++) {
490 mMmapThreads.valueAt(i)->dump(fd, args);
491 }
492
Eric Laurentaaa44472014-09-12 17:41:50 -0700493 // dump orphan effect chains
494 if (mOrphanEffectChains.size() != 0) {
495 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
496 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
497 mOrphanEffectChains.valueAt(i)->dump(fd, args);
498 }
499 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700500 // dump all hardware devs
501 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700502 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
503 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700505
Glenn Kasten46909e72013-02-26 09:20:22 -0800506#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700507 // dump the serially shared record tee sink
508 if (mRecordTeeSource != 0) {
509 dumpTee(fd, mRecordTeeSource);
510 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800511#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700512
rago3bd1c872016-09-26 12:58:14 -0700513 BUFLOG_RESET;
514
Glenn Kastend65d73c2012-06-22 17:21:07 -0700515 if (locked) {
516 mLock.unlock();
517 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800518
519 // append a copy of media.log here by forwarding fd to it, but don't attempt
520 // to lookup the service if it's not running, as it will block for a second
521 if (mLogMemoryDealer != 0) {
522 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
523 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700524 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800525 Vector<String16> args;
526 binder->dump(fd, args);
527 }
528 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700529
530 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700531 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700532 bool unreachableMemory = false;
533 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700534 if (arg == String16("-m")) {
535 dumpMem = true;
536 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700537 unreachableMemory = true;
538 }
539 }
540
Andy Hung07b745e2016-05-23 16:21:07 -0700541 if (dumpMem) {
542 dprintf(fd, "\nDumping memory:\n");
543 std::string s = dumpMemoryAddresses(100 /* limit */);
544 write(fd, s.c_str(), s.size());
545 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700546 if (unreachableMemory) {
547 dprintf(fd, "\nDumping unreachable memory:\n");
548 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700549 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700550 write(fd, s.c_str(), s.size());
551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 }
553 return NO_ERROR;
554}
555
Eric Laurent021cf962014-05-13 10:18:14 -0700556sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800557{
Eric Laurent021cf962014-05-13 10:18:14 -0700558 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800559 // If pid is already in the mClients wp<> map, then use that entry
560 // (for which promote() is always != 0), otherwise create a new entry and Client.
561 sp<Client> client = mClients.valueFor(pid).promote();
562 if (client == 0) {
563 client = new Client(this, pid);
564 mClients.add(pid, client);
565 }
566
567 return client;
568}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569
Glenn Kasten9e58b552013-01-18 15:09:48 -0800570sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
571{
Glenn Kasten481fb672013-09-30 14:39:28 -0700572 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800573 if (mLogMemoryDealer == 0) {
574 return new NBLog::Writer();
575 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800576 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700577 // Similarly if we can't contact the media.log service, also return a dummy writer
578 if (binder == 0) {
579 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800580 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700581 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
582 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
583 // If allocation fails, consult the vector of previously unregistered writers
584 // and garbage-collect one or more them until an allocation succeeds
585 if (shared == 0) {
586 Mutex::Autolock _l(mUnregisteredWritersLock);
587 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
588 {
589 // Pick the oldest stale writer to garbage-collect
590 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
591 mUnregisteredWriters.removeAt(0);
592 mediaLogService->unregisterWriter(iMemory);
593 // Now the media.log remote reference to IMemory is gone. When our last local
594 // reference to IMemory also drops to zero at end of this block,
595 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
596 }
597 // Re-attempt the allocation
598 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
599 if (shared != 0) {
600 goto success;
601 }
602 }
603 // Even after garbage-collecting all old writers, there is still not enough memory,
604 // so return a dummy writer
605 return new NBLog::Writer();
606 }
607success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800608 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
609 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
610 // explicit destructor not needed since it is POD
Glenn Kasten481fb672013-09-30 14:39:28 -0700611 mediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800612 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800613}
614
615void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
616{
Glenn Kasten685ef092013-02-04 08:15:34 -0800617 if (writer == 0) {
618 return;
619 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800620 sp<IMemory> iMemory(writer->getIMemory());
621 if (iMemory == 0) {
622 return;
623 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700624 // Rather than removing the writer immediately, append it to a queue of old writers to
625 // be garbage-collected later. This allows us to continue to view old logs for a while.
626 Mutex::Autolock _l(mUnregisteredWritersLock);
627 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800628}
629
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630// IAudioFlinger interface
631
632
633sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800634 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800636 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700637 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800638 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700639 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800641 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700642 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800643 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800644 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800645 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800646 status_t *status,
647 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648{
649 sp<PlaybackThread::Track> track;
650 sp<TrackHandle> trackHandle;
651 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800653 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700655 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
656 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
657 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
658 ALOGW_IF(pid != -1 && pid != callingPid,
659 "%s uid %d pid %d tried to pass itself off as pid %d",
660 __func__, callingUid, callingPid, pid);
661 pid = callingPid;
662 }
663
Glenn Kasten263709e2012-01-06 08:40:01 -0800664 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
665 // but if someone uses binder directly they could bypass that and cause us to crash
666 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000667 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 lStatus = BAD_VALUE;
669 goto Exit;
670 }
671
Glenn Kasten53b5d092014-02-05 10:00:23 -0800672 // further sample rate checks are performed by createTrack_l() depending on the thread type
673 if (sampleRate == 0) {
674 ALOGE("createTrack() invalid sample rate %u", sampleRate);
675 lStatus = BAD_VALUE;
676 goto Exit;
677 }
678
679 // further channel mask checks are performed by createTrack_l() depending on the thread type
680 if (!audio_is_output_channel(channelMask)) {
681 ALOGE("createTrack() invalid channel mask %#x", channelMask);
682 lStatus = BAD_VALUE;
683 goto Exit;
684 }
685
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700686 // further format checks are performed by createTrack_l() depending on the thread type
687 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800688 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700689 lStatus = BAD_VALUE;
690 goto Exit;
691 }
692
Glenn Kasten663c2242013-09-24 11:52:37 -0700693 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
694 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
695 lStatus = BAD_VALUE;
696 goto Exit;
697 }
698
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 {
700 Mutex::Autolock _l(mLock);
701 PlaybackThread *thread = checkPlaybackThread_l(output);
702 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800703 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 lStatus = BAD_VALUE;
705 goto Exit;
706 }
707
Eric Laurent021cf962014-05-13 10:18:14 -0700708 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709
Glenn Kastene848bd92014-03-13 15:00:32 -0700710 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700711 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800712 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
713 ALOGE("createTrack() invalid session ID %d", *sessionId);
714 lStatus = BAD_VALUE;
715 goto Exit;
716 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700717 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700718 // check if an effect chain with the same session ID is present on another
719 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700721 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
722 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700723 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700724 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700725 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700726 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700727 }
Eric Laurentde070132010-07-13 04:45:46 -0700728 }
729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700731 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800732 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733 if (sessionId != NULL) {
734 *sessionId = lSessionId;
735 }
736 }
Steve Block3856b092011-10-20 11:56:00 +0100737 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738
739 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800740 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
741 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800742 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700743 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700744
745 // move effect chain to this output thread if an effect on same session was waiting
746 // for a track to be created
747 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700748 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700749 Mutex::Autolock _dl(thread->mLock);
750 Mutex::Autolock _sl(effectThread->mLock);
751 moveEffectChain_l(lSessionId, effectThread, thread, true);
752 }
Eric Laurenta011e352012-03-29 15:51:43 -0700753
754 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700755 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700756 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
757 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700758 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700759 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700760 } else {
761 mPendingSyncEvents[i]->cancel();
762 }
Eric Laurenta011e352012-03-29 15:51:43 -0700763 mPendingSyncEvents.removeAt(i);
764 i--;
765 }
766 }
767 }
Glenn Kastene198c362013-08-13 09:13:36 -0700768
Glenn Kastend848eb42016-03-08 13:42:11 -0800769 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 }
Glenn Kastene198c362013-08-13 09:13:36 -0700771
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700772 if (lStatus != NO_ERROR) {
773 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700774 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700775 // Don't hold mClientLock when releasing the reference on the track as the
776 // destructor will acquire it.
777 {
778 Mutex::Autolock _cl(mClientLock);
779 client.clear();
780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700782 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 }
784
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700785 // return handle to client
786 trackHandle = new TrackHandle(track);
787
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700789 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 return trackHandle;
791}
792
Glenn Kasten2c073da2016-02-26 09:14:08 -0800793uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794{
795 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800796 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800798 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799 return 0;
800 }
801 return thread->sampleRate();
802}
803
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800804audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
806 Mutex::Autolock _l(mLock);
807 PlaybackThread *thread = checkPlaybackThread_l(output);
808 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000809 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800810 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 return thread->format();
813}
814
Glenn Kasten2c073da2016-02-26 09:14:08 -0800815size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816{
817 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800818 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800820 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 return 0;
822 }
Glenn Kasten58912562012-04-03 10:45:00 -0700823 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
824 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 return thread->frameCount();
826}
827
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700828size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
829{
830 Mutex::Autolock _l(mLock);
831 ThreadBase *thread = checkThread_l(ioHandle);
832 if (thread == NULL) {
833 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
834 return 0;
835 }
836 return thread->frameCountHAL();
837}
838
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800839uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
841 Mutex::Autolock _l(mLock);
842 PlaybackThread *thread = checkPlaybackThread_l(output);
843 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800844 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
847 return thread->latency();
848}
849
850status_t AudioFlinger::setMasterVolume(float value)
851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return ret;
855 }
856
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 // check calling permissions
858 if (!settingsAllowed()) {
859 return PERMISSION_DENIED;
860 }
861
Eric Laurenta4c5a552012-03-29 10:12:40 -0700862 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700863 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700864
John Grossmanee578c02012-07-23 17:05:46 -0700865 // Set master volume in the HALs which support it.
866 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
867 AutoMutex lock(mHardwareLock);
868 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800869
John Grossmanee578c02012-07-23 17:05:46 -0700870 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
871 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700872 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800873 }
John Grossmanee578c02012-07-23 17:05:46 -0700874 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876
John Grossmanee578c02012-07-23 17:05:46 -0700877 // Now set the master volume in each playback thread. Playback threads
878 // assigned to HALs which do not have master volume support will apply
879 // master volume during the mix operation. Threads with HALs which do
880 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700881 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
882 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
883 continue;
884 }
John Grossmanee578c02012-07-23 17:05:46 -0700885 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887
888 return NO_ERROR;
889}
890
Glenn Kastenf78aee72012-01-04 11:00:47 -0800891status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892{
Eric Laurenta1884f92011-08-23 08:25:03 -0700893 status_t ret = initCheck();
894 if (ret != NO_ERROR) {
895 return ret;
896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897
898 // check calling permissions
899 if (!settingsAllowed()) {
900 return PERMISSION_DENIED;
901 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800902 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000903 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 return BAD_VALUE;
905 }
906
907 { // scope for the lock
908 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700909 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700911 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 mHardwareStatus = AUDIO_HW_IDLE;
913 }
914
915 if (NO_ERROR == ret) {
916 Mutex::Autolock _l(mLock);
917 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800918 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700919 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 return ret;
923}
924
925status_t AudioFlinger::setMicMute(bool state)
926{
Eric Laurenta1884f92011-08-23 08:25:03 -0700927 status_t ret = initCheck();
928 if (ret != NO_ERROR) {
929 return ret;
930 }
931
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 // check calling permissions
933 if (!settingsAllowed()) {
934 return PERMISSION_DENIED;
935 }
936
937 AutoMutex lock(mHardwareLock);
938 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700939 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700940 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
941 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700942 if (result != NO_ERROR) {
943 ret = result;
944 }
945 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 mHardwareStatus = AUDIO_HW_IDLE;
947 return ret;
948}
949
950bool AudioFlinger::getMicMute() const
951{
Eric Laurenta1884f92011-08-23 08:25:03 -0700952 status_t ret = initCheck();
953 if (ret != NO_ERROR) {
954 return false;
955 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800956 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700957 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800958 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800960 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700961 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
962 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800963 if (result == NO_ERROR) {
964 mute = mute && state;
965 }
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800968
969 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970}
971
972status_t AudioFlinger::setMasterMute(bool muted)
973{
John Grossmand8f178d2012-07-20 14:51:35 -0700974 status_t ret = initCheck();
975 if (ret != NO_ERROR) {
976 return ret;
977 }
978
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 // check calling permissions
980 if (!settingsAllowed()) {
981 return PERMISSION_DENIED;
982 }
983
John Grossmanee578c02012-07-23 17:05:46 -0700984 Mutex::Autolock _l(mLock);
985 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700986
John Grossmanee578c02012-07-23 17:05:46 -0700987 // Set master mute in the HALs which support it.
988 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
989 AutoMutex lock(mHardwareLock);
990 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700991
John Grossmanee578c02012-07-23 17:05:46 -0700992 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
993 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700994 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700995 }
John Grossmanee578c02012-07-23 17:05:46 -0700996 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700997 }
998
John Grossmanee578c02012-07-23 17:05:46 -0700999 // Now set the master mute in each playback thread. Playback threads
1000 // assigned to HALs which do not have master mute support will apply master
1001 // mute during the mix operation. Threads with HALs which do support master
1002 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001003 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1004 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1005 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001006 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007
1008 return NO_ERROR;
1009}
1010
1011float AudioFlinger::masterVolume() const
1012{
Glenn Kasten98067102011-12-13 11:47:54 -08001013 Mutex::Autolock _l(mLock);
1014 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015}
1016
1017bool AudioFlinger::masterMute() const
1018{
Glenn Kasten98067102011-12-13 11:47:54 -08001019 Mutex::Autolock _l(mLock);
1020 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021}
1022
John Grossman4ff14ba2012-02-08 16:37:41 -08001023float AudioFlinger::masterVolume_l() const
1024{
John Grossman4ff14ba2012-02-08 16:37:41 -08001025 return mMasterVolume;
1026}
1027
John Grossmand8f178d2012-07-20 14:51:35 -07001028bool AudioFlinger::masterMute_l() const
1029{
John Grossmanee578c02012-07-23 17:05:46 -07001030 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001031}
1032
Eric Laurent223fd5c2014-11-11 13:43:36 -08001033status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1034{
1035 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001036 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001037 return BAD_VALUE;
1038 }
1039 pid_t caller = IPCThreadState::self()->getCallingPid();
1040 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001041 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001042 return PERMISSION_DENIED;
1043 }
1044
1045 return NO_ERROR;
1046}
1047
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001048status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1049 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050{
1051 // check calling permissions
1052 if (!settingsAllowed()) {
1053 return PERMISSION_DENIED;
1054 }
1055
Eric Laurent223fd5c2014-11-11 13:43:36 -08001056 status_t status = checkStreamType(stream);
1057 if (status != NO_ERROR) {
1058 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001060 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061
1062 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001063 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001064 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001065 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1066 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 return BAD_VALUE;
1068 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001069 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 }
1071
1072 mStreamTypes[stream].volume = value;
1073
Eric Laurent6acd1d42017-01-04 14:23:29 -08001074 if (volumeInterfaces.size() == 0) {
1075 volumeInterfaces = getAllVolumeInterfaces_l();
1076 }
1077 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1078 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 }
1080
1081 return NO_ERROR;
1082}
1083
Glenn Kastenfff6d712012-01-12 16:38:12 -08001084status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085{
1086 // check calling permissions
1087 if (!settingsAllowed()) {
1088 return PERMISSION_DENIED;
1089 }
1090
Eric Laurent223fd5c2014-11-11 13:43:36 -08001091 status_t status = checkStreamType(stream);
1092 if (status != NO_ERROR) {
1093 return status;
1094 }
1095 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1096
1097 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001098 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 return BAD_VALUE;
1100 }
1101
Eric Laurent93575202011-01-18 18:39:02 -08001102 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001104 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1105 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1106 volumeInterfaces[i]->setStreamMute(stream, muted);
1107 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108
1109 return NO_ERROR;
1110}
1111
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001112float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001114 status_t status = checkStreamType(stream);
1115 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 return 0.0f;
1117 }
1118
1119 AutoMutex lock(mLock);
1120 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001121 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001122 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1123 if (volumeInterface != NULL) {
1124 volume = volumeInterface->streamVolume(stream);
1125 } else {
1126 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001129 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 }
1131
1132 return volume;
1133}
1134
Glenn Kastenfff6d712012-01-12 16:38:12 -08001135bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001137 status_t status = checkStreamType(stream);
1138 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 return true;
1140 }
1141
Glenn Kasten6637baa2012-01-09 09:40:36 -08001142 AutoMutex lock(mLock);
1143 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144}
1145
Eric Laurent054d9d32015-04-24 08:48:48 -07001146
1147void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1148{
1149 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1150 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1151 }
1152}
1153
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001154status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001156 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1157 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001158
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 // check calling permissions
1160 if (!settingsAllowed()) {
1161 return PERMISSION_DENIED;
1162 }
1163
Glenn Kasten142f5192014-03-25 17:44:59 -07001164 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1165 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001166 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001167 // result will remain NO_INIT if no audio device is present
1168 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001169 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001170 AutoMutex lock(mHardwareLock);
1171 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1172 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001173 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1174 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001175 // return success if at least one audio device accepts the parameters as not all
1176 // HALs are requested to support all parameters. If no audio device supports the
1177 // requested parameters, the last error is reported.
1178 if (final_result != NO_ERROR) {
1179 final_result = result;
1180 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001181 }
1182 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001183 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001184 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1185 AudioParameter param = AudioParameter(keyValuePairs);
1186 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001187 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1188 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001189 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001190 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1191 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001192 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001193 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1194 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001195 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001196 // suspend effects associated with those session IDs
1197 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001198 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001199 thread->setEffectSuspended(FX_IID_AEC,
1200 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001201 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001202 thread->setEffectSuspended(FX_IID_NS,
1203 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001204 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001205 }
1206 }
Eric Laurentbee53372011-08-29 12:42:48 -07001207 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001208 }
1209 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001210 String8 screenState;
1211 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001212 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001213 if (isOff != (AudioFlinger::mScreenState & 1)) {
1214 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001215 }
1216 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001217 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 }
1219
1220 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1221 // and the thread is exited once the lock is released
1222 sp<ThreadBase> thread;
1223 {
1224 Mutex::Autolock _l(mLock);
1225 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001226 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001228 if (thread == 0) {
1229 thread = checkMmapThread_l(ioHandle);
1230 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001231 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001232 // indicate output device change to all input threads for pre processing
1233 AudioParameter param = AudioParameter(keyValuePairs);
1234 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001235 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1236 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001237 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 }
1240 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001241 if (thread != 0) {
1242 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 }
1244 return BAD_VALUE;
1245}
1246
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001247String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001249 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1250 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251
Eric Laurenta4c5a552012-03-29 10:12:40 -07001252 Mutex::Autolock _l(mLock);
1253
Glenn Kasten142f5192014-03-25 17:44:59 -07001254 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001255 String8 out_s8;
1256
Dima Zavin799a70e2011-04-18 16:57:27 -07001257 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001258 String8 s;
1259 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001260 {
1261 AutoMutex lock(mHardwareLock);
1262 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001263 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1264 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001265 mHardwareStatus = AUDIO_HW_IDLE;
1266 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001267 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001268 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001269 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 }
1271
Eric Laurent6acd1d42017-01-04 14:23:29 -08001272 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1273 if (thread == NULL) {
1274 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1275 if (thread == NULL) {
1276 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1277 if (thread == NULL) {
1278 String8("");
1279 }
1280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001282 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283}
1284
Glenn Kastendd8104c2012-07-02 12:42:44 -07001285size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1286 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287{
Eric Laurenta1884f92011-08-23 08:25:03 -07001288 status_t ret = initCheck();
1289 if (ret != NO_ERROR) {
1290 return 0;
1291 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001292 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001293 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001294 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001295 return 0;
1296 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001297
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001298 AutoMutex lock(mHardwareLock);
1299 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001300 audio_config_t config, proposed;
1301 memset(&proposed, 0, sizeof(proposed));
1302 proposed.sample_rate = sampleRate;
1303 proposed.channel_mask = channelMask;
1304 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001305
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001306 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001307 size_t frames;
1308 for (;;) {
1309 // Note: config is currently a const parameter for get_input_buffer_size()
1310 // but we use a copy from proposed in case config changes from the call.
1311 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001312 status_t result = dev->getInputBufferSize(&config, &frames);
1313 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001314 break; // hal success, config is the result
1315 }
1316 // change one parameter of the configuration each iteration to a more "common" value
1317 // to see if the device will support it.
1318 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1319 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1320 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1321 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1322 } else {
1323 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1324 "format %#x, channelMask 0x%X",
1325 sampleRate, format, channelMask);
1326 break; // retries failed, break out of loop with frames == 0.
1327 }
1328 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001329 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001330 if (frames > 0 && config.sample_rate != sampleRate) {
1331 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1332 }
1333 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334}
1335
Glenn Kasten5f972c02014-01-13 09:59:31 -08001336uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338 Mutex::Autolock _l(mLock);
1339
1340 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1341 if (recordThread != NULL) {
1342 return recordThread->getInputFramesLost();
1343 }
1344 return 0;
1345}
1346
1347status_t AudioFlinger::setVoiceVolume(float value)
1348{
Eric Laurenta1884f92011-08-23 08:25:03 -07001349 status_t ret = initCheck();
1350 if (ret != NO_ERROR) {
1351 return ret;
1352 }
1353
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 // check calling permissions
1355 if (!settingsAllowed()) {
1356 return PERMISSION_DENIED;
1357 }
1358
1359 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001360 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001361 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001362 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 mHardwareStatus = AUDIO_HW_IDLE;
1364
1365 return ret;
1366}
1367
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001368status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001369 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371 Mutex::Autolock _l(mLock);
1372
1373 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1374 if (playbackThread != NULL) {
1375 return playbackThread->getRenderPosition(halFrames, dspFrames);
1376 }
1377
1378 return BAD_VALUE;
1379}
1380
1381void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1382{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001384 if (client == 0) {
1385 return;
1386 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001387 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001388 {
1389 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001390 if (mNotificationClients.indexOfKey(pid) < 0) {
1391 sp<NotificationClient> notificationClient = new NotificationClient(this,
1392 client,
1393 pid);
1394 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395
Eric Laurent021cf962014-05-13 10:18:14 -07001396 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397
Marco Nelissen06b46062014-11-14 07:58:25 -08001398 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001399 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001400 }
1401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402
Eric Laurent021cf962014-05-13 10:18:14 -07001403 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001404 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001405 // the config change is always sent from playback or record threads to avoid deadlock
1406 // with AudioSystem::gLock
1407 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1408 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1409 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001411 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1412 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413 }
1414}
1415
1416void AudioFlinger::removeNotificationClient(pid_t pid)
1417{
1418 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001419 {
1420 Mutex::Autolock _cl(mClientLock);
1421 mNotificationClients.removeItem(pid);
1422 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001423
Steve Block3856b092011-10-20 11:56:00 +01001424 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001425 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001426 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001427 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001428 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001429 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001430 if (ref->mPid == pid) {
1431 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001432 mAudioSessionRefs.removeAt(i);
1433 delete ref;
1434 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001435 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001436 } else {
1437 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001438 }
1439 }
1440 if (removed) {
1441 purgeStaleEffects_l();
1442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443}
1444
Eric Laurent73e26b62015-04-27 16:55:58 -07001445void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001446 const sp<AudioIoDescriptor>& ioDesc,
1447 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448{
Eric Laurent021cf962014-05-13 10:18:14 -07001449 Mutex::Autolock _l(mClientLock);
1450 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001452 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1453 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1454 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 }
1456}
1457
Eric Laurent021cf962014-05-13 10:18:14 -07001458// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459void AudioFlinger::removeClient_l(pid_t pid)
1460{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001461 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001462 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463 mClients.removeItem(pid);
1464}
1465
Eric Laurent717e1282012-06-29 16:36:52 -07001466// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001467sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1468 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001469{
1470 sp<PlaybackThread> thread;
1471
1472 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1473 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1474 ALOG_ASSERT(thread == 0);
1475 thread = mPlaybackThreads.valueAt(i);
1476 }
1477 }
1478
1479 return thread;
1480}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483
1484// ----------------------------------------------------------------------------
1485
1486AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1487 : RefBase(),
1488 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001489 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301491 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1492 heapSize *= 1024;
1493 if (!heapSize) {
1494 heapSize = kClientSharedHeapSizeBytes;
1495 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1496 // invalidated tracks
1497 if (!audioFlinger->isLowRamDevice()) {
1498 heapSize *= kClientSharedHeapSizeMultiplier;
1499 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001500 }
1501 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502}
1503
Eric Laurent021cf962014-05-13 10:18:14 -07001504// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505AudioFlinger::Client::~Client()
1506{
1507 mAudioFlinger->removeClient_l(mPid);
1508}
1509
Glenn Kasten435dbe62012-01-30 10:15:48 -08001510sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511{
1512 return mMemoryDealer;
1513}
1514
1515// ----------------------------------------------------------------------------
1516
1517AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1518 const sp<IAudioFlingerClient>& client,
1519 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001520 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521{
1522}
1523
1524AudioFlinger::NotificationClient::~NotificationClient()
1525{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526}
1527
Glenn Kasten0f11b512014-01-31 16:18:54 -08001528void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529{
1530 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001531 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532}
1533
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001534// ----------------------------------------------------------------------------
1535AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1536 : mPendingRequests(false) {}
1537
1538
1539void AudioFlinger::MediaLogNotifier::requestMerge() {
1540 AutoMutex _l(mMutex);
1541 mPendingRequests = true;
1542 mCond.signal();
1543}
1544
1545bool AudioFlinger::MediaLogNotifier::threadLoop() {
1546 // Wait until there are pending requests
1547 {
1548 AutoMutex _l(mMutex);
1549 mPendingRequests = false; // to ignore past requests
1550 while (!mPendingRequests) {
1551 mCond.wait(mMutex);
1552 // TODO may also need an exitPending check
1553 }
1554 mPendingRequests = false;
1555 }
1556 // Execute the actual MediaLogService binder call and ignore extra requests for a while
1557 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
1558 if (binder != 0) {
1559 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
1560 mediaLogService->requestMergeWakeup();
1561 }
1562 usleep(kPostTriggerSleepPeriod);
1563 return true;
1564}
1565
1566void AudioFlinger::requestLogMerge() {
1567 mMediaLogNotifier->requestMerge();
1568}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569
1570// ----------------------------------------------------------------------------
1571
1572sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001573 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001575 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001576 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001577 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001578 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001579 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001580 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001581 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001582 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001583 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001584 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001585 sp<IMemory>& cblk,
1586 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001587 status_t *status,
1588 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589{
1590 sp<RecordThread::RecordTrack> recordTrack;
1591 sp<RecordHandle> recordHandle;
1592 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001594 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595
Glenn Kastend776ac62014-05-07 09:16:09 -07001596 cblk.clear();
1597 buffers.clear();
1598
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001599 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001600 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1601 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001602 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001603 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1604 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001605 updatePid = true;
1606 }
1607
1608 if (updatePid) {
1609 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1610 ALOGW_IF(pid != -1 && pid != callingPid,
1611 "%s uid %d pid %d tried to pass itself off as pid %d",
1612 __func__, callingUid, callingPid, pid);
1613 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001614 }
1615
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001617 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001618 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619 lStatus = PERMISSION_DENIED;
1620 goto Exit;
1621 }
1622
Glenn Kasten53b5d092014-02-05 10:00:23 -08001623 // further sample rate checks are performed by createRecordTrack_l()
1624 if (sampleRate == 0) {
1625 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1626 lStatus = BAD_VALUE;
1627 goto Exit;
1628 }
1629
Andy Hung6770c6f2015-04-07 13:43:36 -07001630 // we don't yet support anything other than linear PCM
1631 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001632 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001633 lStatus = BAD_VALUE;
1634 goto Exit;
1635 }
1636
Glenn Kasten53b5d092014-02-05 10:00:23 -08001637 // further channel mask checks are performed by createRecordTrack_l()
1638 if (!audio_is_input_channel(channelMask)) {
1639 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1640 lStatus = BAD_VALUE;
1641 goto Exit;
1642 }
1643
Glenn Kasten05997e22014-03-13 15:08:33 -07001644 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001646 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001648 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 lStatus = BAD_VALUE;
1650 goto Exit;
1651 }
1652
Eric Laurent021cf962014-05-13 10:18:14 -07001653 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001655 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001656 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1657 lStatus = BAD_VALUE;
1658 goto Exit;
1659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 lSessionId = *sessionId;
1661 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001662 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001663 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 if (sessionId != NULL) {
1665 *sessionId = lSessionId;
1666 }
1667 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001668 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001669
Glenn Kasten1879fff2012-07-11 15:36:59 -07001670 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001671 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001672 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001673 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001674
1675 if (lStatus == NO_ERROR) {
1676 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1677 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001678 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001679 if (chain != 0) {
1680 Mutex::Autolock _l(thread->mLock);
1681 thread->addEffectChain_l(chain);
1682 }
1683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 }
Glenn Kastene198c362013-08-13 09:13:36 -07001685
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001686 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001687 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001688 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001689 // Don't hold mClientLock when releasing the reference on the track as the
1690 // destructor will acquire it.
1691 {
1692 Mutex::Autolock _cl(mClientLock);
1693 client.clear();
1694 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 goto Exit;
1697 }
1698
Glenn Kastend776ac62014-05-07 09:16:09 -07001699 cblk = recordTrack->getCblk();
1700 buffers = recordTrack->getBuffers();
1701
Glenn Kasten2fc14732013-08-05 14:58:14 -07001702 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704
1705Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001706 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707 return recordHandle;
1708}
1709
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001710
1711
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712// ----------------------------------------------------------------------------
1713
Eric Laurenta4c5a552012-03-29 10:12:40 -07001714audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1715{
Eric Laurent44622db2014-08-01 19:00:33 -07001716 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001717 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001718 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001719 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001720 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001721 }
1722 Mutex::Autolock _l(mLock);
1723 return loadHwModule_l(name);
1724}
1725
1726// loadHwModule_l() must be called with AudioFlinger::mLock held
1727audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1728{
1729 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1730 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1731 ALOGW("loadHwModule() module %s already loaded", name);
1732 return mAudioHwDevs.keyAt(i);
1733 }
1734 }
1735
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001736 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001737
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001738 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001739 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001740 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001741 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001742 }
1743
1744 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001745 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001746 mHardwareStatus = AUDIO_HW_IDLE;
1747 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001748 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001749 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001750 }
1751
John Grossmanee578c02012-07-23 17:05:46 -07001752 // Check and cache this HAL's level of support for master mute and master
1753 // volume. If this is the first HAL opened, and it supports the get
1754 // methods, use the initial values provided by the HAL as the current
1755 // master mute and volume settings.
1756
1757 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1758 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001759 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001760
1761 if (0 == mAudioHwDevs.size()) {
1762 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001763 float mv;
1764 if (OK == dev->getMasterVolume(&mv)) {
1765 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001766 }
1767
1768 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001769 bool mm;
1770 if (OK == dev->getMasterMute(&mm)) {
1771 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001772 }
1773 }
1774
Eric Laurenta4c5a552012-03-29 10:12:40 -07001775 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001776 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001777 flags = static_cast<AudioHwDevice::Flags>(flags |
1778 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1779 }
1780
1781 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001782 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001783 flags = static_cast<AudioHwDevice::Flags>(flags |
1784 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1785 }
1786
Eric Laurenta4c5a552012-03-29 10:12:40 -07001787 mHardwareStatus = AUDIO_HW_IDLE;
1788 }
1789
Glenn Kastena13cde92016-03-28 15:26:02 -07001790 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001791 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001792
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001793 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001794
1795 return handle;
1796
1797}
1798
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001799// ----------------------------------------------------------------------------
1800
Glenn Kasten3b16c762012-11-14 08:44:39 -08001801uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001802{
1803 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001804 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001805 return thread != NULL ? thread->sampleRate() : 0;
1806}
1807
Glenn Kastene33054e2012-11-14 12:54:39 -08001808size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001809{
1810 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001811 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001812 return thread != NULL ? thread->frameCountHAL() : 0;
1813}
1814
1815// ----------------------------------------------------------------------------
1816
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001817status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1818{
1819 uid_t uid = IPCThreadState::self()->getCallingUid();
1820 if (uid != AID_SYSTEM) {
1821 return PERMISSION_DENIED;
1822 }
1823 Mutex::Autolock _l(mLock);
1824 if (mIsDeviceTypeKnown) {
1825 return INVALID_OPERATION;
1826 }
1827 mIsLowRamDevice = isLowRamDevice;
1828 mIsDeviceTypeKnown = true;
1829 return NO_ERROR;
1830}
1831
Eric Laurent93c3d412014-08-01 14:48:35 -07001832audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1833{
1834 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001835
1836 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1837 if (index >= 0) {
1838 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1839 mHwAvSyncIds.valueAt(index), sessionId);
1840 return mHwAvSyncIds.valueAt(index);
1841 }
1842
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001843 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001844 if (dev == NULL) {
1845 return AUDIO_HW_SYNC_INVALID;
1846 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001847 String8 reply;
1848 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001849 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001850 param = AudioParameter(reply);
1851 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001852
1853 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001854 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001855 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1856 return AUDIO_HW_SYNC_INVALID;
1857 }
1858
1859 // allow only one session for a given HW A/V sync ID.
1860 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1861 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1862 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1863 value, mHwAvSyncIds.keyAt(i));
1864 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001865 break;
1866 }
1867 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001868
1869 mHwAvSyncIds.add(sessionId, value);
1870
1871 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1872 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1873 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001874 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001875 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001876 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001877 thread->setParameters(param.toString());
1878 break;
1879 }
1880 }
1881
1882 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1883 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001884}
1885
Eric Laurent72e3f392015-05-20 14:43:50 -07001886status_t AudioFlinger::systemReady()
1887{
1888 Mutex::Autolock _l(mLock);
1889 ALOGI("%s", __FUNCTION__);
1890 if (mSystemReady) {
1891 ALOGW("%s called twice", __FUNCTION__);
1892 return NO_ERROR;
1893 }
1894 mSystemReady = true;
1895 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1896 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1897 thread->systemReady();
1898 }
1899 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1900 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1901 thread->systemReady();
1902 }
1903 return NO_ERROR;
1904}
1905
Eric Laurentfa90e842014-10-17 18:12:31 -07001906// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1907void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1908{
1909 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1910 if (index >= 0) {
1911 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1912 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1913 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001914 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001915 thread->setParameters(param.toString());
1916 }
1917}
1918
1919
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001920// ----------------------------------------------------------------------------
1921
Eric Laurent83b88082014-06-20 18:31:16 -07001922
Eric Laurent6acd1d42017-01-04 14:23:29 -08001923sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001924 audio_io_handle_t *output,
1925 audio_config_t *config,
1926 audio_devices_t devices,
1927 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001928 audio_output_flags_t flags)
1929{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001930 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001931 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001932 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001933 }
1934
Eric Laurentcf2c0212014-07-25 16:20:43 -07001935 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001936 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1937 } else {
1938 // Audio Policy does not currently request a specific output handle.
1939 // If this is ever needed, see openInput_l() for example code.
1940 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1941 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001942 }
Eric Laurent83b88082014-06-20 18:31:16 -07001943
1944 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1945
Eric Laurent83b88082014-06-20 18:31:16 -07001946 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001947 // This if statement allows overriding the audio policy settings
1948 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1949 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1950 // Check only for Normal Mixing mode
1951 if (kEnableExtendedPrecision) {
1952 // Specify format (uncomment one below to choose)
1953 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1954 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1955 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1956 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001957 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001958 }
1959 if (kEnableExtendedChannels) {
1960 // Specify channel mask (uncomment one below to choose)
1961 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1962 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1963 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1964 }
Eric Laurent83b88082014-06-20 18:31:16 -07001965 }
1966
Phil Burk062e67a2015-02-11 13:40:50 -08001967 AudioStreamOut *outputStream = NULL;
1968 status_t status = outHwDev->openOutputStream(
1969 &outputStream,
1970 *output,
1971 devices,
1972 flags,
1973 config,
1974 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001975
1976 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001977
Phil Burk062e67a2015-02-11 13:40:50 -08001978 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001979 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
1980 sp<MmapPlaybackThread> thread =
1981 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
1982 devices, AUDIO_DEVICE_NONE, mSystemReady);
1983 mMmapThreads.add(*output, thread);
1984 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
1985 *output, thread.get());
1986 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07001987 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001988 sp<PlaybackThread> thread;
1989 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1990 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
1991 ALOGV("openOutput_l() created offload output: ID %d thread %p",
1992 *output, thread.get());
1993 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1994 || !isValidPcmSinkFormat(config->format)
1995 || !isValidPcmSinkChannelMask(config->channel_mask)) {
1996 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
1997 ALOGV("openOutput_l() created direct output: ID %d thread %p",
1998 *output, thread.get());
1999 } else {
2000 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2001 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2002 *output, thread.get());
2003 }
2004 mPlaybackThreads.add(*output, thread);
2005 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002006 }
Eric Laurent83b88082014-06-20 18:31:16 -07002007 }
2008
2009 return 0;
2010}
2011
Eric Laurentcf2c0212014-07-25 16:20:43 -07002012status_t AudioFlinger::openOutput(audio_module_handle_t module,
2013 audio_io_handle_t *output,
2014 audio_config_t *config,
2015 audio_devices_t *devices,
2016 const String8& address,
2017 uint32_t *latencyMs,
2018 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002020 ALOGI("openOutput() this %p, module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
2021 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002022 (devices != NULL) ? *devices : 0,
2023 config->sample_rate,
2024 config->format,
2025 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002026 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002028 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002029 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002031
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 Mutex::Autolock _l(mLock);
2033
Eric Laurent6acd1d42017-01-04 14:23:29 -08002034 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002035 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002036 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2037 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2038 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039
Eric Laurent6acd1d42017-01-04 14:23:29 -08002040 // notify client processes of the new output creation
2041 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002042
Eric Laurent6acd1d42017-01-04 14:23:29 -08002043 // the first primary output opened designates the primary hw device
2044 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2045 ALOGI("Using module %d has the primary audio interface", module);
2046 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002047
Eric Laurent6acd1d42017-01-04 14:23:29 -08002048 AutoMutex lock(mHardwareLock);
2049 mHardwareStatus = AUDIO_HW_SET_MODE;
2050 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2051 mHardwareStatus = AUDIO_HW_IDLE;
2052 }
2053 } else {
2054 MmapThread *mmapThread = (MmapThread *)thread.get();
2055 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002056 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002057 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 }
2059
Eric Laurentcf2c0212014-07-25 16:20:43 -07002060 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061}
2062
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002063audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2064 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065{
2066 Mutex::Autolock _l(mLock);
2067 MixerThread *thread1 = checkMixerThread_l(output1);
2068 MixerThread *thread2 = checkMixerThread_l(output2);
2069
2070 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002071 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2072 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002073 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074 }
2075
Glenn Kasteneeecb982016-02-26 10:44:04 -08002076 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002077 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 thread->addOutputTrack(thread2);
2079 mPlaybackThreads.add(id, thread);
2080 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002081 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 return id;
2083}
2084
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002085status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086{
Glenn Kastend96c5722012-04-25 13:44:49 -07002087 return closeOutput_nonvirtual(output);
2088}
2089
2090status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2091{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 // keep strong reference on the playback thread so that
2093 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002094 sp<PlaybackThread> playbackThread;
2095 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 {
2097 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002098 playbackThread = checkPlaybackThread_l(output);
2099 if (playbackThread != NULL) {
2100 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101
Eric Laurent6acd1d42017-01-04 14:23:29 -08002102 if (playbackThread->type() == ThreadBase::MIXER) {
2103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2104 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2105 DuplicatingThread *dupThread =
2106 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2107 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2108 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 }
2110 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002111
2112
Eric Laurent6acd1d42017-01-04 14:23:29 -08002113 mPlaybackThreads.removeItem(output);
2114 // save all effects to the default thread
2115 if (mPlaybackThreads.size()) {
2116 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2117 if (dstThread != NULL) {
2118 // audioflinger lock is held here so the acquisition order of thread locks does not
2119 // matter
2120 Mutex::Autolock _dl(dstThread->mLock);
2121 Mutex::Autolock _sl(playbackThread->mLock);
2122 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2123 for (size_t i = 0; i < effectChains.size(); i ++) {
2124 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(), dstThread, true);
2125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 }
2127 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002128 } else {
2129 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2130 if (mmapThread == 0) {
2131 return BAD_VALUE;
2132 }
2133 mMmapThreads.removeItem(output);
2134 ALOGV("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002136 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2137 ioDesc->mIoHandle = output;
2138 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002140 // The thread entity (active unit of execution) is no longer running here,
2141 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142
Eric Laurent6acd1d42017-01-04 14:23:29 -08002143 if (playbackThread != 0) {
2144 playbackThread->exit();
2145 if (!playbackThread->isDuplicating()) {
2146 closeOutputFinish(playbackThread);
2147 }
2148 } else if (mmapThread != 0) {
2149 ALOGV("mmapThread exit()");
2150 mmapThread->exit();
2151 AudioStreamOut *out = mmapThread->clearOutput();
2152 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2153 // from now on thread->mOutput is NULL
2154 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 }
2156 return NO_ERROR;
2157}
2158
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002159void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002160{
2161 AudioStreamOut *out = thread->clearOutput();
2162 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2163 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002164 delete out;
2165}
2166
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002167void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002168{
2169 mPlaybackThreads.removeItem(thread->mId);
2170 thread->exit();
2171 closeOutputFinish(thread);
2172}
2173
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002174status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175{
2176 Mutex::Autolock _l(mLock);
2177 PlaybackThread *thread = checkPlaybackThread_l(output);
2178
2179 if (thread == NULL) {
2180 return BAD_VALUE;
2181 }
2182
Steve Block3856b092011-10-20 11:56:00 +01002183 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 thread->suspend();
2185
2186 return NO_ERROR;
2187}
2188
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002189status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190{
2191 Mutex::Autolock _l(mLock);
2192 PlaybackThread *thread = checkPlaybackThread_l(output);
2193
2194 if (thread == NULL) {
2195 return BAD_VALUE;
2196 }
2197
Steve Block3856b092011-10-20 11:56:00 +01002198 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199
2200 thread->restore();
2201
2202 return NO_ERROR;
2203}
2204
Eric Laurentcf2c0212014-07-25 16:20:43 -07002205status_t AudioFlinger::openInput(audio_module_handle_t module,
2206 audio_io_handle_t *input,
2207 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002208 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002209 const String8& address,
2210 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002211 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212{
Eric Laurent83b88082014-06-20 18:31:16 -07002213 Mutex::Autolock _l(mLock);
2214
Glenn Kastene7d66712015-03-05 13:46:52 -08002215 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002216 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002217 }
2218
Eric Laurent6acd1d42017-01-04 14:23:29 -08002219 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002220
2221 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002222 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002223 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002224 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002226 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002227}
Dima Zavin799a70e2011-04-18 16:57:27 -07002228
Eric Laurent6acd1d42017-01-04 14:23:29 -08002229sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002230 audio_io_handle_t *input,
2231 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002232 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002233 const String8& address,
2234 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002235 audio_input_flags_t flags)
2236{
Glenn Kastene7d66712015-03-05 13:46:52 -08002237 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002238 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002239 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002240 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002241 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002242
Glenn Kasteneeecb982016-02-26 10:44:04 -08002243 // Audio Policy can request a specific handle for hardware hotword.
2244 // The goal here is not to re-open an already opened input.
2245 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002246 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002247 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2248 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2249 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2250 return 0;
2251 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2252 // This should not happen in a transient state with current design.
2253 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2254 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002255 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002256
Eric Laurentcf2c0212014-07-25 16:20:43 -07002257 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002258 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002259 sp<StreamInHalInterface> inStream;
2260 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002261 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002262 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002263 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002264 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002265 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002266 halconfig.sample_rate,
2267 halconfig.format,
2268 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002269 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002270 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002272 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002273 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002274 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002275 audio_is_linear_pcm(config->format) &&
2276 audio_is_linear_pcm(halconfig.format) &&
2277 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002278 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2279 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002280 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002281 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002282 inStream.clear();
2283 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002284 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002285 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 }
2287
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002288 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002289 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002290 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2291 sp<MmapCaptureThread> thread =
2292 new MmapCaptureThread(this, *input,
2293 inHwDev, inputStream,
2294 primaryOutputDevice_l(), devices, mSystemReady);
2295 mMmapThreads.add(*input, thread);
2296 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input, thread.get());
2297 return thread;
2298 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002299#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002300 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2301 // or (re-)create if current Pipe is idle and does not match the new format
2302 sp<NBAIO_Sink> teeSink;
2303 enum {
2304 TEE_SINK_NO, // don't copy input
2305 TEE_SINK_NEW, // copy input using a new pipe
2306 TEE_SINK_OLD, // copy input using an existing pipe
2307 } kind;
2308 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2309 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2310 if (!mTeeSinkInputEnabled) {
2311 kind = TEE_SINK_NO;
2312 } else if (!Format_isValid(format)) {
2313 kind = TEE_SINK_NO;
2314 } else if (mRecordTeeSink == 0) {
2315 kind = TEE_SINK_NEW;
2316 } else if (mRecordTeeSink->getStrongCount() != 1) {
2317 kind = TEE_SINK_NO;
2318 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2319 kind = TEE_SINK_OLD;
2320 } else {
2321 kind = TEE_SINK_NEW;
2322 }
2323 switch (kind) {
2324 case TEE_SINK_NEW: {
2325 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2326 size_t numCounterOffers = 0;
2327 const NBAIO_Format offers[1] = {format};
2328 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2329 ALOG_ASSERT(index == 0);
2330 PipeReader *pipeReader = new PipeReader(*pipe);
2331 numCounterOffers = 0;
2332 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2333 ALOG_ASSERT(index == 0);
2334 mRecordTeeSink = pipe;
2335 mRecordTeeSource = pipeReader;
2336 teeSink = pipe;
2337 }
2338 break;
2339 case TEE_SINK_OLD:
2340 teeSink = mRecordTeeSink;
2341 break;
2342 case TEE_SINK_NO:
2343 default:
2344 break;
2345 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002346#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002347
2348 // Start record thread
2349 // RecordThread requires both input and output device indication to forward to audio
2350 // pre processing modules
2351 sp<RecordThread> thread = new RecordThread(this,
2352 inputStream,
2353 *input,
2354 primaryOutputDevice_l(),
2355 devices,
2356 mSystemReady
2357#ifdef TEE_SINK
2358 , teeSink
2359#endif
2360 );
2361 mRecordThreads.add(*input, thread);
2362 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2363 return thread;
2364 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 }
2366
Eric Laurentcf2c0212014-07-25 16:20:43 -07002367 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 return 0;
2369}
2370
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002371status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372{
Glenn Kastend96c5722012-04-25 13:44:49 -07002373 return closeInput_nonvirtual(input);
2374}
2375
2376status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2377{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 // keep strong reference on the record thread so that
2379 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002380 sp<RecordThread> recordThread;
2381 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 {
2383 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002384 recordThread = checkRecordThread_l(input);
2385 if (recordThread != 0) {
2386 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387
Eric Laurent6acd1d42017-01-04 14:23:29 -08002388 // If we still have effect chains, it means that a client still holds a handle
2389 // on at least one effect. We must either move the chain to an existing thread with the
2390 // same session ID or put it aside in case a new record thread is opened for a
2391 // new capture on the same session
2392 sp<EffectChain> chain;
2393 {
2394 Mutex::Autolock _sl(recordThread->mLock);
2395 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2396 // Note: maximum one chain per record thread
2397 if (effectChains.size() != 0) {
2398 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002399 }
2400 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002401 if (chain != 0) {
2402 // first check if a record thread is already opened with a client on the same session.
2403 // This should only happen in case of overlap between one thread tear down and the
2404 // creation of its replacement
2405 size_t i;
2406 for (i = 0; i < mRecordThreads.size(); i++) {
2407 sp<RecordThread> t = mRecordThreads.valueAt(i);
2408 if (t == recordThread) {
2409 continue;
2410 }
2411 if (t->hasAudioSession(chain->sessionId()) != 0) {
2412 Mutex::Autolock _l(t->mLock);
2413 ALOGV("closeInput() found thread %d for effect session %d",
2414 t->id(), chain->sessionId());
2415 t->addEffectChain_l(chain);
2416 break;
2417 }
2418 }
2419 // put the chain aside if we could not find a record thread with the same session id.
2420 if (i == mRecordThreads.size()) {
2421 putOrphanEffectChain_l(chain);
2422 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002423 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002424 mRecordThreads.removeItem(input);
2425 } else {
2426 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2427 if (mmapThread == 0) {
2428 return BAD_VALUE;
2429 }
2430 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002431 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002432 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2433 ioDesc->mIoHandle = input;
2434 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
Eric Laurent83b88082014-06-20 18:31:16 -07002436 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2437 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002438 if (recordThread != 0) {
2439 closeInputFinish(recordThread);
2440 } else if (mmapThread != 0) {
2441 mmapThread->exit();
2442 AudioStreamIn *in = mmapThread->clearInput();
2443 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2444 // from now on thread->mInput is NULL
2445 delete in;
2446 }
Eric Laurent83b88082014-06-20 18:31:16 -07002447 return NO_ERROR;
2448}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002450void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002451{
2452 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002453 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002454 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002455 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002456 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002457}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002459void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002460{
2461 mRecordThreads.removeItem(thread->mId);
2462 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463}
2464
Glenn Kastend2304db2014-02-03 07:40:31 -08002465status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466{
2467 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002468 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469
2470 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2471 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002472 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002473 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002474 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2475 mMmapThreads[i]->invalidateTracks(stream);
2476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 return NO_ERROR;
2478}
2479
2480
Glenn Kasteneeecb982016-02-26 10:44:04 -08002481audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482{
Glenn Kasten9d003132016-04-06 14:38:09 -07002483 // This is a binder API, so a malicious client could pass in a bad parameter.
2484 // Check for that before calling the internal API nextUniqueId().
2485 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2486 ALOGE("newAudioUniqueId invalid use %d", use);
2487 return AUDIO_UNIQUE_ID_ALLOCATE;
2488 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002489 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490}
2491
Glenn Kastend848eb42016-03-08 13:42:11 -08002492void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002493{
2494 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002495 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002496 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2497 if (pid != -1 && (caller == getpid_cached)) {
2498 caller = pid;
2499 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002500
Eric Laurent021cf962014-05-13 10:18:14 -07002501 {
2502 Mutex::Autolock _cl(mClientLock);
2503 // Ignore requests received from processes not known as notification client. The request
2504 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2505 // called from a different pid leaving a stale session reference. Also we don't know how
2506 // to clear this reference if the client process dies.
2507 if (mNotificationClients.indexOfKey(caller) < 0) {
2508 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2509 return;
2510 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002511 }
2512
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002513 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002514 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002515 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002516 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2517 ref->mCnt++;
2518 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002519 return;
2520 }
2521 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002522 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2523 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002524}
2525
Glenn Kastend848eb42016-03-08 13:42:11 -08002526void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002527{
2528 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002529 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002530 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2531 if (pid != -1 && (caller == getpid_cached)) {
2532 caller = pid;
2533 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002534 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002535 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002536 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002537 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2538 ref->mCnt--;
2539 ALOGV(" decremented refcount to %d", ref->mCnt);
2540 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002541 mAudioSessionRefs.removeAt(i);
2542 delete ref;
2543 purgeStaleEffects_l();
2544 }
2545 return;
2546 }
2547 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002548 // If the caller is mediaserver it is likely that the session being released was acquired
2549 // on behalf of a process not in notification clients and we ignore the warning.
2550 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002551}
2552
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002553bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2554{
2555 size_t num = mAudioSessionRefs.size();
2556 for (size_t i = 0; i < num; i++) {
2557 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2558 if (ref->mSessionid == audioSession) {
2559 return true;
2560 }
2561 }
2562 return false;
2563}
2564
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002565void AudioFlinger::purgeStaleEffects_l() {
2566
Steve Block3856b092011-10-20 11:56:00 +01002567 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002568
2569 Vector< sp<EffectChain> > chains;
2570
2571 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2572 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2573 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2574 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002575 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2576 chains.push(ec);
2577 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002578 }
2579 }
2580 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2581 sp<RecordThread> t = mRecordThreads.valueAt(i);
2582 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2583 sp<EffectChain> ec = t->mEffectChains[j];
2584 chains.push(ec);
2585 }
2586 }
2587
2588 for (size_t i = 0; i < chains.size(); i++) {
2589 sp<EffectChain> ec = chains[i];
2590 int sessionid = ec->sessionId();
2591 sp<ThreadBase> t = ec->mThread.promote();
2592 if (t == 0) {
2593 continue;
2594 }
2595 size_t numsessionrefs = mAudioSessionRefs.size();
2596 bool found = false;
2597 for (size_t k = 0; k < numsessionrefs; k++) {
2598 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002599 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002600 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002601 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002602 found = true;
2603 break;
2604 }
2605 }
2606 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002607 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002608 // remove all effects from the chain
2609 while (ec->mEffects.size()) {
2610 sp<EffectModule> effect = ec->mEffects[0];
2611 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002612 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002613 if (effect->purgeHandles()) {
2614 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002615 }
2616 AudioSystem::unregisterEffect(effect->id());
2617 }
2618 }
2619 }
2620 return;
2621}
2622
Glenn Kasteneeecb982016-02-26 10:44:04 -08002623// checkThread_l() must be called with AudioFlinger::mLock held
2624AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2625{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002626 ThreadBase *thread = checkMmapThread_l(ioHandle);
2627 if (thread == 0) {
2628 switch (audio_unique_id_get_use(ioHandle)) {
2629 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2630 thread = checkPlaybackThread_l(ioHandle);
2631 break;
2632 case AUDIO_UNIQUE_ID_USE_INPUT:
2633 thread = checkRecordThread_l(ioHandle);
2634 break;
2635 default:
2636 break;
2637 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002638 }
2639 return thread;
2640}
2641
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002643AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644{
Glenn Kastena1117922012-01-26 10:53:32 -08002645 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646}
2647
2648// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002649AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650{
2651 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002652 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653}
2654
2655// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002656AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657{
Glenn Kastena1117922012-01-26 10:53:32 -08002658 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659}
2660
Eric Laurent6acd1d42017-01-04 14:23:29 -08002661// checkMmapThread_l() must be called with AudioFlinger::mLock held
2662AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2663{
2664 return mMmapThreads.valueFor(io).get();
2665}
2666
2667
2668// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2669AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2670{
2671 VolumeInterface *volumeInterface = (VolumeInterface *)mPlaybackThreads.valueFor(output).get();
2672 if (volumeInterface == nullptr) {
2673 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2674 if (mmapThread != nullptr) {
2675 if (mmapThread->isOutput()) {
2676 volumeInterface = (VolumeInterface *)mmapThread;
2677 }
2678 }
2679 }
2680 return volumeInterface;
2681}
2682
2683Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2684{
2685 Vector <VolumeInterface *> volumeInterfaces;
2686 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2687 volumeInterfaces.add((VolumeInterface *)mPlaybackThreads.valueAt(i).get());
2688 }
2689 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2690 if (mMmapThreads.valueAt(i)->isOutput()) {
2691 volumeInterfaces.add((VolumeInterface *)mMmapThreads.valueAt(i).get());
2692 }
2693 }
2694 return volumeInterfaces;
2695}
2696
Glenn Kasteneeecb982016-02-26 10:44:04 -08002697audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698{
Glenn Kasten9d003132016-04-06 14:38:09 -07002699 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002700 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002701 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2702 for (int retry = 0; retry < maxRetries; retry++) {
2703 // The cast allows wraparound from max positive to min negative instead of abort
2704 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2705 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2706 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2707 // allow wrap by skipping 0 and -1 for session ids
2708 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2709 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2710 return (audio_unique_id_t) (base | use);
2711 }
2712 }
2713 // We have no way of recovering from wraparound
2714 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2715 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716}
2717
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002718AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002719{
2720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2721 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002722 if(thread->isDuplicating()) {
2723 continue;
2724 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002725 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002726 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002727 return thread;
2728 }
2729 }
2730 return NULL;
2731}
2732
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002733audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002734{
2735 PlaybackThread *thread = primaryPlaybackThread_l();
2736
2737 if (thread == NULL) {
2738 return 0;
2739 }
2740
Eric Laurentf1c04f92012-08-28 14:26:53 -07002741 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002742}
2743
Glenn Kastena7335632016-06-09 17:09:53 -07002744AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2745{
2746 size_t minFrameCount = 0;
2747 PlaybackThread *minThread = NULL;
2748 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2749 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2750 if (!thread->isDuplicating()) {
2751 size_t frameCount = thread->frameCountHAL();
2752 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2753 (frameCount == minFrameCount && thread->hasFastMixer() &&
2754 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2755 minFrameCount = frameCount;
2756 minThread = thread;
2757 }
2758 }
2759 }
2760 return minThread;
2761}
2762
Eric Laurenta011e352012-03-29 15:51:43 -07002763sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002764 audio_session_t triggerSession,
2765 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002766 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002767 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002768{
2769 Mutex::Autolock _l(mLock);
2770
2771 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2772 status_t playStatus = NAME_NOT_FOUND;
2773 status_t recStatus = NAME_NOT_FOUND;
2774 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2775 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2776 if (playStatus == NO_ERROR) {
2777 return event;
2778 }
2779 }
2780 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2781 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2782 if (recStatus == NO_ERROR) {
2783 return event;
2784 }
2785 }
2786 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2787 mPendingSyncEvents.add(event);
2788 } else {
2789 ALOGV("createSyncEvent() invalid event %d", event->type());
2790 event.clear();
2791 }
2792 return event;
2793}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002794
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795// ----------------------------------------------------------------------------
2796// Effect management
2797// ----------------------------------------------------------------------------
2798
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002799sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2800 return mEffectsFactoryHal;
2801}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802
Glenn Kastenf587ba52012-01-26 16:25:10 -08002803status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804{
2805 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002806 if (mEffectsFactoryHal.get()) {
2807 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2808 } else {
2809 return -ENODEV;
2810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811}
2812
Glenn Kastenf587ba52012-01-26 16:25:10 -08002813status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814{
2815 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002816 if (mEffectsFactoryHal.get()) {
2817 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2818 } else {
2819 return -ENODEV;
2820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821}
2822
Glenn Kasten5e92a782012-01-30 07:40:52 -08002823status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002824 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825{
2826 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002827 if (mEffectsFactoryHal.get()) {
2828 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2829 } else {
2830 return -ENODEV;
2831 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832}
2833
2834
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002835sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 effect_descriptor_t *pDesc,
2837 const sp<IEffectClient>& effectClient,
2838 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002839 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002841 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002842 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843 status_t *status,
2844 int *id,
2845 int *enabled)
2846{
2847 status_t lStatus = NO_ERROR;
2848 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850
Eric Laurentb6436272016-12-07 19:24:50 -08002851 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2852 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2853 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2854 ALOGW_IF(pid != -1 && pid != callingPid,
2855 "%s uid %d pid %d tried to pass itself off as pid %d",
2856 __func__, callingUid, callingPid, pid);
2857 pid = callingPid;
2858 }
2859
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002860 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2861 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862
2863 if (pDesc == NULL) {
2864 lStatus = BAD_VALUE;
2865 goto Exit;
2866 }
2867
Eric Laurent84e9a102010-09-23 16:10:16 -07002868 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002869 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002870 lStatus = PERMISSION_DENIED;
2871 goto Exit;
2872 }
2873
Dima Zavinfce7a472011-04-19 22:30:36 -07002874 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002875 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002876 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002877 lStatus = PERMISSION_DENIED;
2878 goto Exit;
2879 }
2880
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002881 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002882 lStatus = NO_INIT;
2883 goto Exit;
2884 }
2885
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002887 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002889 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002891 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 goto Exit;
2893 }
2894 } else {
2895 // if uuid is not specified, look for an available implementation
2896 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002897 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002898 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899 lStatus = BAD_VALUE;
2900 goto Exit;
2901 }
2902 uint32_t numEffects = 0;
2903 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002904 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 bool found = false;
2906
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002907 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002909 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 goto Exit;
2911 }
2912 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002913 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002915 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916 continue;
2917 }
2918 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2919 // If matching type found save effect descriptor. If the session is
2920 // 0 and the effect is not auxiliary, continue enumeration in case
2921 // an auxiliary version of this effect type is available
2922 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002923 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002924 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2926 break;
2927 }
2928 }
2929 }
2930 if (!found) {
2931 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002932 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 goto Exit;
2934 }
2935 // For same effect type, chose auxiliary version over insert version if
2936 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002937 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002939 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 }
2941 }
2942
2943 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2946 lStatus = INVALID_OPERATION;
2947 goto Exit;
2948 }
2949
Eric Laurent59255e42011-07-27 19:49:51 -07002950 // check recording permission for visualizer
2951 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002952 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002953 lStatus = PERMISSION_DENIED;
2954 goto Exit;
2955 }
2956
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002958 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002959 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002960 // if the output returned by getOutputForEffect() is removed before we lock the
2961 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2962 // and we will exit safely
2963 io = AudioSystem::getOutputForEffect(&desc);
2964 ALOGV("createEffect got output %d", io);
2965 }
2966
2967 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968
2969 // If output is not specified try to find a matching audio session ID in one of the
2970 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002971 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2972 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002973 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002974 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002975 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2976 // output must be specified by AudioPolicyManager when using session
2977 // AUDIO_SESSION_OUTPUT_STAGE
2978 lStatus = BAD_VALUE;
2979 goto Exit;
2980 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002981 // look for the thread where the specified audio session is present
2982 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2983 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2984 io = mPlaybackThreads.keyAt(i);
2985 break;
2986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002988 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002989 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2990 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2991 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002992 break;
2993 }
2994 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002995 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002996 if (io == AUDIO_IO_HANDLE_NONE) {
2997 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2998 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2999 io = mMmapThreads.keyAt(i);
3000 break;
3001 }
3002 }
3003 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003004 // If no output thread contains the requested session ID, default to
3005 // first output. The effect chain will be moved to the correct output
3006 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003007 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003008 io = mPlaybackThreads.keyAt(0);
3009 }
Steve Block3856b092011-10-20 11:56:00 +01003010 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003011 }
3012 ThreadBase *thread = checkRecordThread_l(io);
3013 if (thread == NULL) {
3014 thread = checkPlaybackThread_l(io);
3015 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003016 thread = checkMmapThread_l(io);
3017 if (thread == NULL) {
3018 ALOGE("createEffect() unknown output thread");
3019 lStatus = BAD_VALUE;
3020 goto Exit;
3021 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003022 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003023 } else {
3024 // Check if one effect chain was awaiting for an effect to be created on this
3025 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003026 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003027 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003028 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003029 thread->addEffectChain_l(chain);
3030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003032
Eric Laurent021cf962014-05-13 10:18:14 -07003033 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003035 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003036 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003037 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003038 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 if (handle != 0 && id != NULL) {
3040 *id = handle->id();
3041 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003042 if (handle == 0) {
3043 // remove local strong reference to Client with mClientLock held
3044 Mutex::Autolock _cl(mClientLock);
3045 client.clear();
3046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 }
3048
3049Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003050 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 return handle;
3052}
3053
Glenn Kastend848eb42016-03-08 13:42:11 -08003054status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003055 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003056{
Steve Block3856b092011-10-20 11:56:00 +01003057 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003058 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003059 Mutex::Autolock _l(mLock);
3060 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003061 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003062 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 }
Eric Laurentde070132010-07-13 04:45:46 -07003064 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3065 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003066 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003067 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068 }
Eric Laurentde070132010-07-13 04:45:46 -07003069 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3070 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003071 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003072 return BAD_VALUE;
3073 }
3074
3075 Mutex::Autolock _dl(dstThread->mLock);
3076 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003077 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078}
3079
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003080// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003081status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003082 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003083 AudioFlinger::PlaybackThread *dstThread,
3084 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003085{
Steve Block3856b092011-10-20 11:56:00 +01003086 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003087 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003088
Eric Laurent59255e42011-07-27 19:49:51 -07003089 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003090 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003091 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003092 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003093 return INVALID_OPERATION;
3094 }
3095
Eric Laurent4c415062016-06-17 16:14:16 -07003096 // Check whether the destination thread and all effects in the chain are compatible
3097 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003098 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003099 " destination thread %p is not compatible with effects in the chain",
3100 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003101 return INVALID_OPERATION;
3102 }
3103
Eric Laurent39e94f82010-07-28 01:32:47 -07003104 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003105 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003106 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003107 // removed.
3108 srcThread->removeEffectChain_l(chain);
3109
3110 // transfer all effects one by one so that new effect chain is created on new thread with
3111 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003112 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003113 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003114 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003115 Vector< sp<EffectModule> > removed;
3116 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003117 while (effect != 0) {
3118 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003119 removed.add(effect);
3120 status = dstThread->addEffect_l(effect);
3121 if (status != NO_ERROR) {
3122 break;
3123 }
Eric Laurentec35a142011-10-05 17:42:25 -07003124 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3125 if (effect->state() == EffectModule::ACTIVE ||
3126 effect->state() == EffectModule::STOPPING) {
3127 effect->start();
3128 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003129 // if the move request is not received from audio policy manager, the effect must be
3130 // re-registered with the new strategy and output
3131 if (dstChain == 0) {
3132 dstChain = effect->chain().promote();
3133 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003134 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003135 status = NO_INIT;
3136 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003137 }
3138 strategy = dstChain->strategy();
3139 }
3140 if (reRegister) {
3141 AudioSystem::unregisterEffect(effect->id());
3142 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003143 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003144 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003145 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003146 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003147 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003148 }
Eric Laurentde070132010-07-13 04:45:46 -07003149 effect = chain->getEffectFromId_l(0);
3150 }
3151
Eric Laurent5baf2af2013-09-12 17:37:00 -07003152 if (status != NO_ERROR) {
3153 for (size_t i = 0; i < removed.size(); i++) {
3154 srcThread->addEffect_l(removed[i]);
3155 if (dstChain != 0 && reRegister) {
3156 AudioSystem::unregisterEffect(removed[i]->id());
3157 AudioSystem::registerEffect(&removed[i]->desc(),
3158 srcThread->id(),
3159 strategy,
3160 sessionId,
3161 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003162 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003163 }
3164 }
3165 }
3166
3167 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168}
3169
Eric Laurent5baf2af2013-09-12 17:37:00 -07003170bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003171{
3172 if (mGlobalEffectEnableTime != 0 &&
3173 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3174 return true;
3175 }
3176
3177 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3178 sp<EffectChain> ec =
3179 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003180 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003181 return true;
3182 }
3183 }
3184 return false;
3185}
3186
Eric Laurent5baf2af2013-09-12 17:37:00 -07003187void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003188{
3189 Mutex::Autolock _l(mLock);
3190
3191 mGlobalEffectEnableTime = systemTime();
3192
3193 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3194 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3195 if (t->mType == ThreadBase::OFFLOAD) {
3196 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3197 }
3198 }
3199
3200}
3201
Eric Laurentaaa44472014-09-12 17:41:50 -07003202status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3203{
Glenn Kastend848eb42016-03-08 13:42:11 -08003204 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003205 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003206 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003207 if (index >= 0) {
3208 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3209 return ALREADY_EXISTS;
3210 }
3211 mOrphanEffectChains.add(session, chain);
3212 return NO_ERROR;
3213}
3214
3215sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3216{
3217 sp<EffectChain> chain;
3218 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003219 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003220 if (index >= 0) {
3221 chain = mOrphanEffectChains.valueAt(index);
3222 mOrphanEffectChains.removeItemsAt(index);
3223 }
3224 return chain;
3225}
3226
3227bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3228{
3229 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003230 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003231 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003232 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003233 if (index >= 0) {
3234 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003235 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003236 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003237 mOrphanEffectChains.removeItemsAt(index);
3238 }
3239 return true;
3240 }
3241 return false;
3242}
3243
3244
Glenn Kastenda6ef132013-01-10 12:31:01 -08003245struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003246#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3247 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003248};
3249
3250int comparEntry(const void *p1, const void *p2)
3251{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003252 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003253}
3254
Glenn Kasten46909e72013-02-26 09:20:22 -08003255#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003256void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257{
Eric Laurent81784c32012-11-19 14:55:58 -08003258 NBAIO_Source *teeSource = source.get();
3259 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003260 // .wav rotation
3261 // There is a benign race condition if 2 threads call this simultaneously.
3262 // They would both traverse the directory, but the result would simply be
3263 // failures at unlink() which are ignored. It's also unlikely since
3264 // normally dumpsys is only done by bugreport or from the command line.
3265 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003266 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003267 size_t teePathLen = strlen(teePath);
3268 DIR *dir = opendir(teePath);
3269 teePath[teePathLen++] = '/';
3270 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003271#define TEE_MAX_SORT 20 // number of entries to sort
3272#define TEE_MAX_KEEP 10 // number of entries to keep
3273 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003274 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003275 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003276 struct dirent de;
3277 struct dirent *result = NULL;
3278 int rc = readdir_r(dir, &de, &result);
3279 if (rc != 0) {
3280 ALOGW("readdir_r failed %d", rc);
3281 break;
3282 }
3283 if (result == NULL) {
3284 break;
3285 }
3286 if (result != &de) {
3287 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3288 break;
3289 }
3290 // ignore non .wav file entries
3291 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003292 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003293 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3294 continue;
3295 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003296 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003297 }
3298 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003299 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003300 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003301 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3302 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003303 (void) unlink(teePath);
3304 }
3305 }
3306 } else {
3307 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003308 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003309 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003310 }
3311 }
Eric Laurent81784c32012-11-19 14:55:58 -08003312 char teeTime[16];
3313 struct timeval tv;
3314 gettimeofday(&tv, NULL);
3315 struct tm tm;
3316 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003317 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3318 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3319 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3320 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003321 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003322 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003323 char wavHeader[44];
3324 memcpy(wavHeader,
3325 "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",
3326 sizeof(wavHeader));
3327 NBAIO_Format format = teeSource->format();
3328 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003329 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003330 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003331 wavHeader[22] = channelCount; // number of channels
3332 wavHeader[24] = sampleRate; // sample rate
3333 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003334 wavHeader[32] = frameSize; // block alignment
3335 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003336 write(teeFd, wavHeader, sizeof(wavHeader));
3337 size_t total = 0;
3338 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003339#define TEE_SINK_READ 1024 // frames per I/O operation
3340 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003341 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003342 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003343 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003344 bool wasFirstRead = firstRead;
3345 firstRead = false;
3346 if (actual <= 0) {
3347 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3348 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003349 }
Eric Laurent81784c32012-11-19 14:55:58 -08003350 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003351 }
Eric Laurent81784c32012-11-19 14:55:58 -08003352 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003353 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003354 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003355 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003356 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003357 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003358 uint32_t temp = 44 + total * frameSize - 8;
3359 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003360 write(teeFd, &temp, sizeof(temp));
3361 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003362 temp = total * frameSize;
3363 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003364 write(teeFd, &temp, sizeof(temp));
3365 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003366 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003367 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003368 }
Eric Laurent59255e42011-07-27 19:49:51 -07003369 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003370 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003371 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003372 }
Eric Laurent59255e42011-07-27 19:49:51 -07003373 }
3374 }
3375}
Glenn Kasten46909e72013-02-26 09:20:22 -08003376#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003377
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378// ----------------------------------------------------------------------------
3379
3380status_t AudioFlinger::onTransact(
3381 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3382{
3383 return BnAudioFlinger::onTransact(code, data, reply, flags);
3384}
3385
Glenn Kasten63238ef2015-03-02 15:50:29 -08003386} // namespace android