blob: f875d0f4e421239e6db306ba1efc6574c8ae8285 [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
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Mathias Agopian65ab4712010-07-14 17:59:35 -070074// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
John Grossman1c345192012-03-27 14:00:17 -070076// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
Eric Laurentde070132010-07-13 04:45:46 -070088
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Glenn Kastenec1d6b52011-12-12 09:04:45 -080091static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
92static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070093static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070094static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten58912562012-04-03 10:45:00 -070096
John Grossman4ff14ba2012-02-08 16:37:41 -080097nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700100
Eric Laurentfc235202016-12-20 18:48:17 -0800101
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103bool AudioFlinger::mTeeSinkInputEnabled = false;
104bool AudioFlinger::mTeeSinkOutputEnabled = false;
105bool AudioFlinger::mTeeSinkTrackEnabled = false;
106
107size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
108size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
109size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800110#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800111
Eric Laurent813e2a72013-08-31 12:59:48 -0700112// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
113// we define a minimum time during which a global effect is considered enabled.
114static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
115
Eric Laurentfc235202016-12-20 18:48:17 -0800116Mutex gLock;
117wp<AudioFlinger> gAudioFlinger;
118
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119// ----------------------------------------------------------------------------
120
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700121std::string formatToString(audio_format_t format) {
122 std::string result;
123 FormatConverter::toString(format, result);
124 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800125}
126
Mathias Agopian65ab4712010-07-14 17:59:35 -0700127// ----------------------------------------------------------------------------
128
129AudioFlinger::AudioFlinger()
130 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800131 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800132 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700133 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800134 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800135 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700136 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800137 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700138 mBtNrecIsOff(false),
139 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700140 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700141 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700142 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700143{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700144 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
145 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
146 // zero ID has a special meaning, so unavailable
147 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
148 }
149
Glenn Kasten949a9262013-04-16 12:35:20 -0700150 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800151 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800152 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800153 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
154 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800155 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700156
Wei Jia3f273d12015-11-24 09:06:49 -0800157 // reset battery stats.
158 // if the audio service has crashed, battery stats could be left
159 // in bad state, reset the state upon service start.
160 BatteryNotifier::getInstance().noteResetAudio();
161
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700162 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700163 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
164
Glenn Kasten46909e72013-02-26 09:20:22 -0800165#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800166 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800167 (void) property_get("ro.debuggable", value, "0");
168 int debuggable = atoi(value);
169 int teeEnabled = 0;
170 if (debuggable) {
171 (void) property_get("af.tee", value, "0");
172 teeEnabled = atoi(value);
173 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800174 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700175 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800176 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700177 }
178 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800179 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700180 }
181 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800182 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700183 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800184#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700185}
186
187void AudioFlinger::onFirstRef()
188{
Eric Laurent93575202011-01-18 18:39:02 -0800189 Mutex::Autolock _l(mLock);
190
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800192 char val_str[PROPERTY_VALUE_MAX] = { 0 };
193 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
194 uint32_t int_val;
195 if (1 == sscanf(val_str, "%u", &int_val)) {
196 mStandbyTimeInNsecs = milliseconds(int_val);
197 ALOGI("Using %u mSec as standby time.", int_val);
198 } else {
199 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
200 ALOGI("Using default %u mSec as standby time.",
201 (uint32_t)(mStandbyTimeInNsecs / 1000000));
202 }
203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700204
Eric Laurent1c333e22014-05-20 10:48:17 -0700205 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700206
Eric Laurenta4c5a552012-03-29 10:12:40 -0700207 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800208
209 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210}
211
212AudioFlinger::~AudioFlinger()
213{
214 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700215 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700216 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217 }
218 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700219 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700220 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700222
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800223 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
224 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700225 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700227
228 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800229 if (mLogMemoryDealer != 0) {
230 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
231 if (binder != 0) {
232 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
233 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
234 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
235 mUnregisteredWriters.pop();
236 mediaLogService->unregisterWriter(iMemory);
237 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240}
241
Eric Laurentfc235202016-12-20 18:48:17 -0800242//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800243__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800244status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
245 const audio_attributes_t *attr,
246 audio_config_base_t *config,
247 const MmapStreamInterface::Client& client,
248 audio_port_handle_t *deviceId,
249 const sp<MmapStreamCallback>& callback,
250 sp<MmapStreamInterface>& interface)
251{
252 sp<AudioFlinger> af;
253 {
254 Mutex::Autolock _l(gLock);
255 af = gAudioFlinger.promote();
256 }
257 status_t ret = NO_INIT;
258 if (af != 0) {
259 ret = af->openMmapStream(
260 direction, attr, config, client, deviceId, callback, interface);
261 }
262 return ret;
263}
264
Eric Laurent6acd1d42017-01-04 14:23:29 -0800265status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
266 const audio_attributes_t *attr,
267 audio_config_base_t *config,
268 const MmapStreamInterface::Client& client,
269 audio_port_handle_t *deviceId,
270 const sp<MmapStreamCallback>& callback,
271 sp<MmapStreamInterface>& interface)
Eric Laurentfc235202016-12-20 18:48:17 -0800272{
273 status_t ret = initCheck();
274 if (ret != NO_ERROR) {
275 return ret;
276 }
277
Eric Laurent6acd1d42017-01-04 14:23:29 -0800278 audio_session_t sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
279 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
280 audio_io_handle_t io;
281 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
282 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
283 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
284 fullConfig.sample_rate = config->sample_rate;
285 fullConfig.channel_mask = config->channel_mask;
286 fullConfig.format = config->format;
287 ret = AudioSystem::getOutputForAttr(attr, &io,
288 sessionId,
289 &streamType, client.clientUid,
290 &fullConfig,
291 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT),
292 *deviceId, &portId);
293 } else {
294 ret = AudioSystem::getInputForAttr(attr, &io,
295 sessionId,
296 client.clientPid,
297 client.clientUid,
298 config,
299 AUDIO_INPUT_FLAG_MMAP_NOIRQ, *deviceId, &portId);
300 }
301 if (ret != NO_ERROR) {
302 return ret;
303 }
304
305 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
306 // audio policy manager and we can retrieve it
307 sp<MmapThread> thread = mMmapThreads.valueFor(io);
308 if (thread != 0) {
309 interface = new MmapThreadHandle(thread);
310 thread->configure(attr, streamType, sessionId, callback, portId);
311 } else {
312 ret = NO_INIT;
313 }
314
315 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
316
Eric Laurentfc235202016-12-20 18:48:17 -0800317 return ret;
318}
319
Eric Laurenta4c5a552012-03-29 10:12:40 -0700320static const char * const audio_interfaces[] = {
321 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
322 AUDIO_HARDWARE_MODULE_ID_A2DP,
323 AUDIO_HARDWARE_MODULE_ID_USB,
324};
325#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
326
Phil Burk062e67a2015-02-11 13:40:50 -0800327AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700328 audio_module_handle_t module,
329 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700330{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700331 // if module is 0, the request comes from an old policy manager and we should load
332 // well known modules
333 if (module == 0) {
334 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
335 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
336 loadHwModule_l(audio_interfaces[i]);
337 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700338 // then try to find a module supporting the requested device.
339 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
340 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700341 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
342 uint32_t supportedDevices;
343 if (dev->getSupportedDevices(&supportedDevices) == OK &&
344 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700345 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700346 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700347 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700348 } else {
349 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700350 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
351 if (audioHwDevice != NULL) {
352 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700353 }
354 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700355
Dima Zavin799a70e2011-04-18 16:57:27 -0700356 return NULL;
357}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700358
Glenn Kasten0f11b512014-01-31 16:18:54 -0800359void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360{
361 const size_t SIZE = 256;
362 char buffer[SIZE];
363 String8 result;
364
365 result.append("Clients:\n");
366 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800367 sp<Client> client = mClients.valueAt(i).promote();
368 if (client != 0) {
369 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
370 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700373
Eric Laurentd1b28d42013-09-18 18:47:13 -0700374 result.append("Notification Clients:\n");
375 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
376 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
377 result.append(buffer);
378 }
379
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700380 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800381 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700382 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
383 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800384 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700385 result.append(buffer);
386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388}
389
390
Glenn Kasten0f11b512014-01-31 16:18:54 -0800391void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392{
393 const size_t SIZE = 256;
394 char buffer[SIZE];
395 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800396 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397
John Grossman4ff14ba2012-02-08 16:37:41 -0800398 snprintf(buffer, SIZE, "Hardware status: %d\n"
399 "Standby Time mSec: %u\n",
400 hardwareStatus,
401 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 result.append(buffer);
403 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404}
405
Glenn Kasten0f11b512014-01-31 16:18:54 -0800406void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407{
408 const size_t SIZE = 256;
409 char buffer[SIZE];
410 String8 result;
411 snprintf(buffer, SIZE, "Permission Denial: "
412 "can't dump AudioFlinger from pid=%d, uid=%d\n",
413 IPCThreadState::self()->getCallingPid(),
414 IPCThreadState::self()->getCallingUid());
415 result.append(buffer);
416 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417}
418
Eric Laurent81784c32012-11-19 14:55:58 -0800419bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420{
421 bool locked = false;
422 for (int i = 0; i < kDumpLockRetries; ++i) {
423 if (mutex.tryLock() == NO_ERROR) {
424 locked = true;
425 break;
426 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800427 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428 }
429 return locked;
430}
431
432status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
433{
Glenn Kasten44deb052012-02-05 18:09:08 -0800434 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 dumpPermissionDenial(fd, args);
436 } else {
437 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800438 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 if (!hardwareLocked) {
440 String8 result(kHardwareLockedString);
441 write(fd, result.string(), result.size());
442 } else {
443 mHardwareLock.unlock();
444 }
445
Eric Laurent81784c32012-11-19 14:55:58 -0800446 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447
448 // failed to lock - AudioFlinger is probably deadlocked
449 if (!locked) {
450 String8 result(kDeadlockedString);
451 write(fd, result.string(), result.size());
452 }
453
Eric Laurent021cf962014-05-13 10:18:14 -0700454 bool clientLocked = dumpTryLock(mClientLock);
455 if (!clientLocked) {
456 String8 result(kClientLockedString);
457 write(fd, result.string(), result.size());
458 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700459
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700460 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700461 mEffectsFactoryHal->dumpEffects(fd);
462 } else {
463 String8 result(kNoEffectsFactory);
464 write(fd, result.string(), result.size());
465 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700466
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700468 if (clientLocked) {
469 mClientLock.unlock();
470 }
471
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 dumpInternals(fd, args);
473
474 // dump playback threads
475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
476 mPlaybackThreads.valueAt(i)->dump(fd, args);
477 }
478
479 // dump record threads
480 for (size_t i = 0; i < mRecordThreads.size(); i++) {
481 mRecordThreads.valueAt(i)->dump(fd, args);
482 }
483
Eric Laurent6acd1d42017-01-04 14:23:29 -0800484 // dump mmap threads
485 for (size_t i = 0; i < mMmapThreads.size(); i++) {
486 mMmapThreads.valueAt(i)->dump(fd, args);
487 }
488
Eric Laurentaaa44472014-09-12 17:41:50 -0700489 // dump orphan effect chains
490 if (mOrphanEffectChains.size() != 0) {
491 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
492 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
493 mOrphanEffectChains.valueAt(i)->dump(fd, args);
494 }
495 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700496 // dump all hardware devs
497 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700498 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
499 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700501
Glenn Kasten46909e72013-02-26 09:20:22 -0800502#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700503 // dump the serially shared record tee sink
504 if (mRecordTeeSource != 0) {
505 dumpTee(fd, mRecordTeeSource);
506 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800507#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700508
rago3bd1c872016-09-26 12:58:14 -0700509 BUFLOG_RESET;
510
Glenn Kastend65d73c2012-06-22 17:21:07 -0700511 if (locked) {
512 mLock.unlock();
513 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800514
515 // append a copy of media.log here by forwarding fd to it, but don't attempt
516 // to lookup the service if it's not running, as it will block for a second
517 if (mLogMemoryDealer != 0) {
518 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
519 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700520 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800521 Vector<String16> args;
522 binder->dump(fd, args);
523 }
524 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700525
526 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700527 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700528 bool unreachableMemory = false;
529 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700530 if (arg == String16("-m")) {
531 dumpMem = true;
532 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700533 unreachableMemory = true;
534 }
535 }
536
Andy Hung07b745e2016-05-23 16:21:07 -0700537 if (dumpMem) {
538 dprintf(fd, "\nDumping memory:\n");
539 std::string s = dumpMemoryAddresses(100 /* limit */);
540 write(fd, s.c_str(), s.size());
541 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700542 if (unreachableMemory) {
543 dprintf(fd, "\nDumping unreachable memory:\n");
544 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700545 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700546 write(fd, s.c_str(), s.size());
547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 }
549 return NO_ERROR;
550}
551
Eric Laurent021cf962014-05-13 10:18:14 -0700552sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800553{
Eric Laurent021cf962014-05-13 10:18:14 -0700554 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800555 // If pid is already in the mClients wp<> map, then use that entry
556 // (for which promote() is always != 0), otherwise create a new entry and Client.
557 sp<Client> client = mClients.valueFor(pid).promote();
558 if (client == 0) {
559 client = new Client(this, pid);
560 mClients.add(pid, client);
561 }
562
563 return client;
564}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565
Glenn Kasten9e58b552013-01-18 15:09:48 -0800566sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
567{
Glenn Kasten481fb672013-09-30 14:39:28 -0700568 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800569 if (mLogMemoryDealer == 0) {
570 return new NBLog::Writer();
571 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800572 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700573 // Similarly if we can't contact the media.log service, also return a dummy writer
574 if (binder == 0) {
575 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800576 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700577 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
578 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
579 // If allocation fails, consult the vector of previously unregistered writers
580 // and garbage-collect one or more them until an allocation succeeds
581 if (shared == 0) {
582 Mutex::Autolock _l(mUnregisteredWritersLock);
583 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
584 {
585 // Pick the oldest stale writer to garbage-collect
586 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
587 mUnregisteredWriters.removeAt(0);
588 mediaLogService->unregisterWriter(iMemory);
589 // Now the media.log remote reference to IMemory is gone. When our last local
590 // reference to IMemory also drops to zero at end of this block,
591 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
592 }
593 // Re-attempt the allocation
594 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
595 if (shared != 0) {
596 goto success;
597 }
598 }
599 // Even after garbage-collecting all old writers, there is still not enough memory,
600 // so return a dummy writer
601 return new NBLog::Writer();
602 }
603success:
604 mediaLogService->registerWriter(shared, size, name);
605 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800606}
607
608void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
609{
Glenn Kasten685ef092013-02-04 08:15:34 -0800610 if (writer == 0) {
611 return;
612 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800613 sp<IMemory> iMemory(writer->getIMemory());
614 if (iMemory == 0) {
615 return;
616 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700617 // Rather than removing the writer immediately, append it to a queue of old writers to
618 // be garbage-collected later. This allows us to continue to view old logs for a while.
619 Mutex::Autolock _l(mUnregisteredWritersLock);
620 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800621}
622
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623// IAudioFlinger interface
624
625
626sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800627 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800629 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700630 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800631 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700632 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800634 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700635 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800636 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800637 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800638 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800639 status_t *status,
640 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641{
642 sp<PlaybackThread::Track> track;
643 sp<TrackHandle> trackHandle;
644 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800646 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700648 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
649 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
650 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
651 ALOGW_IF(pid != -1 && pid != callingPid,
652 "%s uid %d pid %d tried to pass itself off as pid %d",
653 __func__, callingUid, callingPid, pid);
654 pid = callingPid;
655 }
656
Glenn Kasten263709e2012-01-06 08:40:01 -0800657 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
658 // but if someone uses binder directly they could bypass that and cause us to crash
659 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000660 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 lStatus = BAD_VALUE;
662 goto Exit;
663 }
664
Glenn Kasten53b5d092014-02-05 10:00:23 -0800665 // further sample rate checks are performed by createTrack_l() depending on the thread type
666 if (sampleRate == 0) {
667 ALOGE("createTrack() invalid sample rate %u", sampleRate);
668 lStatus = BAD_VALUE;
669 goto Exit;
670 }
671
672 // further channel mask checks are performed by createTrack_l() depending on the thread type
673 if (!audio_is_output_channel(channelMask)) {
674 ALOGE("createTrack() invalid channel mask %#x", channelMask);
675 lStatus = BAD_VALUE;
676 goto Exit;
677 }
678
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700679 // further format checks are performed by createTrack_l() depending on the thread type
680 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800681 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700682 lStatus = BAD_VALUE;
683 goto Exit;
684 }
685
Glenn Kasten663c2242013-09-24 11:52:37 -0700686 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
687 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
688 lStatus = BAD_VALUE;
689 goto Exit;
690 }
691
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 {
693 Mutex::Autolock _l(mLock);
694 PlaybackThread *thread = checkPlaybackThread_l(output);
695 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800696 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 lStatus = BAD_VALUE;
698 goto Exit;
699 }
700
Eric Laurent021cf962014-05-13 10:18:14 -0700701 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702
Glenn Kastene848bd92014-03-13 15:00:32 -0700703 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700704 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800705 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
706 ALOGE("createTrack() invalid session ID %d", *sessionId);
707 lStatus = BAD_VALUE;
708 goto Exit;
709 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700710 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700711 // check if an effect chain with the same session ID is present on another
712 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700713 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700714 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
715 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700716 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700717 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700718 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700719 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700720 }
Eric Laurentde070132010-07-13 04:45:46 -0700721 }
722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700724 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800725 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726 if (sessionId != NULL) {
727 *sessionId = lSessionId;
728 }
729 }
Steve Block3856b092011-10-20 11:56:00 +0100730 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731
732 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800733 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
734 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800735 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700736 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700737
738 // move effect chain to this output thread if an effect on same session was waiting
739 // for a track to be created
740 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700741 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700742 Mutex::Autolock _dl(thread->mLock);
743 Mutex::Autolock _sl(effectThread->mLock);
744 moveEffectChain_l(lSessionId, effectThread, thread, true);
745 }
Eric Laurenta011e352012-03-29 15:51:43 -0700746
747 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700748 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700749 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
750 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700751 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700752 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700753 } else {
754 mPendingSyncEvents[i]->cancel();
755 }
Eric Laurenta011e352012-03-29 15:51:43 -0700756 mPendingSyncEvents.removeAt(i);
757 i--;
758 }
759 }
760 }
Glenn Kastene198c362013-08-13 09:13:36 -0700761
Glenn Kastend848eb42016-03-08 13:42:11 -0800762 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 }
Glenn Kastene198c362013-08-13 09:13:36 -0700764
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700765 if (lStatus != NO_ERROR) {
766 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700767 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700768 // Don't hold mClientLock when releasing the reference on the track as the
769 // destructor will acquire it.
770 {
771 Mutex::Autolock _cl(mClientLock);
772 client.clear();
773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700775 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776 }
777
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700778 // return handle to client
779 trackHandle = new TrackHandle(track);
780
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700782 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 return trackHandle;
784}
785
Glenn Kasten2c073da2016-02-26 09:14:08 -0800786uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787{
788 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800789 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800791 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 return 0;
793 }
794 return thread->sampleRate();
795}
796
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800797audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798{
799 Mutex::Autolock _l(mLock);
800 PlaybackThread *thread = checkPlaybackThread_l(output);
801 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000802 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800803 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805 return thread->format();
806}
807
Glenn Kasten2c073da2016-02-26 09:14:08 -0800808size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809{
810 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800811 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800813 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return 0;
815 }
Glenn Kasten58912562012-04-03 10:45:00 -0700816 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
817 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 return thread->frameCount();
819}
820
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700821size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
822{
823 Mutex::Autolock _l(mLock);
824 ThreadBase *thread = checkThread_l(ioHandle);
825 if (thread == NULL) {
826 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
827 return 0;
828 }
829 return thread->frameCountHAL();
830}
831
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800832uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
834 Mutex::Autolock _l(mLock);
835 PlaybackThread *thread = checkPlaybackThread_l(output);
836 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800837 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 return 0;
839 }
840 return thread->latency();
841}
842
843status_t AudioFlinger::setMasterVolume(float value)
844{
Eric Laurenta1884f92011-08-23 08:25:03 -0700845 status_t ret = initCheck();
846 if (ret != NO_ERROR) {
847 return ret;
848 }
849
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 // check calling permissions
851 if (!settingsAllowed()) {
852 return PERMISSION_DENIED;
853 }
854
Eric Laurenta4c5a552012-03-29 10:12:40 -0700855 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700856 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857
John Grossmanee578c02012-07-23 17:05:46 -0700858 // Set master volume in the HALs which support it.
859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860 AutoMutex lock(mHardwareLock);
861 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800862
John Grossmanee578c02012-07-23 17:05:46 -0700863 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
864 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700865 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800866 }
John Grossmanee578c02012-07-23 17:05:46 -0700867 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869
John Grossmanee578c02012-07-23 17:05:46 -0700870 // Now set the master volume in each playback thread. Playback threads
871 // assigned to HALs which do not have master volume support will apply
872 // master volume during the mix operation. Threads with HALs which do
873 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700874 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
875 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
876 continue;
877 }
John Grossmanee578c02012-07-23 17:05:46 -0700878 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700879 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880
881 return NO_ERROR;
882}
883
Glenn Kastenf78aee72012-01-04 11:00:47 -0800884status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885{
Eric Laurenta1884f92011-08-23 08:25:03 -0700886 status_t ret = initCheck();
887 if (ret != NO_ERROR) {
888 return ret;
889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890
891 // check calling permissions
892 if (!settingsAllowed()) {
893 return PERMISSION_DENIED;
894 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800895 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000896 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 return BAD_VALUE;
898 }
899
900 { // scope for the lock
901 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700902 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700904 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 mHardwareStatus = AUDIO_HW_IDLE;
906 }
907
908 if (NO_ERROR == ret) {
909 Mutex::Autolock _l(mLock);
910 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800911 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700912 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914
915 return ret;
916}
917
918status_t AudioFlinger::setMicMute(bool state)
919{
Eric Laurenta1884f92011-08-23 08:25:03 -0700920 status_t ret = initCheck();
921 if (ret != NO_ERROR) {
922 return ret;
923 }
924
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 // check calling permissions
926 if (!settingsAllowed()) {
927 return PERMISSION_DENIED;
928 }
929
930 AutoMutex lock(mHardwareLock);
931 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700932 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700933 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
934 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700935 if (result != NO_ERROR) {
936 ret = result;
937 }
938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mHardwareStatus = AUDIO_HW_IDLE;
940 return ret;
941}
942
943bool AudioFlinger::getMicMute() const
944{
Eric Laurenta1884f92011-08-23 08:25:03 -0700945 status_t ret = initCheck();
946 if (ret != NO_ERROR) {
947 return false;
948 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800949 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700950 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800951 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800953 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700954 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
955 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800956 if (result == NO_ERROR) {
957 mute = mute && state;
958 }
959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800961
962 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963}
964
965status_t AudioFlinger::setMasterMute(bool muted)
966{
John Grossmand8f178d2012-07-20 14:51:35 -0700967 status_t ret = initCheck();
968 if (ret != NO_ERROR) {
969 return ret;
970 }
971
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 // check calling permissions
973 if (!settingsAllowed()) {
974 return PERMISSION_DENIED;
975 }
976
John Grossmanee578c02012-07-23 17:05:46 -0700977 Mutex::Autolock _l(mLock);
978 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700979
John Grossmanee578c02012-07-23 17:05:46 -0700980 // Set master mute in the HALs which support it.
981 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
982 AutoMutex lock(mHardwareLock);
983 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700984
John Grossmanee578c02012-07-23 17:05:46 -0700985 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
986 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700987 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700988 }
John Grossmanee578c02012-07-23 17:05:46 -0700989 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700990 }
991
John Grossmanee578c02012-07-23 17:05:46 -0700992 // Now set the master mute in each playback thread. Playback threads
993 // assigned to HALs which do not have master mute support will apply master
994 // mute during the mix operation. Threads with HALs which do support master
995 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -0800996 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
997 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
998 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000
1001 return NO_ERROR;
1002}
1003
1004float AudioFlinger::masterVolume() const
1005{
Glenn Kasten98067102011-12-13 11:47:54 -08001006 Mutex::Autolock _l(mLock);
1007 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008}
1009
1010bool AudioFlinger::masterMute() const
1011{
Glenn Kasten98067102011-12-13 11:47:54 -08001012 Mutex::Autolock _l(mLock);
1013 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014}
1015
John Grossman4ff14ba2012-02-08 16:37:41 -08001016float AudioFlinger::masterVolume_l() const
1017{
John Grossman4ff14ba2012-02-08 16:37:41 -08001018 return mMasterVolume;
1019}
1020
John Grossmand8f178d2012-07-20 14:51:35 -07001021bool AudioFlinger::masterMute_l() const
1022{
John Grossmanee578c02012-07-23 17:05:46 -07001023 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001024}
1025
Eric Laurent223fd5c2014-11-11 13:43:36 -08001026status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1027{
1028 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001029 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001030 return BAD_VALUE;
1031 }
1032 pid_t caller = IPCThreadState::self()->getCallingPid();
1033 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001034 ALOGW("checkStreamType() pid %d cannot use internal stream type %d", caller, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001035 return PERMISSION_DENIED;
1036 }
1037
1038 return NO_ERROR;
1039}
1040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001041status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1042 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043{
1044 // check calling permissions
1045 if (!settingsAllowed()) {
1046 return PERMISSION_DENIED;
1047 }
1048
Eric Laurent223fd5c2014-11-11 13:43:36 -08001049 status_t status = checkStreamType(stream);
1050 if (status != NO_ERROR) {
1051 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001053 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054
1055 AutoMutex lock(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001056 Vector<VolumeInterface *> volumeInterfaces;
Glenn Kasten142f5192014-03-25 17:44:59 -07001057 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001058 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1059 if (volumeInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 return BAD_VALUE;
1061 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001062 volumeInterfaces.add(volumeInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 }
1064
1065 mStreamTypes[stream].volume = value;
1066
Eric Laurent6acd1d42017-01-04 14:23:29 -08001067 if (volumeInterfaces.size() == 0) {
1068 volumeInterfaces = getAllVolumeInterfaces_l();
1069 }
1070 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1071 volumeInterfaces[i]->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 }
1073
1074 return NO_ERROR;
1075}
1076
Glenn Kastenfff6d712012-01-12 16:38:12 -08001077status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078{
1079 // check calling permissions
1080 if (!settingsAllowed()) {
1081 return PERMISSION_DENIED;
1082 }
1083
Eric Laurent223fd5c2014-11-11 13:43:36 -08001084 status_t status = checkStreamType(stream);
1085 if (status != NO_ERROR) {
1086 return status;
1087 }
1088 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1089
1090 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001091 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 return BAD_VALUE;
1093 }
1094
Eric Laurent93575202011-01-18 18:39:02 -08001095 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001097 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1098 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1099 volumeInterfaces[i]->setStreamMute(stream, muted);
1100 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001101
1102 return NO_ERROR;
1103}
1104
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001105float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001107 status_t status = checkStreamType(stream);
1108 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 return 0.0f;
1110 }
1111
1112 AutoMutex lock(mLock);
1113 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001114 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001115 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1116 if (volumeInterface != NULL) {
1117 volume = volumeInterface->streamVolume(stream);
1118 } else {
1119 volume = 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001122 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 }
1124
1125 return volume;
1126}
1127
Glenn Kastenfff6d712012-01-12 16:38:12 -08001128bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001130 status_t status = checkStreamType(stream);
1131 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 return true;
1133 }
1134
Glenn Kasten6637baa2012-01-09 09:40:36 -08001135 AutoMutex lock(mLock);
1136 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137}
1138
Eric Laurent054d9d32015-04-24 08:48:48 -07001139
1140void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1141{
1142 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1143 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1144 }
1145}
1146
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001147status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001149 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1150 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001151
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 // check calling permissions
1153 if (!settingsAllowed()) {
1154 return PERMISSION_DENIED;
1155 }
1156
Glenn Kasten142f5192014-03-25 17:44:59 -07001157 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1158 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001159 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001160 // result will remain NO_INIT if no audio device is present
1161 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001162 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001163 AutoMutex lock(mHardwareLock);
1164 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1165 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001166 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1167 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001168 // return success if at least one audio device accepts the parameters as not all
1169 // HALs are requested to support all parameters. If no audio device supports the
1170 // requested parameters, the last error is reported.
1171 if (final_result != NO_ERROR) {
1172 final_result = result;
1173 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001174 }
1175 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001176 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001177 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1178 AudioParameter param = AudioParameter(keyValuePairs);
1179 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001180 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1181 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001182 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001183 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1184 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001185 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001186 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1187 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001188 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001189 // suspend effects associated with those session IDs
1190 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001191 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001192 thread->setEffectSuspended(FX_IID_AEC,
1193 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001194 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001195 thread->setEffectSuspended(FX_IID_NS,
1196 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001197 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001198 }
1199 }
Eric Laurentbee53372011-08-29 12:42:48 -07001200 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001201 }
1202 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001203 String8 screenState;
1204 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001205 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001206 if (isOff != (AudioFlinger::mScreenState & 1)) {
1207 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001208 }
1209 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001210 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 }
1212
1213 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1214 // and the thread is exited once the lock is released
1215 sp<ThreadBase> thread;
1216 {
1217 Mutex::Autolock _l(mLock);
1218 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001219 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001221 if (thread == 0) {
1222 thread = checkMmapThread_l(ioHandle);
1223 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001224 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001225 // indicate output device change to all input threads for pre processing
1226 AudioParameter param = AudioParameter(keyValuePairs);
1227 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001228 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1229 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001230 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001231 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 }
1233 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001234 if (thread != 0) {
1235 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 }
1237 return BAD_VALUE;
1238}
1239
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001240String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001242 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1243 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244
Eric Laurenta4c5a552012-03-29 10:12:40 -07001245 Mutex::Autolock _l(mLock);
1246
Glenn Kasten142f5192014-03-25 17:44:59 -07001247 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001248 String8 out_s8;
1249
Dima Zavin799a70e2011-04-18 16:57:27 -07001250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001251 String8 s;
1252 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001253 {
1254 AutoMutex lock(mHardwareLock);
1255 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001256 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1257 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001258 mHardwareStatus = AUDIO_HW_IDLE;
1259 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001260 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001261 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001262 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 }
1264
Eric Laurent6acd1d42017-01-04 14:23:29 -08001265 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1266 if (thread == NULL) {
1267 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1268 if (thread == NULL) {
1269 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1270 if (thread == NULL) {
1271 String8("");
1272 }
1273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001275 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276}
1277
Glenn Kastendd8104c2012-07-02 12:42:44 -07001278size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1279 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280{
Eric Laurenta1884f92011-08-23 08:25:03 -07001281 status_t ret = initCheck();
1282 if (ret != NO_ERROR) {
1283 return 0;
1284 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001285 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001286 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001287 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001288 return 0;
1289 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001290
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001291 AutoMutex lock(mHardwareLock);
1292 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001293 audio_config_t config, proposed;
1294 memset(&proposed, 0, sizeof(proposed));
1295 proposed.sample_rate = sampleRate;
1296 proposed.channel_mask = channelMask;
1297 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001298
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001299 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001300 size_t frames;
1301 for (;;) {
1302 // Note: config is currently a const parameter for get_input_buffer_size()
1303 // but we use a copy from proposed in case config changes from the call.
1304 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001305 status_t result = dev->getInputBufferSize(&config, &frames);
1306 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001307 break; // hal success, config is the result
1308 }
1309 // change one parameter of the configuration each iteration to a more "common" value
1310 // to see if the device will support it.
1311 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1312 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1313 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1314 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1315 } else {
1316 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1317 "format %#x, channelMask 0x%X",
1318 sampleRate, format, channelMask);
1319 break; // retries failed, break out of loop with frames == 0.
1320 }
1321 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001322 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001323 if (frames > 0 && config.sample_rate != sampleRate) {
1324 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1325 }
1326 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327}
1328
Glenn Kasten5f972c02014-01-13 09:59:31 -08001329uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331 Mutex::Autolock _l(mLock);
1332
1333 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1334 if (recordThread != NULL) {
1335 return recordThread->getInputFramesLost();
1336 }
1337 return 0;
1338}
1339
1340status_t AudioFlinger::setVoiceVolume(float value)
1341{
Eric Laurenta1884f92011-08-23 08:25:03 -07001342 status_t ret = initCheck();
1343 if (ret != NO_ERROR) {
1344 return ret;
1345 }
1346
Mathias Agopian65ab4712010-07-14 17:59:35 -07001347 // check calling permissions
1348 if (!settingsAllowed()) {
1349 return PERMISSION_DENIED;
1350 }
1351
1352 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001353 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001354 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001355 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356 mHardwareStatus = AUDIO_HW_IDLE;
1357
1358 return ret;
1359}
1360
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001361status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001362 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364 Mutex::Autolock _l(mLock);
1365
1366 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1367 if (playbackThread != NULL) {
1368 return playbackThread->getRenderPosition(halFrames, dspFrames);
1369 }
1370
1371 return BAD_VALUE;
1372}
1373
1374void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1375{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001376 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001377 if (client == 0) {
1378 return;
1379 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001380 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001381 {
1382 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001383 if (mNotificationClients.indexOfKey(pid) < 0) {
1384 sp<NotificationClient> notificationClient = new NotificationClient(this,
1385 client,
1386 pid);
1387 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388
Eric Laurent021cf962014-05-13 10:18:14 -07001389 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390
Marco Nelissen06b46062014-11-14 07:58:25 -08001391 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001392 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001393 }
1394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395
Eric Laurent021cf962014-05-13 10:18:14 -07001396 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001397 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001398 // the config change is always sent from playback or record threads to avoid deadlock
1399 // with AudioSystem::gLock
1400 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1401 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001404 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1405 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 }
1407}
1408
1409void AudioFlinger::removeNotificationClient(pid_t pid)
1410{
1411 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001412 {
1413 Mutex::Autolock _cl(mClientLock);
1414 mNotificationClients.removeItem(pid);
1415 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001416
Steve Block3856b092011-10-20 11:56:00 +01001417 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001418 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001419 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001420 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001421 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001422 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001423 if (ref->mPid == pid) {
1424 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001425 mAudioSessionRefs.removeAt(i);
1426 delete ref;
1427 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001428 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001429 } else {
1430 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001431 }
1432 }
1433 if (removed) {
1434 purgeStaleEffects_l();
1435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
Eric Laurent73e26b62015-04-27 16:55:58 -07001438void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001439 const sp<AudioIoDescriptor>& ioDesc,
1440 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441{
Eric Laurent021cf962014-05-13 10:18:14 -07001442 Mutex::Autolock _l(mClientLock);
1443 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001445 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1446 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1447 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 }
1449}
1450
Eric Laurent021cf962014-05-13 10:18:14 -07001451// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452void AudioFlinger::removeClient_l(pid_t pid)
1453{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001454 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001455 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 mClients.removeItem(pid);
1457}
1458
Eric Laurent717e1282012-06-29 16:36:52 -07001459// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001460sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1461 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001462{
1463 sp<PlaybackThread> thread;
1464
1465 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1466 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1467 ALOG_ASSERT(thread == 0);
1468 thread = mPlaybackThreads.valueAt(i);
1469 }
1470 }
1471
1472 return thread;
1473}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476
1477// ----------------------------------------------------------------------------
1478
1479AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1480 : RefBase(),
1481 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001482 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301484 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1485 heapSize *= 1024;
1486 if (!heapSize) {
1487 heapSize = kClientSharedHeapSizeBytes;
1488 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1489 // invalidated tracks
1490 if (!audioFlinger->isLowRamDevice()) {
1491 heapSize *= kClientSharedHeapSizeMultiplier;
1492 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001493 }
1494 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495}
1496
Eric Laurent021cf962014-05-13 10:18:14 -07001497// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498AudioFlinger::Client::~Client()
1499{
1500 mAudioFlinger->removeClient_l(mPid);
1501}
1502
Glenn Kasten435dbe62012-01-30 10:15:48 -08001503sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
1505 return mMemoryDealer;
1506}
1507
1508// ----------------------------------------------------------------------------
1509
1510AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1511 const sp<IAudioFlingerClient>& client,
1512 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001513 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514{
1515}
1516
1517AudioFlinger::NotificationClient::~NotificationClient()
1518{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519}
1520
Glenn Kasten0f11b512014-01-31 16:18:54 -08001521void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522{
1523 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001524 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525}
1526
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527
1528// ----------------------------------------------------------------------------
1529
1530sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001531 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001533 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001534 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001535 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001536 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001537 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001538 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001539 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001540 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001541 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001542 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001543 sp<IMemory>& cblk,
1544 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001545 status_t *status,
1546 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547{
1548 sp<RecordThread::RecordTrack> recordTrack;
1549 sp<RecordHandle> recordHandle;
1550 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001552 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553
Glenn Kastend776ac62014-05-07 09:16:09 -07001554 cblk.clear();
1555 buffers.clear();
1556
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001557 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001558 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1559 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001560 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001561 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1562 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001563 updatePid = true;
1564 }
1565
1566 if (updatePid) {
1567 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1568 ALOGW_IF(pid != -1 && pid != callingPid,
1569 "%s uid %d pid %d tried to pass itself off as pid %d",
1570 __func__, callingUid, callingPid, pid);
1571 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001572 }
1573
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001575 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001576 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 lStatus = PERMISSION_DENIED;
1578 goto Exit;
1579 }
1580
Glenn Kasten53b5d092014-02-05 10:00:23 -08001581 // further sample rate checks are performed by createRecordTrack_l()
1582 if (sampleRate == 0) {
1583 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1584 lStatus = BAD_VALUE;
1585 goto Exit;
1586 }
1587
Andy Hung6770c6f2015-04-07 13:43:36 -07001588 // we don't yet support anything other than linear PCM
1589 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001590 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001591 lStatus = BAD_VALUE;
1592 goto Exit;
1593 }
1594
Glenn Kasten53b5d092014-02-05 10:00:23 -08001595 // further channel mask checks are performed by createRecordTrack_l()
1596 if (!audio_is_input_channel(channelMask)) {
1597 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1598 lStatus = BAD_VALUE;
1599 goto Exit;
1600 }
1601
Glenn Kasten05997e22014-03-13 15:08:33 -07001602 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001604 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001606 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 lStatus = BAD_VALUE;
1608 goto Exit;
1609 }
1610
Eric Laurent021cf962014-05-13 10:18:14 -07001611 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001613 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001614 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1615 lStatus = BAD_VALUE;
1616 goto Exit;
1617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 lSessionId = *sessionId;
1619 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001620 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001621 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 if (sessionId != NULL) {
1623 *sessionId = lSessionId;
1624 }
1625 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001626 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001627
Glenn Kasten1879fff2012-07-11 15:36:59 -07001628 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001629 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001630 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001631 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001632
1633 if (lStatus == NO_ERROR) {
1634 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1635 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001636 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001637 if (chain != 0) {
1638 Mutex::Autolock _l(thread->mLock);
1639 thread->addEffectChain_l(chain);
1640 }
1641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
Glenn Kastene198c362013-08-13 09:13:36 -07001643
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001644 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001645 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001646 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001647 // Don't hold mClientLock when releasing the reference on the track as the
1648 // destructor will acquire it.
1649 {
1650 Mutex::Autolock _cl(mClientLock);
1651 client.clear();
1652 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 goto Exit;
1655 }
1656
Glenn Kastend776ac62014-05-07 09:16:09 -07001657 cblk = recordTrack->getCblk();
1658 buffers = recordTrack->getBuffers();
1659
Glenn Kasten2fc14732013-08-05 14:58:14 -07001660 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662
1663Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001664 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 return recordHandle;
1666}
1667
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001668
1669
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670// ----------------------------------------------------------------------------
1671
Eric Laurenta4c5a552012-03-29 10:12:40 -07001672audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1673{
Eric Laurent44622db2014-08-01 19:00:33 -07001674 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001675 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001676 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001677 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001678 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001679 }
1680 Mutex::Autolock _l(mLock);
1681 return loadHwModule_l(name);
1682}
1683
1684// loadHwModule_l() must be called with AudioFlinger::mLock held
1685audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1686{
1687 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1688 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1689 ALOGW("loadHwModule() module %s already loaded", name);
1690 return mAudioHwDevs.keyAt(i);
1691 }
1692 }
1693
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001694 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001695
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001696 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001697 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001698 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001699 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001700 }
1701
1702 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001703 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001704 mHardwareStatus = AUDIO_HW_IDLE;
1705 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001706 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001707 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001708 }
1709
John Grossmanee578c02012-07-23 17:05:46 -07001710 // Check and cache this HAL's level of support for master mute and master
1711 // volume. If this is the first HAL opened, and it supports the get
1712 // methods, use the initial values provided by the HAL as the current
1713 // master mute and volume settings.
1714
1715 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1716 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001717 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001718
1719 if (0 == mAudioHwDevs.size()) {
1720 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001721 float mv;
1722 if (OK == dev->getMasterVolume(&mv)) {
1723 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001724 }
1725
1726 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001727 bool mm;
1728 if (OK == dev->getMasterMute(&mm)) {
1729 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001730 }
1731 }
1732
Eric Laurenta4c5a552012-03-29 10:12:40 -07001733 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001734 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001735 flags = static_cast<AudioHwDevice::Flags>(flags |
1736 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1737 }
1738
1739 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001740 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001741 flags = static_cast<AudioHwDevice::Flags>(flags |
1742 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1743 }
1744
Eric Laurenta4c5a552012-03-29 10:12:40 -07001745 mHardwareStatus = AUDIO_HW_IDLE;
1746 }
1747
Glenn Kastena13cde92016-03-28 15:26:02 -07001748 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001749 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001750
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001751 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001752
1753 return handle;
1754
1755}
1756
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001757// ----------------------------------------------------------------------------
1758
Glenn Kasten3b16c762012-11-14 08:44:39 -08001759uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001760{
1761 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001762 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001763 return thread != NULL ? thread->sampleRate() : 0;
1764}
1765
Glenn Kastene33054e2012-11-14 12:54:39 -08001766size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001767{
1768 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001769 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001770 return thread != NULL ? thread->frameCountHAL() : 0;
1771}
1772
1773// ----------------------------------------------------------------------------
1774
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001775status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1776{
1777 uid_t uid = IPCThreadState::self()->getCallingUid();
1778 if (uid != AID_SYSTEM) {
1779 return PERMISSION_DENIED;
1780 }
1781 Mutex::Autolock _l(mLock);
1782 if (mIsDeviceTypeKnown) {
1783 return INVALID_OPERATION;
1784 }
1785 mIsLowRamDevice = isLowRamDevice;
1786 mIsDeviceTypeKnown = true;
1787 return NO_ERROR;
1788}
1789
Eric Laurent93c3d412014-08-01 14:48:35 -07001790audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1791{
1792 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001793
1794 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1795 if (index >= 0) {
1796 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1797 mHwAvSyncIds.valueAt(index), sessionId);
1798 return mHwAvSyncIds.valueAt(index);
1799 }
1800
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001801 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001802 if (dev == NULL) {
1803 return AUDIO_HW_SYNC_INVALID;
1804 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001805 String8 reply;
1806 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001807 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001808 param = AudioParameter(reply);
1809 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001810
1811 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001812 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001813 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1814 return AUDIO_HW_SYNC_INVALID;
1815 }
1816
1817 // allow only one session for a given HW A/V sync ID.
1818 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1819 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1820 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1821 value, mHwAvSyncIds.keyAt(i));
1822 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001823 break;
1824 }
1825 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001826
1827 mHwAvSyncIds.add(sessionId, value);
1828
1829 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1830 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1831 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001832 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001833 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001834 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001835 thread->setParameters(param.toString());
1836 break;
1837 }
1838 }
1839
1840 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1841 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001842}
1843
Eric Laurent72e3f392015-05-20 14:43:50 -07001844status_t AudioFlinger::systemReady()
1845{
1846 Mutex::Autolock _l(mLock);
1847 ALOGI("%s", __FUNCTION__);
1848 if (mSystemReady) {
1849 ALOGW("%s called twice", __FUNCTION__);
1850 return NO_ERROR;
1851 }
1852 mSystemReady = true;
1853 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1854 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1855 thread->systemReady();
1856 }
1857 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1858 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1859 thread->systemReady();
1860 }
1861 return NO_ERROR;
1862}
1863
Eric Laurentfa90e842014-10-17 18:12:31 -07001864// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1865void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1866{
1867 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1868 if (index >= 0) {
1869 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1870 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1871 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001872 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001873 thread->setParameters(param.toString());
1874 }
1875}
1876
1877
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001878// ----------------------------------------------------------------------------
1879
Eric Laurent83b88082014-06-20 18:31:16 -07001880
Eric Laurent6acd1d42017-01-04 14:23:29 -08001881sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 audio_io_handle_t *output,
1883 audio_config_t *config,
1884 audio_devices_t devices,
1885 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001886 audio_output_flags_t flags)
1887{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001888 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001889 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001890 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001891 }
1892
Eric Laurentcf2c0212014-07-25 16:20:43 -07001893 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001894 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1895 } else {
1896 // Audio Policy does not currently request a specific output handle.
1897 // If this is ever needed, see openInput_l() for example code.
1898 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1899 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001900 }
Eric Laurent83b88082014-06-20 18:31:16 -07001901
1902 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1903
Eric Laurent83b88082014-06-20 18:31:16 -07001904 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001905 // This if statement allows overriding the audio policy settings
1906 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1907 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1908 // Check only for Normal Mixing mode
1909 if (kEnableExtendedPrecision) {
1910 // Specify format (uncomment one below to choose)
1911 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1912 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1913 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1914 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001915 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001916 }
1917 if (kEnableExtendedChannels) {
1918 // Specify channel mask (uncomment one below to choose)
1919 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1920 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1921 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1922 }
Eric Laurent83b88082014-06-20 18:31:16 -07001923 }
1924
Phil Burk062e67a2015-02-11 13:40:50 -08001925 AudioStreamOut *outputStream = NULL;
1926 status_t status = outHwDev->openOutputStream(
1927 &outputStream,
1928 *output,
1929 devices,
1930 flags,
1931 config,
1932 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001933
1934 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001935
Phil Burk062e67a2015-02-11 13:40:50 -08001936 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001937 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
1938 sp<MmapPlaybackThread> thread =
1939 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
1940 devices, AUDIO_DEVICE_NONE, mSystemReady);
1941 mMmapThreads.add(*output, thread);
1942 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
1943 *output, thread.get());
1944 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07001945 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001946 sp<PlaybackThread> thread;
1947 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1948 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
1949 ALOGV("openOutput_l() created offload output: ID %d thread %p",
1950 *output, thread.get());
1951 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1952 || !isValidPcmSinkFormat(config->format)
1953 || !isValidPcmSinkChannelMask(config->channel_mask)) {
1954 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
1955 ALOGV("openOutput_l() created direct output: ID %d thread %p",
1956 *output, thread.get());
1957 } else {
1958 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
1959 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
1960 *output, thread.get());
1961 }
1962 mPlaybackThreads.add(*output, thread);
1963 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07001964 }
Eric Laurent83b88082014-06-20 18:31:16 -07001965 }
1966
1967 return 0;
1968}
1969
Eric Laurentcf2c0212014-07-25 16:20:43 -07001970status_t AudioFlinger::openOutput(audio_module_handle_t module,
1971 audio_io_handle_t *output,
1972 audio_config_t *config,
1973 audio_devices_t *devices,
1974 const String8& address,
1975 uint32_t *latencyMs,
1976 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977{
Eric Laurent6acd1d42017-01-04 14:23:29 -08001978 ALOGI("openOutput() this %p, module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
1979 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001980 (devices != NULL) ? *devices : 0,
1981 config->sample_rate,
1982 config->format,
1983 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001984 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985
Eric Laurentcf2c0212014-07-25 16:20:43 -07001986 if (*devices == AUDIO_DEVICE_NONE) {
1987 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001989
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 Mutex::Autolock _l(mLock);
1991
Eric Laurent6acd1d42017-01-04 14:23:29 -08001992 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001993 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001994 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
1995 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
1996 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
Eric Laurent6acd1d42017-01-04 14:23:29 -08001998 // notify client processes of the new output creation
1999 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002000
Eric Laurent6acd1d42017-01-04 14:23:29 -08002001 // the first primary output opened designates the primary hw device
2002 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
2003 ALOGI("Using module %d has the primary audio interface", module);
2004 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002005
Eric Laurent6acd1d42017-01-04 14:23:29 -08002006 AutoMutex lock(mHardwareLock);
2007 mHardwareStatus = AUDIO_HW_SET_MODE;
2008 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2009 mHardwareStatus = AUDIO_HW_IDLE;
2010 }
2011 } else {
2012 MmapThread *mmapThread = (MmapThread *)thread.get();
2013 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002014 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002015 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 }
2017
Eric Laurentcf2c0212014-07-25 16:20:43 -07002018 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019}
2020
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002021audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2022 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023{
2024 Mutex::Autolock _l(mLock);
2025 MixerThread *thread1 = checkMixerThread_l(output1);
2026 MixerThread *thread2 = checkMixerThread_l(output2);
2027
2028 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002029 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2030 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002031 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 }
2033
Glenn Kasteneeecb982016-02-26 10:44:04 -08002034 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002035 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 thread->addOutputTrack(thread2);
2037 mPlaybackThreads.add(id, thread);
2038 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002039 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 return id;
2041}
2042
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002043status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044{
Glenn Kastend96c5722012-04-25 13:44:49 -07002045 return closeOutput_nonvirtual(output);
2046}
2047
2048status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2049{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 // keep strong reference on the playback thread so that
2051 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002052 sp<PlaybackThread> playbackThread;
2053 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 {
2055 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002056 playbackThread = checkPlaybackThread_l(output);
2057 if (playbackThread != NULL) {
2058 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059
Eric Laurent6acd1d42017-01-04 14:23:29 -08002060 if (playbackThread->type() == ThreadBase::MIXER) {
2061 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2062 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2063 DuplicatingThread *dupThread =
2064 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2065 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2066 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002067 }
2068 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002069
2070
Eric Laurent6acd1d42017-01-04 14:23:29 -08002071 mPlaybackThreads.removeItem(output);
2072 // save all effects to the default thread
2073 if (mPlaybackThreads.size()) {
2074 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2075 if (dstThread != NULL) {
2076 // audioflinger lock is held here so the acquisition order of thread locks does not
2077 // matter
2078 Mutex::Autolock _dl(dstThread->mLock);
2079 Mutex::Autolock _sl(playbackThread->mLock);
2080 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2081 for (size_t i = 0; i < effectChains.size(); i ++) {
2082 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(), dstThread, true);
2083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 }
2085 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002086 } else {
2087 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2088 if (mmapThread == 0) {
2089 return BAD_VALUE;
2090 }
2091 mMmapThreads.removeItem(output);
2092 ALOGV("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002094 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2095 ioDesc->mIoHandle = output;
2096 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002098 // The thread entity (active unit of execution) is no longer running here,
2099 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100
Eric Laurent6acd1d42017-01-04 14:23:29 -08002101 if (playbackThread != 0) {
2102 playbackThread->exit();
2103 if (!playbackThread->isDuplicating()) {
2104 closeOutputFinish(playbackThread);
2105 }
2106 } else if (mmapThread != 0) {
2107 ALOGV("mmapThread exit()");
2108 mmapThread->exit();
2109 AudioStreamOut *out = mmapThread->clearOutput();
2110 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2111 // from now on thread->mOutput is NULL
2112 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 }
2114 return NO_ERROR;
2115}
2116
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002117void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002118{
2119 AudioStreamOut *out = thread->clearOutput();
2120 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2121 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002122 delete out;
2123}
2124
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002125void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002126{
2127 mPlaybackThreads.removeItem(thread->mId);
2128 thread->exit();
2129 closeOutputFinish(thread);
2130}
2131
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002132status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133{
2134 Mutex::Autolock _l(mLock);
2135 PlaybackThread *thread = checkPlaybackThread_l(output);
2136
2137 if (thread == NULL) {
2138 return BAD_VALUE;
2139 }
2140
Steve Block3856b092011-10-20 11:56:00 +01002141 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142 thread->suspend();
2143
2144 return NO_ERROR;
2145}
2146
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002147status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148{
2149 Mutex::Autolock _l(mLock);
2150 PlaybackThread *thread = checkPlaybackThread_l(output);
2151
2152 if (thread == NULL) {
2153 return BAD_VALUE;
2154 }
2155
Steve Block3856b092011-10-20 11:56:00 +01002156 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157
2158 thread->restore();
2159
2160 return NO_ERROR;
2161}
2162
Eric Laurentcf2c0212014-07-25 16:20:43 -07002163status_t AudioFlinger::openInput(audio_module_handle_t module,
2164 audio_io_handle_t *input,
2165 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002166 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002167 const String8& address,
2168 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002169 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170{
Eric Laurent83b88082014-06-20 18:31:16 -07002171 Mutex::Autolock _l(mLock);
2172
Glenn Kastene7d66712015-03-05 13:46:52 -08002173 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002174 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002175 }
2176
Eric Laurent6acd1d42017-01-04 14:23:29 -08002177 sp<ThreadBase> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002178
2179 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002180 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002181 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002182 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002184 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002185}
Dima Zavin799a70e2011-04-18 16:57:27 -07002186
Eric Laurent6acd1d42017-01-04 14:23:29 -08002187sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002188 audio_io_handle_t *input,
2189 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002190 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002191 const String8& address,
2192 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002193 audio_input_flags_t flags)
2194{
Glenn Kastene7d66712015-03-05 13:46:52 -08002195 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002196 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002197 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002198 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002199 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002200
Glenn Kasteneeecb982016-02-26 10:44:04 -08002201 // Audio Policy can request a specific handle for hardware hotword.
2202 // The goal here is not to re-open an already opened input.
2203 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002204 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002205 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2206 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2207 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2208 return 0;
2209 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2210 // This should not happen in a transient state with current design.
2211 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2212 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002213 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002214
Eric Laurentcf2c0212014-07-25 16:20:43 -07002215 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002216 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002217 sp<StreamInHalInterface> inStream;
2218 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002219 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002220 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002221 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002222 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002223 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002224 halconfig.sample_rate,
2225 halconfig.format,
2226 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002227 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002228 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002230 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002231 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002232 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002233 audio_is_linear_pcm(config->format) &&
2234 audio_is_linear_pcm(halconfig.format) &&
2235 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002236 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2237 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002238 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002239 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002240 inStream.clear();
2241 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002242 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002243 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 }
2245
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002247 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002248 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2249 sp<MmapCaptureThread> thread =
2250 new MmapCaptureThread(this, *input,
2251 inHwDev, inputStream,
2252 primaryOutputDevice_l(), devices, mSystemReady);
2253 mMmapThreads.add(*input, thread);
2254 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input, thread.get());
2255 return thread;
2256 } else {
Glenn Kasten46909e72013-02-26 09:20:22 -08002257#ifdef TEE_SINK
Eric Laurent6acd1d42017-01-04 14:23:29 -08002258 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2259 // or (re-)create if current Pipe is idle and does not match the new format
2260 sp<NBAIO_Sink> teeSink;
2261 enum {
2262 TEE_SINK_NO, // don't copy input
2263 TEE_SINK_NEW, // copy input using a new pipe
2264 TEE_SINK_OLD, // copy input using an existing pipe
2265 } kind;
2266 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2267 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
2268 if (!mTeeSinkInputEnabled) {
2269 kind = TEE_SINK_NO;
2270 } else if (!Format_isValid(format)) {
2271 kind = TEE_SINK_NO;
2272 } else if (mRecordTeeSink == 0) {
2273 kind = TEE_SINK_NEW;
2274 } else if (mRecordTeeSink->getStrongCount() != 1) {
2275 kind = TEE_SINK_NO;
2276 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
2277 kind = TEE_SINK_OLD;
2278 } else {
2279 kind = TEE_SINK_NEW;
2280 }
2281 switch (kind) {
2282 case TEE_SINK_NEW: {
2283 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
2284 size_t numCounterOffers = 0;
2285 const NBAIO_Format offers[1] = {format};
2286 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2287 ALOG_ASSERT(index == 0);
2288 PipeReader *pipeReader = new PipeReader(*pipe);
2289 numCounterOffers = 0;
2290 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2291 ALOG_ASSERT(index == 0);
2292 mRecordTeeSink = pipe;
2293 mRecordTeeSource = pipeReader;
2294 teeSink = pipe;
2295 }
2296 break;
2297 case TEE_SINK_OLD:
2298 teeSink = mRecordTeeSink;
2299 break;
2300 case TEE_SINK_NO:
2301 default:
2302 break;
2303 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002304#endif
Eric Laurent6acd1d42017-01-04 14:23:29 -08002305
2306 // Start record thread
2307 // RecordThread requires both input and output device indication to forward to audio
2308 // pre processing modules
2309 sp<RecordThread> thread = new RecordThread(this,
2310 inputStream,
2311 *input,
2312 primaryOutputDevice_l(),
2313 devices,
2314 mSystemReady
2315#ifdef TEE_SINK
2316 , teeSink
2317#endif
2318 );
2319 mRecordThreads.add(*input, thread);
2320 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2321 return thread;
2322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 }
2324
Eric Laurentcf2c0212014-07-25 16:20:43 -07002325 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 return 0;
2327}
2328
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002329status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330{
Glenn Kastend96c5722012-04-25 13:44:49 -07002331 return closeInput_nonvirtual(input);
2332}
2333
2334status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2335{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 // keep strong reference on the record thread so that
2337 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002338 sp<RecordThread> recordThread;
2339 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 {
2341 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002342 recordThread = checkRecordThread_l(input);
2343 if (recordThread != 0) {
2344 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345
Eric Laurent6acd1d42017-01-04 14:23:29 -08002346 // If we still have effect chains, it means that a client still holds a handle
2347 // on at least one effect. We must either move the chain to an existing thread with the
2348 // same session ID or put it aside in case a new record thread is opened for a
2349 // new capture on the same session
2350 sp<EffectChain> chain;
2351 {
2352 Mutex::Autolock _sl(recordThread->mLock);
2353 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2354 // Note: maximum one chain per record thread
2355 if (effectChains.size() != 0) {
2356 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002357 }
2358 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002359 if (chain != 0) {
2360 // first check if a record thread is already opened with a client on the same session.
2361 // This should only happen in case of overlap between one thread tear down and the
2362 // creation of its replacement
2363 size_t i;
2364 for (i = 0; i < mRecordThreads.size(); i++) {
2365 sp<RecordThread> t = mRecordThreads.valueAt(i);
2366 if (t == recordThread) {
2367 continue;
2368 }
2369 if (t->hasAudioSession(chain->sessionId()) != 0) {
2370 Mutex::Autolock _l(t->mLock);
2371 ALOGV("closeInput() found thread %d for effect session %d",
2372 t->id(), chain->sessionId());
2373 t->addEffectChain_l(chain);
2374 break;
2375 }
2376 }
2377 // put the chain aside if we could not find a record thread with the same session id.
2378 if (i == mRecordThreads.size()) {
2379 putOrphanEffectChain_l(chain);
2380 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002381 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002382 mRecordThreads.removeItem(input);
2383 } else {
2384 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2385 if (mmapThread == 0) {
2386 return BAD_VALUE;
2387 }
2388 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002389 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002390 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2391 ioDesc->mIoHandle = input;
2392 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 }
Eric Laurent83b88082014-06-20 18:31:16 -07002394 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2395 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396 if (recordThread != 0) {
2397 closeInputFinish(recordThread);
2398 } else if (mmapThread != 0) {
2399 mmapThread->exit();
2400 AudioStreamIn *in = mmapThread->clearInput();
2401 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2402 // from now on thread->mInput is NULL
2403 delete in;
2404 }
Eric Laurent83b88082014-06-20 18:31:16 -07002405 return NO_ERROR;
2406}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002407
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002408void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002409{
2410 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002411 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002412 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002413 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002414 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002415}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002416
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002417void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002418{
2419 mRecordThreads.removeItem(thread->mId);
2420 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421}
2422
Glenn Kastend2304db2014-02-03 07:40:31 -08002423status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424{
2425 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002426 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427
2428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2429 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002430 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002431 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002432 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2433 mMmapThreads[i]->invalidateTracks(stream);
2434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 return NO_ERROR;
2436}
2437
2438
Glenn Kasteneeecb982016-02-26 10:44:04 -08002439audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440{
Glenn Kasten9d003132016-04-06 14:38:09 -07002441 // This is a binder API, so a malicious client could pass in a bad parameter.
2442 // Check for that before calling the internal API nextUniqueId().
2443 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2444 ALOGE("newAudioUniqueId invalid use %d", use);
2445 return AUDIO_UNIQUE_ID_ALLOCATE;
2446 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002447 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002448}
2449
Glenn Kastend848eb42016-03-08 13:42:11 -08002450void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002451{
2452 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002453 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002454 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2455 if (pid != -1 && (caller == getpid_cached)) {
2456 caller = pid;
2457 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002458
Eric Laurent021cf962014-05-13 10:18:14 -07002459 {
2460 Mutex::Autolock _cl(mClientLock);
2461 // Ignore requests received from processes not known as notification client. The request
2462 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2463 // called from a different pid leaving a stale session reference. Also we don't know how
2464 // to clear this reference if the client process dies.
2465 if (mNotificationClients.indexOfKey(caller) < 0) {
2466 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2467 return;
2468 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002469 }
2470
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002471 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002472 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002473 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002474 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2475 ref->mCnt++;
2476 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002477 return;
2478 }
2479 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002480 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2481 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002482}
2483
Glenn Kastend848eb42016-03-08 13:42:11 -08002484void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002485{
2486 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002487 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002488 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2489 if (pid != -1 && (caller == getpid_cached)) {
2490 caller = pid;
2491 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002492 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002493 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002494 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002495 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2496 ref->mCnt--;
2497 ALOGV(" decremented refcount to %d", ref->mCnt);
2498 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002499 mAudioSessionRefs.removeAt(i);
2500 delete ref;
2501 purgeStaleEffects_l();
2502 }
2503 return;
2504 }
2505 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002506 // If the caller is mediaserver it is likely that the session being released was acquired
2507 // on behalf of a process not in notification clients and we ignore the warning.
2508 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002509}
2510
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002511bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2512{
2513 size_t num = mAudioSessionRefs.size();
2514 for (size_t i = 0; i < num; i++) {
2515 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2516 if (ref->mSessionid == audioSession) {
2517 return true;
2518 }
2519 }
2520 return false;
2521}
2522
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002523void AudioFlinger::purgeStaleEffects_l() {
2524
Steve Block3856b092011-10-20 11:56:00 +01002525 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002526
2527 Vector< sp<EffectChain> > chains;
2528
2529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2530 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2531 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2532 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002533 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2534 chains.push(ec);
2535 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002536 }
2537 }
2538 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2539 sp<RecordThread> t = mRecordThreads.valueAt(i);
2540 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2541 sp<EffectChain> ec = t->mEffectChains[j];
2542 chains.push(ec);
2543 }
2544 }
2545
2546 for (size_t i = 0; i < chains.size(); i++) {
2547 sp<EffectChain> ec = chains[i];
2548 int sessionid = ec->sessionId();
2549 sp<ThreadBase> t = ec->mThread.promote();
2550 if (t == 0) {
2551 continue;
2552 }
2553 size_t numsessionrefs = mAudioSessionRefs.size();
2554 bool found = false;
2555 for (size_t k = 0; k < numsessionrefs; k++) {
2556 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002557 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002558 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002559 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002560 found = true;
2561 break;
2562 }
2563 }
2564 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002565 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002566 // remove all effects from the chain
2567 while (ec->mEffects.size()) {
2568 sp<EffectModule> effect = ec->mEffects[0];
2569 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002570 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002571 if (effect->purgeHandles()) {
2572 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002573 }
2574 AudioSystem::unregisterEffect(effect->id());
2575 }
2576 }
2577 }
2578 return;
2579}
2580
Glenn Kasteneeecb982016-02-26 10:44:04 -08002581// checkThread_l() must be called with AudioFlinger::mLock held
2582AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2583{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002584 ThreadBase *thread = checkMmapThread_l(ioHandle);
2585 if (thread == 0) {
2586 switch (audio_unique_id_get_use(ioHandle)) {
2587 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2588 thread = checkPlaybackThread_l(ioHandle);
2589 break;
2590 case AUDIO_UNIQUE_ID_USE_INPUT:
2591 thread = checkRecordThread_l(ioHandle);
2592 break;
2593 default:
2594 break;
2595 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002596 }
2597 return thread;
2598}
2599
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002601AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602{
Glenn Kastena1117922012-01-26 10:53:32 -08002603 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604}
2605
2606// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002607AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608{
2609 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002610 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611}
2612
2613// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002614AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615{
Glenn Kastena1117922012-01-26 10:53:32 -08002616 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617}
2618
Eric Laurent6acd1d42017-01-04 14:23:29 -08002619// checkMmapThread_l() must be called with AudioFlinger::mLock held
2620AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2621{
2622 return mMmapThreads.valueFor(io).get();
2623}
2624
2625
2626// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2627AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2628{
2629 VolumeInterface *volumeInterface = (VolumeInterface *)mPlaybackThreads.valueFor(output).get();
2630 if (volumeInterface == nullptr) {
2631 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2632 if (mmapThread != nullptr) {
2633 if (mmapThread->isOutput()) {
2634 volumeInterface = (VolumeInterface *)mmapThread;
2635 }
2636 }
2637 }
2638 return volumeInterface;
2639}
2640
2641Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2642{
2643 Vector <VolumeInterface *> volumeInterfaces;
2644 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2645 volumeInterfaces.add((VolumeInterface *)mPlaybackThreads.valueAt(i).get());
2646 }
2647 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2648 if (mMmapThreads.valueAt(i)->isOutput()) {
2649 volumeInterfaces.add((VolumeInterface *)mMmapThreads.valueAt(i).get());
2650 }
2651 }
2652 return volumeInterfaces;
2653}
2654
Glenn Kasteneeecb982016-02-26 10:44:04 -08002655audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656{
Glenn Kasten9d003132016-04-06 14:38:09 -07002657 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002658 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002659 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2660 for (int retry = 0; retry < maxRetries; retry++) {
2661 // The cast allows wraparound from max positive to min negative instead of abort
2662 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2663 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2664 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2665 // allow wrap by skipping 0 and -1 for session ids
2666 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2667 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2668 return (audio_unique_id_t) (base | use);
2669 }
2670 }
2671 // We have no way of recovering from wraparound
2672 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2673 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674}
2675
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002676AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002677{
2678 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2679 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002680 if(thread->isDuplicating()) {
2681 continue;
2682 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002683 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002684 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002685 return thread;
2686 }
2687 }
2688 return NULL;
2689}
2690
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002691audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002692{
2693 PlaybackThread *thread = primaryPlaybackThread_l();
2694
2695 if (thread == NULL) {
2696 return 0;
2697 }
2698
Eric Laurentf1c04f92012-08-28 14:26:53 -07002699 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002700}
2701
Glenn Kastena7335632016-06-09 17:09:53 -07002702AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2703{
2704 size_t minFrameCount = 0;
2705 PlaybackThread *minThread = NULL;
2706 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2707 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2708 if (!thread->isDuplicating()) {
2709 size_t frameCount = thread->frameCountHAL();
2710 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2711 (frameCount == minFrameCount && thread->hasFastMixer() &&
2712 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2713 minFrameCount = frameCount;
2714 minThread = thread;
2715 }
2716 }
2717 }
2718 return minThread;
2719}
2720
Eric Laurenta011e352012-03-29 15:51:43 -07002721sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002722 audio_session_t triggerSession,
2723 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002724 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002725 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002726{
2727 Mutex::Autolock _l(mLock);
2728
2729 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2730 status_t playStatus = NAME_NOT_FOUND;
2731 status_t recStatus = NAME_NOT_FOUND;
2732 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2733 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2734 if (playStatus == NO_ERROR) {
2735 return event;
2736 }
2737 }
2738 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2739 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2740 if (recStatus == NO_ERROR) {
2741 return event;
2742 }
2743 }
2744 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2745 mPendingSyncEvents.add(event);
2746 } else {
2747 ALOGV("createSyncEvent() invalid event %d", event->type());
2748 event.clear();
2749 }
2750 return event;
2751}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002752
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753// ----------------------------------------------------------------------------
2754// Effect management
2755// ----------------------------------------------------------------------------
2756
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002757sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2758 return mEffectsFactoryHal;
2759}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760
Glenn Kastenf587ba52012-01-26 16:25:10 -08002761status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762{
2763 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002764 if (mEffectsFactoryHal.get()) {
2765 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2766 } else {
2767 return -ENODEV;
2768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769}
2770
Glenn Kastenf587ba52012-01-26 16:25:10 -08002771status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772{
2773 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002774 if (mEffectsFactoryHal.get()) {
2775 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2776 } else {
2777 return -ENODEV;
2778 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779}
2780
Glenn Kasten5e92a782012-01-30 07:40:52 -08002781status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002782 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783{
2784 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002785 if (mEffectsFactoryHal.get()) {
2786 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2787 } else {
2788 return -ENODEV;
2789 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790}
2791
2792
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002793sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 effect_descriptor_t *pDesc,
2795 const sp<IEffectClient>& effectClient,
2796 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002797 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002798 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002799 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002800 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 status_t *status,
2802 int *id,
2803 int *enabled)
2804{
2805 status_t lStatus = NO_ERROR;
2806 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808
Eric Laurentb6436272016-12-07 19:24:50 -08002809 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2810 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2811 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2812 ALOGW_IF(pid != -1 && pid != callingPid,
2813 "%s uid %d pid %d tried to pass itself off as pid %d",
2814 __func__, callingUid, callingPid, pid);
2815 pid = callingPid;
2816 }
2817
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002818 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2819 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820
2821 if (pDesc == NULL) {
2822 lStatus = BAD_VALUE;
2823 goto Exit;
2824 }
2825
Eric Laurent84e9a102010-09-23 16:10:16 -07002826 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002827 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002828 lStatus = PERMISSION_DENIED;
2829 goto Exit;
2830 }
2831
Dima Zavinfce7a472011-04-19 22:30:36 -07002832 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002833 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002834 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002835 lStatus = PERMISSION_DENIED;
2836 goto Exit;
2837 }
2838
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002839 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002840 lStatus = NO_INIT;
2841 goto Exit;
2842 }
2843
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002845 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002846 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002847 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002849 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 goto Exit;
2851 }
2852 } else {
2853 // if uuid is not specified, look for an available implementation
2854 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002855 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002856 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 lStatus = BAD_VALUE;
2858 goto Exit;
2859 }
2860 uint32_t numEffects = 0;
2861 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002862 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 bool found = false;
2864
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002865 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002867 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 goto Exit;
2869 }
2870 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002871 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002873 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 continue;
2875 }
2876 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2877 // If matching type found save effect descriptor. If the session is
2878 // 0 and the effect is not auxiliary, continue enumeration in case
2879 // an auxiliary version of this effect type is available
2880 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002881 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002882 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2884 break;
2885 }
2886 }
2887 }
2888 if (!found) {
2889 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002890 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 goto Exit;
2892 }
2893 // For same effect type, chose auxiliary version over insert version if
2894 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002895 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002897 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 }
2899 }
2900
2901 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002902 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2904 lStatus = INVALID_OPERATION;
2905 goto Exit;
2906 }
2907
Eric Laurent59255e42011-07-27 19:49:51 -07002908 // check recording permission for visualizer
2909 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002910 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002911 lStatus = PERMISSION_DENIED;
2912 goto Exit;
2913 }
2914
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002916 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002917 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002918 // if the output returned by getOutputForEffect() is removed before we lock the
2919 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2920 // and we will exit safely
2921 io = AudioSystem::getOutputForEffect(&desc);
2922 ALOGV("createEffect got output %d", io);
2923 }
2924
2925 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926
2927 // If output is not specified try to find a matching audio session ID in one of the
2928 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002929 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2930 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002931 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002932 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002933 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2934 // output must be specified by AudioPolicyManager when using session
2935 // AUDIO_SESSION_OUTPUT_STAGE
2936 lStatus = BAD_VALUE;
2937 goto Exit;
2938 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002939 // look for the thread where the specified audio session is present
2940 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2941 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2942 io = mPlaybackThreads.keyAt(i);
2943 break;
2944 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002946 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002947 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2948 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2949 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002950 break;
2951 }
2952 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002953 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002954 if (io == AUDIO_IO_HANDLE_NONE) {
2955 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2956 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2957 io = mMmapThreads.keyAt(i);
2958 break;
2959 }
2960 }
2961 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002962 // If no output thread contains the requested session ID, default to
2963 // first output. The effect chain will be moved to the correct output
2964 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002965 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002966 io = mPlaybackThreads.keyAt(0);
2967 }
Steve Block3856b092011-10-20 11:56:00 +01002968 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002969 }
2970 ThreadBase *thread = checkRecordThread_l(io);
2971 if (thread == NULL) {
2972 thread = checkPlaybackThread_l(io);
2973 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002974 thread = checkMmapThread_l(io);
2975 if (thread == NULL) {
2976 ALOGE("createEffect() unknown output thread");
2977 lStatus = BAD_VALUE;
2978 goto Exit;
2979 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002980 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002981 } else {
2982 // Check if one effect chain was awaiting for an effect to be created on this
2983 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002984 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002985 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002986 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002987 thread->addEffectChain_l(chain);
2988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002990
Eric Laurent021cf962014-05-13 10:18:14 -07002991 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002993 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002994 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002995 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002996 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 if (handle != 0 && id != NULL) {
2998 *id = handle->id();
2999 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003000 if (handle == 0) {
3001 // remove local strong reference to Client with mClientLock held
3002 Mutex::Autolock _cl(mClientLock);
3003 client.clear();
3004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 }
3006
3007Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003008 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 return handle;
3010}
3011
Glenn Kastend848eb42016-03-08 13:42:11 -08003012status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003013 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003014{
Steve Block3856b092011-10-20 11:56:00 +01003015 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003016 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003017 Mutex::Autolock _l(mLock);
3018 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003019 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003020 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 }
Eric Laurentde070132010-07-13 04:45:46 -07003022 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3023 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003024 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003025 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
Eric Laurentde070132010-07-13 04:45:46 -07003027 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3028 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003029 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003030 return BAD_VALUE;
3031 }
3032
3033 Mutex::Autolock _dl(dstThread->mLock);
3034 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003035 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036}
3037
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003038// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003039status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003040 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003041 AudioFlinger::PlaybackThread *dstThread,
3042 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003043{
Steve Block3856b092011-10-20 11:56:00 +01003044 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003045 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003046
Eric Laurent59255e42011-07-27 19:49:51 -07003047 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003048 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003049 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003050 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003051 return INVALID_OPERATION;
3052 }
3053
Eric Laurent4c415062016-06-17 16:14:16 -07003054 // Check whether the destination thread and all effects in the chain are compatible
3055 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003056 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003057 " destination thread %p is not compatible with effects in the chain",
3058 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003059 return INVALID_OPERATION;
3060 }
3061
Eric Laurent39e94f82010-07-28 01:32:47 -07003062 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003063 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003064 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003065 // removed.
3066 srcThread->removeEffectChain_l(chain);
3067
3068 // transfer all effects one by one so that new effect chain is created on new thread with
3069 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003070 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003071 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003072 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003073 Vector< sp<EffectModule> > removed;
3074 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003075 while (effect != 0) {
3076 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003077 removed.add(effect);
3078 status = dstThread->addEffect_l(effect);
3079 if (status != NO_ERROR) {
3080 break;
3081 }
Eric Laurentec35a142011-10-05 17:42:25 -07003082 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3083 if (effect->state() == EffectModule::ACTIVE ||
3084 effect->state() == EffectModule::STOPPING) {
3085 effect->start();
3086 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003087 // if the move request is not received from audio policy manager, the effect must be
3088 // re-registered with the new strategy and output
3089 if (dstChain == 0) {
3090 dstChain = effect->chain().promote();
3091 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003092 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003093 status = NO_INIT;
3094 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003095 }
3096 strategy = dstChain->strategy();
3097 }
3098 if (reRegister) {
3099 AudioSystem::unregisterEffect(effect->id());
3100 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003101 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003102 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003103 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003104 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003105 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003106 }
Eric Laurentde070132010-07-13 04:45:46 -07003107 effect = chain->getEffectFromId_l(0);
3108 }
3109
Eric Laurent5baf2af2013-09-12 17:37:00 -07003110 if (status != NO_ERROR) {
3111 for (size_t i = 0; i < removed.size(); i++) {
3112 srcThread->addEffect_l(removed[i]);
3113 if (dstChain != 0 && reRegister) {
3114 AudioSystem::unregisterEffect(removed[i]->id());
3115 AudioSystem::registerEffect(&removed[i]->desc(),
3116 srcThread->id(),
3117 strategy,
3118 sessionId,
3119 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003120 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003121 }
3122 }
3123 }
3124
3125 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126}
3127
Eric Laurent5baf2af2013-09-12 17:37:00 -07003128bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003129{
3130 if (mGlobalEffectEnableTime != 0 &&
3131 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3132 return true;
3133 }
3134
3135 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3136 sp<EffectChain> ec =
3137 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003138 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003139 return true;
3140 }
3141 }
3142 return false;
3143}
3144
Eric Laurent5baf2af2013-09-12 17:37:00 -07003145void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003146{
3147 Mutex::Autolock _l(mLock);
3148
3149 mGlobalEffectEnableTime = systemTime();
3150
3151 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3152 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3153 if (t->mType == ThreadBase::OFFLOAD) {
3154 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3155 }
3156 }
3157
3158}
3159
Eric Laurentaaa44472014-09-12 17:41:50 -07003160status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3161{
Glenn Kastend848eb42016-03-08 13:42:11 -08003162 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003163 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003164 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003165 if (index >= 0) {
3166 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3167 return ALREADY_EXISTS;
3168 }
3169 mOrphanEffectChains.add(session, chain);
3170 return NO_ERROR;
3171}
3172
3173sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3174{
3175 sp<EffectChain> chain;
3176 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003177 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003178 if (index >= 0) {
3179 chain = mOrphanEffectChains.valueAt(index);
3180 mOrphanEffectChains.removeItemsAt(index);
3181 }
3182 return chain;
3183}
3184
3185bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3186{
3187 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003188 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003189 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003190 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003191 if (index >= 0) {
3192 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003193 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003194 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003195 mOrphanEffectChains.removeItemsAt(index);
3196 }
3197 return true;
3198 }
3199 return false;
3200}
3201
3202
Glenn Kastenda6ef132013-01-10 12:31:01 -08003203struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003204#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3205 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003206};
3207
3208int comparEntry(const void *p1, const void *p2)
3209{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003210 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003211}
3212
Glenn Kasten46909e72013-02-26 09:20:22 -08003213#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003214void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215{
Eric Laurent81784c32012-11-19 14:55:58 -08003216 NBAIO_Source *teeSource = source.get();
3217 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003218 // .wav rotation
3219 // There is a benign race condition if 2 threads call this simultaneously.
3220 // They would both traverse the directory, but the result would simply be
3221 // failures at unlink() which are ignored. It's also unlikely since
3222 // normally dumpsys is only done by bugreport or from the command line.
3223 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003224 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003225 size_t teePathLen = strlen(teePath);
3226 DIR *dir = opendir(teePath);
3227 teePath[teePathLen++] = '/';
3228 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003229#define TEE_MAX_SORT 20 // number of entries to sort
3230#define TEE_MAX_KEEP 10 // number of entries to keep
3231 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003232 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003233 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003234 struct dirent de;
3235 struct dirent *result = NULL;
3236 int rc = readdir_r(dir, &de, &result);
3237 if (rc != 0) {
3238 ALOGW("readdir_r failed %d", rc);
3239 break;
3240 }
3241 if (result == NULL) {
3242 break;
3243 }
3244 if (result != &de) {
3245 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3246 break;
3247 }
3248 // ignore non .wav file entries
3249 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003250 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003251 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3252 continue;
3253 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003254 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003255 }
3256 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003257 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003258 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003259 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3260 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003261 (void) unlink(teePath);
3262 }
3263 }
3264 } else {
3265 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003266 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003267 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003268 }
3269 }
Eric Laurent81784c32012-11-19 14:55:58 -08003270 char teeTime[16];
3271 struct timeval tv;
3272 gettimeofday(&tv, NULL);
3273 struct tm tm;
3274 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003275 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3276 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3277 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3278 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003279 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003280 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003281 char wavHeader[44];
3282 memcpy(wavHeader,
3283 "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",
3284 sizeof(wavHeader));
3285 NBAIO_Format format = teeSource->format();
3286 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003287 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003288 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003289 wavHeader[22] = channelCount; // number of channels
3290 wavHeader[24] = sampleRate; // sample rate
3291 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003292 wavHeader[32] = frameSize; // block alignment
3293 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003294 write(teeFd, wavHeader, sizeof(wavHeader));
3295 size_t total = 0;
3296 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003297#define TEE_SINK_READ 1024 // frames per I/O operation
3298 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003299 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003300 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003301 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003302 bool wasFirstRead = firstRead;
3303 firstRead = false;
3304 if (actual <= 0) {
3305 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3306 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003307 }
Eric Laurent81784c32012-11-19 14:55:58 -08003308 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003309 }
Eric Laurent81784c32012-11-19 14:55:58 -08003310 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003311 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003312 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003313 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003314 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003315 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003316 uint32_t temp = 44 + total * frameSize - 8;
3317 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003318 write(teeFd, &temp, sizeof(temp));
3319 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003320 temp = total * frameSize;
3321 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003322 write(teeFd, &temp, sizeof(temp));
3323 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003324 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003325 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003326 }
Eric Laurent59255e42011-07-27 19:49:51 -07003327 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003328 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003329 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003330 }
Eric Laurent59255e42011-07-27 19:49:51 -07003331 }
3332 }
3333}
Glenn Kasten46909e72013-02-26 09:20:22 -08003334#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003335
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336// ----------------------------------------------------------------------------
3337
3338status_t AudioFlinger::onTransact(
3339 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3340{
3341 return BnAudioFlinger::onTransact(code, data, reply, flags);
3342}
3343
Glenn Kasten63238ef2015-03-02 15:50:29 -08003344} // namespace android