blob: 81f59de5a5f36ca089e9c73563e4539b2f398ba1 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070034#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
Mikhail Naganove4f1f632016-08-31 11:35:10 -070047#include "DeviceHalInterface.h"
48#include "DevicesFactoryHalInterface.h"
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070049#include "EffectsFactoryHalInterface.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
John Grossman1c345192012-03-27 14:00:17 -070072// Note: the following macro is used for extremely verbose logging message. In
73// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
74// 0; but one side effect of this is to turn all LOGV's as well. Some messages
75// are so verbose that we want to suppress them even when we have ALOG_ASSERT
76// turned on. Do not uncomment the #def below unless you really know what you
77// are doing and want to see all of the extremely verbose messages.
78//#define VERY_VERY_VERBOSE_LOGGING
79#ifdef VERY_VERY_VERBOSE_LOGGING
80#define ALOGVV ALOGV
81#else
82#define ALOGVV(a...) do { } while(0)
83#endif
Eric Laurentde070132010-07-13 04:45:46 -070084
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Glenn Kastenec1d6b52011-12-12 09:04:45 -080087static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
88static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070089static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070090static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
Glenn Kasten58912562012-04-03 10:45:00 -070092
John Grossman4ff14ba2012-02-08 16:37:41 -080093nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080094
Eric Laurent81784c32012-11-19 14:55:58 -080095uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070096
Glenn Kasten46909e72013-02-26 09:20:22 -080097#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080098bool AudioFlinger::mTeeSinkInputEnabled = false;
99bool AudioFlinger::mTeeSinkOutputEnabled = false;
100bool AudioFlinger::mTeeSinkTrackEnabled = false;
101
102size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
103size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
104size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800105#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800106
Eric Laurent813e2a72013-08-31 12:59:48 -0700107// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
108// we define a minimum time during which a global effect is considered enabled.
109static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
110
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111// ----------------------------------------------------------------------------
112
Marco Nelissenb2208842014-02-07 14:00:50 -0800113const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800114 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530115 case AUDIO_FORMAT_PCM:
116 switch (format) {
117 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
118 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
119 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
120 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
121 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
122 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
123 default:
124 break;
125 }
126 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800127 case AUDIO_FORMAT_MP3: return "mp3";
128 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
129 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
130 case AUDIO_FORMAT_AAC: return "aac";
131 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
132 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
133 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530134 case AUDIO_FORMAT_OPUS: return "opus";
135 case AUDIO_FORMAT_AC3: return "ac-3";
136 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800137 case AUDIO_FORMAT_IEC61937: return "iec61937";
Eric Laurente30f2092016-07-07 18:56:57 -0700138 case AUDIO_FORMAT_DTS: return "dts";
139 case AUDIO_FORMAT_DTS_HD: return "dts-hd";
140 case AUDIO_FORMAT_DOLBY_TRUEHD: return "dolby-truehd";
Marco Nelissenb2208842014-02-07 14:00:50 -0800141 default:
142 break;
143 }
144 return "unknown";
145}
146
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147// ----------------------------------------------------------------------------
148
149AudioFlinger::AudioFlinger()
150 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800151 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800152 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700153 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800155 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700156 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700158 mBtNrecIsOff(false),
159 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700160 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700161 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700162 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700163{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700164 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
165 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
166 // zero ID has a special meaning, so unavailable
167 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
168 }
169
Glenn Kasten949a9262013-04-16 12:35:20 -0700170 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800171 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800172 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800173 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
174 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800175 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700176
Wei Jia3f273d12015-11-24 09:06:49 -0800177 // reset battery stats.
178 // if the audio service has crashed, battery stats could be left
179 // in bad state, reset the state upon service start.
180 BatteryNotifier::getInstance().noteResetAudio();
181
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700182 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700183 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
184
Glenn Kasten46909e72013-02-26 09:20:22 -0800185#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800186 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800187 (void) property_get("ro.debuggable", value, "0");
188 int debuggable = atoi(value);
189 int teeEnabled = 0;
190 if (debuggable) {
191 (void) property_get("af.tee", value, "0");
192 teeEnabled = atoi(value);
193 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800194 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700195 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800196 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700197 }
198 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700200 }
201 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700203 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800204#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700205}
206
207void AudioFlinger::onFirstRef()
208{
Eric Laurent93575202011-01-18 18:39:02 -0800209 Mutex::Autolock _l(mLock);
210
Dima Zavin799a70e2011-04-18 16:57:27 -0700211 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 char val_str[PROPERTY_VALUE_MAX] = { 0 };
213 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
214 uint32_t int_val;
215 if (1 == sscanf(val_str, "%u", &int_val)) {
216 mStandbyTimeInNsecs = milliseconds(int_val);
217 ALOGI("Using %u mSec as standby time.", int_val);
218 } else {
219 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
220 ALOGI("Using default %u mSec as standby time.",
221 (uint32_t)(mStandbyTimeInNsecs / 1000000));
222 }
223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224
Eric Laurent1c333e22014-05-20 10:48:17 -0700225 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700226
Eric Laurenta4c5a552012-03-29 10:12:40 -0700227 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228}
229
230AudioFlinger::~AudioFlinger()
231{
232 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700233 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700234 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 }
236 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700237 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700238 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700240
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800241 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
242 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700243 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700245
246 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800247 if (mLogMemoryDealer != 0) {
248 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
249 if (binder != 0) {
250 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
251 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
252 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
253 mUnregisteredWriters.pop();
254 mediaLogService->unregisterWriter(iMemory);
255 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700256 }
257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258}
259
Eric Laurenta4c5a552012-03-29 10:12:40 -0700260static const char * const audio_interfaces[] = {
261 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
262 AUDIO_HARDWARE_MODULE_ID_A2DP,
263 AUDIO_HARDWARE_MODULE_ID_USB,
264};
265#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
266
Phil Burk062e67a2015-02-11 13:40:50 -0800267AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700268 audio_module_handle_t module,
269 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700270{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 // if module is 0, the request comes from an old policy manager and we should load
272 // well known modules
273 if (module == 0) {
274 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
275 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
276 loadHwModule_l(audio_interfaces[i]);
277 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700278 // then try to find a module supporting the requested device.
279 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
280 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700281 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
282 uint32_t supportedDevices;
283 if (dev->getSupportedDevices(&supportedDevices) == OK &&
284 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700285 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700286 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700287 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700288 } else {
289 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700290 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
291 if (audioHwDevice != NULL) {
292 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700293 }
294 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295
Dima Zavin799a70e2011-04-18 16:57:27 -0700296 return NULL;
297}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
Glenn Kasten0f11b512014-01-31 16:18:54 -0800299void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300{
301 const size_t SIZE = 256;
302 char buffer[SIZE];
303 String8 result;
304
305 result.append("Clients:\n");
306 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800307 sp<Client> client = mClients.valueAt(i).promote();
308 if (client != 0) {
309 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
310 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311 }
312 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700313
Eric Laurentd1b28d42013-09-18 18:47:13 -0700314 result.append("Notification Clients:\n");
315 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
316 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
317 result.append(buffer);
318 }
319
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700320 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800321 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
323 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800324 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700325 result.append(buffer);
326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700327 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328}
329
330
Glenn Kasten0f11b512014-01-31 16:18:54 -0800331void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332{
333 const size_t SIZE = 256;
334 char buffer[SIZE];
335 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800336 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337
John Grossman4ff14ba2012-02-08 16:37:41 -0800338 snprintf(buffer, SIZE, "Hardware status: %d\n"
339 "Standby Time mSec: %u\n",
340 hardwareStatus,
341 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342 result.append(buffer);
343 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344}
345
Glenn Kasten0f11b512014-01-31 16:18:54 -0800346void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
351 snprintf(buffer, SIZE, "Permission Denial: "
352 "can't dump AudioFlinger from pid=%d, uid=%d\n",
353 IPCThreadState::self()->getCallingPid(),
354 IPCThreadState::self()->getCallingUid());
355 result.append(buffer);
356 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357}
358
Eric Laurent81784c32012-11-19 14:55:58 -0800359bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360{
361 bool locked = false;
362 for (int i = 0; i < kDumpLockRetries; ++i) {
363 if (mutex.tryLock() == NO_ERROR) {
364 locked = true;
365 break;
366 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800367 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
Glenn Kasten44deb052012-02-05 18:09:08 -0800374 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 dumpPermissionDenial(fd, args);
376 } else {
377 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800378 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379 if (!hardwareLocked) {
380 String8 result(kHardwareLockedString);
381 write(fd, result.string(), result.size());
382 } else {
383 mHardwareLock.unlock();
384 }
385
Eric Laurent81784c32012-11-19 14:55:58 -0800386 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387
388 // failed to lock - AudioFlinger is probably deadlocked
389 if (!locked) {
390 String8 result(kDeadlockedString);
391 write(fd, result.string(), result.size());
392 }
393
Eric Laurent021cf962014-05-13 10:18:14 -0700394 bool clientLocked = dumpTryLock(mClientLock);
395 if (!clientLocked) {
396 String8 result(kClientLockedString);
397 write(fd, result.string(), result.size());
398 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700399
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700400 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700401 mEffectsFactoryHal->dumpEffects(fd);
402 } else {
403 String8 result(kNoEffectsFactory);
404 write(fd, result.string(), result.size());
405 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700406
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700408 if (clientLocked) {
409 mClientLock.unlock();
410 }
411
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 dumpInternals(fd, args);
413
414 // dump playback threads
415 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
416 mPlaybackThreads.valueAt(i)->dump(fd, args);
417 }
418
419 // dump record threads
420 for (size_t i = 0; i < mRecordThreads.size(); i++) {
421 mRecordThreads.valueAt(i)->dump(fd, args);
422 }
423
Eric Laurentaaa44472014-09-12 17:41:50 -0700424 // dump orphan effect chains
425 if (mOrphanEffectChains.size() != 0) {
426 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
427 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
428 mOrphanEffectChains.valueAt(i)->dump(fd, args);
429 }
430 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700431 // dump all hardware devs
432 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700433 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
434 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700436
Glenn Kasten46909e72013-02-26 09:20:22 -0800437#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700438 // dump the serially shared record tee sink
439 if (mRecordTeeSource != 0) {
440 dumpTee(fd, mRecordTeeSource);
441 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800442#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700443
Glenn Kastend65d73c2012-06-22 17:21:07 -0700444 if (locked) {
445 mLock.unlock();
446 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800447
448 // append a copy of media.log here by forwarding fd to it, but don't attempt
449 // to lookup the service if it's not running, as it will block for a second
450 if (mLogMemoryDealer != 0) {
451 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
452 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700453 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800454 Vector<String16> args;
455 binder->dump(fd, args);
456 }
457 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700458
459 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700460 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700461 bool unreachableMemory = false;
462 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700463 if (arg == String16("-m")) {
464 dumpMem = true;
465 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700466 unreachableMemory = true;
467 }
468 }
469
Andy Hung07b745e2016-05-23 16:21:07 -0700470 if (dumpMem) {
471 dprintf(fd, "\nDumping memory:\n");
472 std::string s = dumpMemoryAddresses(100 /* limit */);
473 write(fd, s.c_str(), s.size());
474 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700475 if (unreachableMemory) {
476 dprintf(fd, "\nDumping unreachable memory:\n");
477 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700478 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700479 write(fd, s.c_str(), s.size());
480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 }
482 return NO_ERROR;
483}
484
Eric Laurent021cf962014-05-13 10:18:14 -0700485sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800486{
Eric Laurent021cf962014-05-13 10:18:14 -0700487 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800488 // If pid is already in the mClients wp<> map, then use that entry
489 // (for which promote() is always != 0), otherwise create a new entry and Client.
490 sp<Client> client = mClients.valueFor(pid).promote();
491 if (client == 0) {
492 client = new Client(this, pid);
493 mClients.add(pid, client);
494 }
495
496 return client;
497}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498
Glenn Kasten9e58b552013-01-18 15:09:48 -0800499sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
500{
Glenn Kasten481fb672013-09-30 14:39:28 -0700501 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800502 if (mLogMemoryDealer == 0) {
503 return new NBLog::Writer();
504 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800505 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700506 // Similarly if we can't contact the media.log service, also return a dummy writer
507 if (binder == 0) {
508 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800509 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700510 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
511 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
512 // If allocation fails, consult the vector of previously unregistered writers
513 // and garbage-collect one or more them until an allocation succeeds
514 if (shared == 0) {
515 Mutex::Autolock _l(mUnregisteredWritersLock);
516 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
517 {
518 // Pick the oldest stale writer to garbage-collect
519 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
520 mUnregisteredWriters.removeAt(0);
521 mediaLogService->unregisterWriter(iMemory);
522 // Now the media.log remote reference to IMemory is gone. When our last local
523 // reference to IMemory also drops to zero at end of this block,
524 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
525 }
526 // Re-attempt the allocation
527 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
528 if (shared != 0) {
529 goto success;
530 }
531 }
532 // Even after garbage-collecting all old writers, there is still not enough memory,
533 // so return a dummy writer
534 return new NBLog::Writer();
535 }
536success:
537 mediaLogService->registerWriter(shared, size, name);
538 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800539}
540
541void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
542{
Glenn Kasten685ef092013-02-04 08:15:34 -0800543 if (writer == 0) {
544 return;
545 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800546 sp<IMemory> iMemory(writer->getIMemory());
547 if (iMemory == 0) {
548 return;
549 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700550 // Rather than removing the writer immediately, append it to a queue of old writers to
551 // be garbage-collected later. This allows us to continue to view old logs for a while.
552 Mutex::Autolock _l(mUnregisteredWritersLock);
553 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800554}
555
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556// IAudioFlinger interface
557
558
559sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800560 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800562 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700563 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800564 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700565 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800567 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700568 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800569 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800570 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800571 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572 status_t *status)
573{
574 sp<PlaybackThread::Track> track;
575 sp<TrackHandle> trackHandle;
576 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800578 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700580 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
581 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
582 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
583 ALOGW_IF(pid != -1 && pid != callingPid,
584 "%s uid %d pid %d tried to pass itself off as pid %d",
585 __func__, callingUid, callingPid, pid);
586 pid = callingPid;
587 }
588
Glenn Kasten263709e2012-01-06 08:40:01 -0800589 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
590 // but if someone uses binder directly they could bypass that and cause us to crash
591 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000592 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 lStatus = BAD_VALUE;
594 goto Exit;
595 }
596
Glenn Kasten53b5d092014-02-05 10:00:23 -0800597 // further sample rate checks are performed by createTrack_l() depending on the thread type
598 if (sampleRate == 0) {
599 ALOGE("createTrack() invalid sample rate %u", sampleRate);
600 lStatus = BAD_VALUE;
601 goto Exit;
602 }
603
604 // further channel mask checks are performed by createTrack_l() depending on the thread type
605 if (!audio_is_output_channel(channelMask)) {
606 ALOGE("createTrack() invalid channel mask %#x", channelMask);
607 lStatus = BAD_VALUE;
608 goto Exit;
609 }
610
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700611 // further format checks are performed by createTrack_l() depending on the thread type
612 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800613 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700614 lStatus = BAD_VALUE;
615 goto Exit;
616 }
617
Glenn Kasten663c2242013-09-24 11:52:37 -0700618 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
619 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
620 lStatus = BAD_VALUE;
621 goto Exit;
622 }
623
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 {
625 Mutex::Autolock _l(mLock);
626 PlaybackThread *thread = checkPlaybackThread_l(output);
627 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800628 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 lStatus = BAD_VALUE;
630 goto Exit;
631 }
632
Eric Laurent021cf962014-05-13 10:18:14 -0700633 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634
Glenn Kastene848bd92014-03-13 15:00:32 -0700635 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700636 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800637 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
638 ALOGE("createTrack() invalid session ID %d", *sessionId);
639 lStatus = BAD_VALUE;
640 goto Exit;
641 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700642 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700643 // check if an effect chain with the same session ID is present on another
644 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700645 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700646 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
647 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700648 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700649 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700650 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700651 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700652 }
Eric Laurentde070132010-07-13 04:45:46 -0700653 }
654 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700656 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800657 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 if (sessionId != NULL) {
659 *sessionId = lSessionId;
660 }
661 }
Steve Block3856b092011-10-20 11:56:00 +0100662 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663
664 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800665 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800666 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700667 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700668
669 // move effect chain to this output thread if an effect on same session was waiting
670 // for a track to be created
671 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700672 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700673 Mutex::Autolock _dl(thread->mLock);
674 Mutex::Autolock _sl(effectThread->mLock);
675 moveEffectChain_l(lSessionId, effectThread, thread, true);
676 }
Eric Laurenta011e352012-03-29 15:51:43 -0700677
678 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700679 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700680 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
681 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700682 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700683 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700684 } else {
685 mPendingSyncEvents[i]->cancel();
686 }
Eric Laurenta011e352012-03-29 15:51:43 -0700687 mPendingSyncEvents.removeAt(i);
688 i--;
689 }
690 }
691 }
Glenn Kastene198c362013-08-13 09:13:36 -0700692
Glenn Kastend848eb42016-03-08 13:42:11 -0800693 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 }
Glenn Kastene198c362013-08-13 09:13:36 -0700695
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700696 if (lStatus != NO_ERROR) {
697 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700698 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700699 // Don't hold mClientLock when releasing the reference on the track as the
700 // destructor will acquire it.
701 {
702 Mutex::Autolock _cl(mClientLock);
703 client.clear();
704 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700706 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 }
708
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700709 // return handle to client
710 trackHandle = new TrackHandle(track);
711
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700713 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 return trackHandle;
715}
716
Glenn Kasten2c073da2016-02-26 09:14:08 -0800717uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718{
719 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800720 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800722 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 return 0;
724 }
725 return thread->sampleRate();
726}
727
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800728audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729{
730 Mutex::Autolock _l(mLock);
731 PlaybackThread *thread = checkPlaybackThread_l(output);
732 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000733 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800734 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735 }
736 return thread->format();
737}
738
Glenn Kasten2c073da2016-02-26 09:14:08 -0800739size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740{
741 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800742 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800744 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745 return 0;
746 }
Glenn Kasten58912562012-04-03 10:45:00 -0700747 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
748 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 return thread->frameCount();
750}
751
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700752size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
753{
754 Mutex::Autolock _l(mLock);
755 ThreadBase *thread = checkThread_l(ioHandle);
756 if (thread == NULL) {
757 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
758 return 0;
759 }
760 return thread->frameCountHAL();
761}
762
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800763uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764{
765 Mutex::Autolock _l(mLock);
766 PlaybackThread *thread = checkPlaybackThread_l(output);
767 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800768 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 return 0;
770 }
771 return thread->latency();
772}
773
774status_t AudioFlinger::setMasterVolume(float value)
775{
Eric Laurenta1884f92011-08-23 08:25:03 -0700776 status_t ret = initCheck();
777 if (ret != NO_ERROR) {
778 return ret;
779 }
780
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 // check calling permissions
782 if (!settingsAllowed()) {
783 return PERMISSION_DENIED;
784 }
785
Eric Laurenta4c5a552012-03-29 10:12:40 -0700786 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700787 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700788
John Grossmanee578c02012-07-23 17:05:46 -0700789 // Set master volume in the HALs which support it.
790 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
791 AutoMutex lock(mHardwareLock);
792 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800793
John Grossmanee578c02012-07-23 17:05:46 -0700794 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
795 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700796 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800797 }
John Grossmanee578c02012-07-23 17:05:46 -0700798 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800
John Grossmanee578c02012-07-23 17:05:46 -0700801 // Now set the master volume in each playback thread. Playback threads
802 // assigned to HALs which do not have master volume support will apply
803 // master volume during the mix operation. Threads with HALs which do
804 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700805 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
806 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
807 continue;
808 }
John Grossmanee578c02012-07-23 17:05:46 -0700809 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811
812 return NO_ERROR;
813}
814
Glenn Kastenf78aee72012-01-04 11:00:47 -0800815status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816{
Eric Laurenta1884f92011-08-23 08:25:03 -0700817 status_t ret = initCheck();
818 if (ret != NO_ERROR) {
819 return ret;
820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821
822 // check calling permissions
823 if (!settingsAllowed()) {
824 return PERMISSION_DENIED;
825 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800826 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000827 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 return BAD_VALUE;
829 }
830
831 { // scope for the lock
832 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700833 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700835 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 mHardwareStatus = AUDIO_HW_IDLE;
837 }
838
839 if (NO_ERROR == ret) {
840 Mutex::Autolock _l(mLock);
841 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800842 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700843 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844 }
845
846 return ret;
847}
848
849status_t AudioFlinger::setMicMute(bool state)
850{
Eric Laurenta1884f92011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return ret;
854 }
855
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 // check calling permissions
857 if (!settingsAllowed()) {
858 return PERMISSION_DENIED;
859 }
860
861 AutoMutex lock(mHardwareLock);
862 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700863 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700864 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
865 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700866 if (result != NO_ERROR) {
867 ret = result;
868 }
869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 mHardwareStatus = AUDIO_HW_IDLE;
871 return ret;
872}
873
874bool AudioFlinger::getMicMute() const
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return false;
879 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800880 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700881 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800882 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800884 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700885 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
886 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800887 if (result == NO_ERROR) {
888 mute = mute && state;
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800892
893 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894}
895
896status_t AudioFlinger::setMasterMute(bool muted)
897{
John Grossmand8f178d2012-07-20 14:51:35 -0700898 status_t ret = initCheck();
899 if (ret != NO_ERROR) {
900 return ret;
901 }
902
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 // check calling permissions
904 if (!settingsAllowed()) {
905 return PERMISSION_DENIED;
906 }
907
John Grossmanee578c02012-07-23 17:05:46 -0700908 Mutex::Autolock _l(mLock);
909 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700910
John Grossmanee578c02012-07-23 17:05:46 -0700911 // Set master mute in the HALs which support it.
912 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
913 AutoMutex lock(mHardwareLock);
914 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700915
John Grossmanee578c02012-07-23 17:05:46 -0700916 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
917 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700918 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700919 }
John Grossmanee578c02012-07-23 17:05:46 -0700920 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700921 }
922
John Grossmanee578c02012-07-23 17:05:46 -0700923 // Now set the master mute in each playback thread. Playback threads
924 // assigned to HALs which do not have master mute support will apply master
925 // mute during the mix operation. Threads with HALs which do support master
926 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
929 continue;
930 }
John Grossmanee578c02012-07-23 17:05:46 -0700931 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933
934 return NO_ERROR;
935}
936
937float AudioFlinger::masterVolume() const
938{
Glenn Kasten98067102011-12-13 11:47:54 -0800939 Mutex::Autolock _l(mLock);
940 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700941}
942
943bool AudioFlinger::masterMute() const
944{
Glenn Kasten98067102011-12-13 11:47:54 -0800945 Mutex::Autolock _l(mLock);
946 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947}
948
John Grossman4ff14ba2012-02-08 16:37:41 -0800949float AudioFlinger::masterVolume_l() const
950{
John Grossman4ff14ba2012-02-08 16:37:41 -0800951 return mMasterVolume;
952}
953
John Grossmand8f178d2012-07-20 14:51:35 -0700954bool AudioFlinger::masterMute_l() const
955{
John Grossmanee578c02012-07-23 17:05:46 -0700956 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700957}
958
Eric Laurent223fd5c2014-11-11 13:43:36 -0800959status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
960{
961 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
962 ALOGW("setStreamVolume() invalid stream %d", stream);
963 return BAD_VALUE;
964 }
965 pid_t caller = IPCThreadState::self()->getCallingPid();
966 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
967 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
968 return PERMISSION_DENIED;
969 }
970
971 return NO_ERROR;
972}
973
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800974status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
975 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976{
977 // check calling permissions
978 if (!settingsAllowed()) {
979 return PERMISSION_DENIED;
980 }
981
Eric Laurent223fd5c2014-11-11 13:43:36 -0800982 status_t status = checkStreamType(stream);
983 if (status != NO_ERROR) {
984 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800986 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987
988 AutoMutex lock(mLock);
989 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700990 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 thread = checkPlaybackThread_l(output);
992 if (thread == NULL) {
993 return BAD_VALUE;
994 }
995 }
996
997 mStreamTypes[stream].volume = value;
998
999 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001001 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 }
1003 } else {
1004 thread->setStreamVolume(stream, value);
1005 }
1006
1007 return NO_ERROR;
1008}
1009
Glenn Kastenfff6d712012-01-12 16:38:12 -08001010status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011{
1012 // check calling permissions
1013 if (!settingsAllowed()) {
1014 return PERMISSION_DENIED;
1015 }
1016
Eric Laurent223fd5c2014-11-11 13:43:36 -08001017 status_t status = checkStreamType(stream);
1018 if (status != NO_ERROR) {
1019 return status;
1020 }
1021 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1022
1023 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001024 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 return BAD_VALUE;
1026 }
1027
Eric Laurent93575202011-01-18 18:39:02 -08001028 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001030 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001031 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032
1033 return NO_ERROR;
1034}
1035
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001036float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001038 status_t status = checkStreamType(stream);
1039 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 return 0.0f;
1041 }
1042
1043 AutoMutex lock(mLock);
1044 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001045 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 PlaybackThread *thread = checkPlaybackThread_l(output);
1047 if (thread == NULL) {
1048 return 0.0f;
1049 }
1050 volume = thread->streamVolume(stream);
1051 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001052 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001053 }
1054
1055 return volume;
1056}
1057
Glenn Kastenfff6d712012-01-12 16:38:12 -08001058bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001060 status_t status = checkStreamType(stream);
1061 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 return true;
1063 }
1064
Glenn Kasten6637baa2012-01-09 09:40:36 -08001065 AutoMutex lock(mLock);
1066 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067}
1068
Eric Laurent054d9d32015-04-24 08:48:48 -07001069
1070void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1071{
1072 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1073 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1074 }
1075}
1076
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001077status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001079 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1080 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001081
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 // check calling permissions
1083 if (!settingsAllowed()) {
1084 return PERMISSION_DENIED;
1085 }
1086
Glenn Kasten142f5192014-03-25 17:44:59 -07001087 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1088 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001089 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001090 // result will remain NO_INIT if no audio device is present
1091 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001092 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001093 AutoMutex lock(mHardwareLock);
1094 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1095 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001096 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1097 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001098 // return success if at least one audio device accepts the parameters as not all
1099 // HALs are requested to support all parameters. If no audio device supports the
1100 // requested parameters, the last error is reported.
1101 if (final_result != NO_ERROR) {
1102 final_result = result;
1103 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001104 }
1105 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001106 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001107 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1108 AudioParameter param = AudioParameter(keyValuePairs);
1109 String8 value;
1110 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001111 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1112 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001113 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1114 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001115 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001116 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1117 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001118 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001119 // suspend effects associated with those session IDs
1120 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001121 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001122 thread->setEffectSuspended(FX_IID_AEC,
1123 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001124 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001125 thread->setEffectSuspended(FX_IID_NS,
1126 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001127 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001128 }
1129 }
Eric Laurentbee53372011-08-29 12:42:48 -07001130 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001131 }
1132 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001133 String8 screenState;
1134 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1135 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001136 if (isOff != (AudioFlinger::mScreenState & 1)) {
1137 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001138 }
1139 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001140 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 }
1142
1143 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1144 // and the thread is exited once the lock is released
1145 sp<ThreadBase> thread;
1146 {
1147 Mutex::Autolock _l(mLock);
1148 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001149 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001151 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001152 // indicate output device change to all input threads for pre processing
1153 AudioParameter param = AudioParameter(keyValuePairs);
1154 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001155 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1156 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001157 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001158 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 }
1160 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001161 if (thread != 0) {
1162 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 }
1164 return BAD_VALUE;
1165}
1166
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001167String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001169 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1170 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171
Eric Laurenta4c5a552012-03-29 10:12:40 -07001172 Mutex::Autolock _l(mLock);
1173
Glenn Kasten142f5192014-03-25 17:44:59 -07001174 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001175 String8 out_s8;
1176
Dima Zavin799a70e2011-04-18 16:57:27 -07001177 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001178 String8 s;
1179 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001180 {
1181 AutoMutex lock(mHardwareLock);
1182 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001183 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1184 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001185 mHardwareStatus = AUDIO_HW_IDLE;
1186 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001187 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001188 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001189 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 }
1191
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1193 if (playbackThread != NULL) {
1194 return playbackThread->getParameters(keys);
1195 }
1196 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1197 if (recordThread != NULL) {
1198 return recordThread->getParameters(keys);
1199 }
1200 return String8("");
1201}
1202
Glenn Kastendd8104c2012-07-02 12:42:44 -07001203size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1204 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205{
Eric Laurenta1884f92011-08-23 08:25:03 -07001206 status_t ret = initCheck();
1207 if (ret != NO_ERROR) {
1208 return 0;
1209 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001210 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001211 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001212 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001213 return 0;
1214 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001215
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001216 AutoMutex lock(mHardwareLock);
1217 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001218 audio_config_t config, proposed;
1219 memset(&proposed, 0, sizeof(proposed));
1220 proposed.sample_rate = sampleRate;
1221 proposed.channel_mask = channelMask;
1222 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001223
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001224 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001225 size_t frames;
1226 for (;;) {
1227 // Note: config is currently a const parameter for get_input_buffer_size()
1228 // but we use a copy from proposed in case config changes from the call.
1229 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001230 status_t result = dev->getInputBufferSize(&config, &frames);
1231 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001232 break; // hal success, config is the result
1233 }
1234 // change one parameter of the configuration each iteration to a more "common" value
1235 // to see if the device will support it.
1236 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1237 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1238 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1239 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1240 } else {
1241 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1242 "format %#x, channelMask 0x%X",
1243 sampleRate, format, channelMask);
1244 break; // retries failed, break out of loop with frames == 0.
1245 }
1246 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001247 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001248 if (frames > 0 && config.sample_rate != sampleRate) {
1249 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1250 }
1251 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252}
1253
Glenn Kasten5f972c02014-01-13 09:59:31 -08001254uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 Mutex::Autolock _l(mLock);
1257
1258 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1259 if (recordThread != NULL) {
1260 return recordThread->getInputFramesLost();
1261 }
1262 return 0;
1263}
1264
1265status_t AudioFlinger::setVoiceVolume(float value)
1266{
Eric Laurenta1884f92011-08-23 08:25:03 -07001267 status_t ret = initCheck();
1268 if (ret != NO_ERROR) {
1269 return ret;
1270 }
1271
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 // check calling permissions
1273 if (!settingsAllowed()) {
1274 return PERMISSION_DENIED;
1275 }
1276
1277 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001278 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001279 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001280 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 mHardwareStatus = AUDIO_HW_IDLE;
1282
1283 return ret;
1284}
1285
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001286status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001287 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 Mutex::Autolock _l(mLock);
1290
1291 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1292 if (playbackThread != NULL) {
1293 return playbackThread->getRenderPosition(halFrames, dspFrames);
1294 }
1295
1296 return BAD_VALUE;
1297}
1298
1299void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1300{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001302 if (client == 0) {
1303 return;
1304 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001305 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001306 {
1307 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001308 if (mNotificationClients.indexOfKey(pid) < 0) {
1309 sp<NotificationClient> notificationClient = new NotificationClient(this,
1310 client,
1311 pid);
1312 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313
Eric Laurent021cf962014-05-13 10:18:14 -07001314 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315
Marco Nelissen06b46062014-11-14 07:58:25 -08001316 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001317 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001318 }
1319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320
Eric Laurent021cf962014-05-13 10:18:14 -07001321 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001322 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001323 // the config change is always sent from playback or record threads to avoid deadlock
1324 // with AudioSystem::gLock
1325 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1326 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001329 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1330 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331 }
1332}
1333
1334void AudioFlinger::removeNotificationClient(pid_t pid)
1335{
1336 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001337 {
1338 Mutex::Autolock _cl(mClientLock);
1339 mNotificationClients.removeItem(pid);
1340 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001341
Steve Block3856b092011-10-20 11:56:00 +01001342 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001343 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001344 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001345 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001346 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001347 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001348 if (ref->mPid == pid) {
1349 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001350 mAudioSessionRefs.removeAt(i);
1351 delete ref;
1352 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001353 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001354 } else {
1355 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001356 }
1357 }
1358 if (removed) {
1359 purgeStaleEffects_l();
1360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361}
1362
Eric Laurent73e26b62015-04-27 16:55:58 -07001363void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001364 const sp<AudioIoDescriptor>& ioDesc,
1365 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366{
Eric Laurent021cf962014-05-13 10:18:14 -07001367 Mutex::Autolock _l(mClientLock);
1368 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001370 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1371 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373 }
1374}
1375
Eric Laurent021cf962014-05-13 10:18:14 -07001376// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377void AudioFlinger::removeClient_l(pid_t pid)
1378{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001379 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001380 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 mClients.removeItem(pid);
1382}
1383
Eric Laurent717e1282012-06-29 16:36:52 -07001384// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001385sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1386 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001387{
1388 sp<PlaybackThread> thread;
1389
1390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1391 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1392 ALOG_ASSERT(thread == 0);
1393 thread = mPlaybackThreads.valueAt(i);
1394 }
1395 }
1396
1397 return thread;
1398}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401
1402// ----------------------------------------------------------------------------
1403
1404AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1405 : RefBase(),
1406 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001407 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301409 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1410 heapSize *= 1024;
1411 if (!heapSize) {
1412 heapSize = kClientSharedHeapSizeBytes;
1413 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1414 // invalidated tracks
1415 if (!audioFlinger->isLowRamDevice()) {
1416 heapSize *= kClientSharedHeapSizeMultiplier;
1417 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001418 }
1419 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420}
1421
Eric Laurent021cf962014-05-13 10:18:14 -07001422// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423AudioFlinger::Client::~Client()
1424{
1425 mAudioFlinger->removeClient_l(mPid);
1426}
1427
Glenn Kasten435dbe62012-01-30 10:15:48 -08001428sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429{
1430 return mMemoryDealer;
1431}
1432
1433// ----------------------------------------------------------------------------
1434
1435AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1436 const sp<IAudioFlingerClient>& client,
1437 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001438 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439{
1440}
1441
1442AudioFlinger::NotificationClient::~NotificationClient()
1443{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444}
1445
Glenn Kasten0f11b512014-01-31 16:18:54 -08001446void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447{
1448 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001449 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450}
1451
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452
1453// ----------------------------------------------------------------------------
1454
1455sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001456 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001458 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001459 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001460 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001461 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001462 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001463 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001464 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001465 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001466 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001467 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001468 sp<IMemory>& cblk,
1469 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 status_t *status)
1471{
1472 sp<RecordThread::RecordTrack> recordTrack;
1473 sp<RecordHandle> recordHandle;
1474 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001476 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477
Glenn Kastend776ac62014-05-07 09:16:09 -07001478 cblk.clear();
1479 buffers.clear();
1480
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001481 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001482 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1483 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001484 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001485 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1486 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001487 updatePid = true;
1488 }
1489
1490 if (updatePid) {
1491 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1492 ALOGW_IF(pid != -1 && pid != callingPid,
1493 "%s uid %d pid %d tried to pass itself off as pid %d",
1494 __func__, callingUid, callingPid, pid);
1495 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001496 }
1497
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001499 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001500 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 lStatus = PERMISSION_DENIED;
1502 goto Exit;
1503 }
1504
Glenn Kasten53b5d092014-02-05 10:00:23 -08001505 // further sample rate checks are performed by createRecordTrack_l()
1506 if (sampleRate == 0) {
1507 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1508 lStatus = BAD_VALUE;
1509 goto Exit;
1510 }
1511
Andy Hung6770c6f2015-04-07 13:43:36 -07001512 // we don't yet support anything other than linear PCM
1513 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001514 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001515 lStatus = BAD_VALUE;
1516 goto Exit;
1517 }
1518
Glenn Kasten53b5d092014-02-05 10:00:23 -08001519 // further channel mask checks are performed by createRecordTrack_l()
1520 if (!audio_is_input_channel(channelMask)) {
1521 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
1525
Glenn Kasten05997e22014-03-13 15:08:33 -07001526 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001528 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001529 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001530 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 lStatus = BAD_VALUE;
1532 goto Exit;
1533 }
1534
Eric Laurent021cf962014-05-13 10:18:14 -07001535 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001537 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001538 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 lSessionId = *sessionId;
1543 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001544 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001545 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 if (sessionId != NULL) {
1547 *sessionId = lSessionId;
1548 }
1549 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001550 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001551
Glenn Kasten1879fff2012-07-11 15:36:59 -07001552 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001553 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001554 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001555 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001556
1557 if (lStatus == NO_ERROR) {
1558 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1559 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001560 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001561 if (chain != 0) {
1562 Mutex::Autolock _l(thread->mLock);
1563 thread->addEffectChain_l(chain);
1564 }
1565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 }
Glenn Kastene198c362013-08-13 09:13:36 -07001567
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001568 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001569 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001570 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001571 // Don't hold mClientLock when releasing the reference on the track as the
1572 // destructor will acquire it.
1573 {
1574 Mutex::Autolock _cl(mClientLock);
1575 client.clear();
1576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 goto Exit;
1579 }
1580
Glenn Kastend776ac62014-05-07 09:16:09 -07001581 cblk = recordTrack->getCblk();
1582 buffers = recordTrack->getBuffers();
1583
Glenn Kasten2fc14732013-08-05 14:58:14 -07001584 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586
1587Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001588 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 return recordHandle;
1590}
1591
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001592
1593
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594// ----------------------------------------------------------------------------
1595
Eric Laurenta4c5a552012-03-29 10:12:40 -07001596audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1597{
Eric Laurent44622db2014-08-01 19:00:33 -07001598 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001599 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001600 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001601 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001602 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001603 }
1604 Mutex::Autolock _l(mLock);
1605 return loadHwModule_l(name);
1606}
1607
1608// loadHwModule_l() must be called with AudioFlinger::mLock held
1609audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1610{
1611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1612 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1613 ALOGW("loadHwModule() module %s already loaded", name);
1614 return mAudioHwDevs.keyAt(i);
1615 }
1616 }
1617
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001618 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001619
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001620 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001621 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001622 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001623 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001624 }
1625
1626 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001627 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001628 mHardwareStatus = AUDIO_HW_IDLE;
1629 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001630 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001631 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001632 }
1633
John Grossmanee578c02012-07-23 17:05:46 -07001634 // Check and cache this HAL's level of support for master mute and master
1635 // volume. If this is the first HAL opened, and it supports the get
1636 // methods, use the initial values provided by the HAL as the current
1637 // master mute and volume settings.
1638
1639 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1640 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001641 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001642
1643 if (0 == mAudioHwDevs.size()) {
1644 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001645 float mv;
1646 if (OK == dev->getMasterVolume(&mv)) {
1647 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001648 }
1649
1650 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001651 bool mm;
1652 if (OK == dev->getMasterMute(&mm)) {
1653 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001654 }
1655 }
1656
Eric Laurenta4c5a552012-03-29 10:12:40 -07001657 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001658 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001659 flags = static_cast<AudioHwDevice::Flags>(flags |
1660 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1661 }
1662
1663 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001664 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001665 flags = static_cast<AudioHwDevice::Flags>(flags |
1666 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1667 }
1668
Eric Laurenta4c5a552012-03-29 10:12:40 -07001669 mHardwareStatus = AUDIO_HW_IDLE;
1670 }
1671
Glenn Kastena13cde92016-03-28 15:26:02 -07001672 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001673 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001674
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001675 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001676
1677 return handle;
1678
1679}
1680
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001681// ----------------------------------------------------------------------------
1682
Glenn Kasten3b16c762012-11-14 08:44:39 -08001683uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001684{
1685 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001686 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001687 return thread != NULL ? thread->sampleRate() : 0;
1688}
1689
Glenn Kastene33054e2012-11-14 12:54:39 -08001690size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001691{
1692 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001693 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001694 return thread != NULL ? thread->frameCountHAL() : 0;
1695}
1696
1697// ----------------------------------------------------------------------------
1698
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001699status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1700{
1701 uid_t uid = IPCThreadState::self()->getCallingUid();
1702 if (uid != AID_SYSTEM) {
1703 return PERMISSION_DENIED;
1704 }
1705 Mutex::Autolock _l(mLock);
1706 if (mIsDeviceTypeKnown) {
1707 return INVALID_OPERATION;
1708 }
1709 mIsLowRamDevice = isLowRamDevice;
1710 mIsDeviceTypeKnown = true;
1711 return NO_ERROR;
1712}
1713
Eric Laurent93c3d412014-08-01 14:48:35 -07001714audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1715{
1716 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001717
1718 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1719 if (index >= 0) {
1720 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1721 mHwAvSyncIds.valueAt(index), sessionId);
1722 return mHwAvSyncIds.valueAt(index);
1723 }
1724
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001725 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001726 if (dev == NULL) {
1727 return AUDIO_HW_SYNC_INVALID;
1728 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001729 String8 reply;
1730 AudioParameter param;
1731 if (dev->getParameters(String8(AUDIO_PARAMETER_HW_AV_SYNC), &reply) == OK) {
1732 param = AudioParameter(reply);
1733 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001734
1735 int value;
1736 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1737 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1738 return AUDIO_HW_SYNC_INVALID;
1739 }
1740
1741 // allow only one session for a given HW A/V sync ID.
1742 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1743 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1744 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1745 value, mHwAvSyncIds.keyAt(i));
1746 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001747 break;
1748 }
1749 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001750
1751 mHwAvSyncIds.add(sessionId, value);
1752
1753 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1754 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1755 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001756 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001757 AudioParameter param = AudioParameter();
1758 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1759 thread->setParameters(param.toString());
1760 break;
1761 }
1762 }
1763
1764 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1765 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001766}
1767
Eric Laurent72e3f392015-05-20 14:43:50 -07001768status_t AudioFlinger::systemReady()
1769{
1770 Mutex::Autolock _l(mLock);
1771 ALOGI("%s", __FUNCTION__);
1772 if (mSystemReady) {
1773 ALOGW("%s called twice", __FUNCTION__);
1774 return NO_ERROR;
1775 }
1776 mSystemReady = true;
1777 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1778 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1779 thread->systemReady();
1780 }
1781 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1782 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1783 thread->systemReady();
1784 }
1785 return NO_ERROR;
1786}
1787
Eric Laurentfa90e842014-10-17 18:12:31 -07001788// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1789void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1790{
1791 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1792 if (index >= 0) {
1793 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1794 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1795 AudioParameter param = AudioParameter();
1796 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1797 thread->setParameters(param.toString());
1798 }
1799}
1800
1801
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001802// ----------------------------------------------------------------------------
1803
Eric Laurent83b88082014-06-20 18:31:16 -07001804
1805sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001806 audio_io_handle_t *output,
1807 audio_config_t *config,
1808 audio_devices_t devices,
1809 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001810 audio_output_flags_t flags)
1811{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001812 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001813 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001814 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001815 }
1816
Eric Laurentcf2c0212014-07-25 16:20:43 -07001817 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001818 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1819 } else {
1820 // Audio Policy does not currently request a specific output handle.
1821 // If this is ever needed, see openInput_l() for example code.
1822 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1823 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001824 }
Eric Laurent83b88082014-06-20 18:31:16 -07001825
1826 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1827
Eric Laurent83b88082014-06-20 18:31:16 -07001828 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001829 // This if statement allows overriding the audio policy settings
1830 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1831 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1832 // Check only for Normal Mixing mode
1833 if (kEnableExtendedPrecision) {
1834 // Specify format (uncomment one below to choose)
1835 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1836 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1837 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1838 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001839 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001840 }
1841 if (kEnableExtendedChannels) {
1842 // Specify channel mask (uncomment one below to choose)
1843 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1844 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1845 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1846 }
Eric Laurent83b88082014-06-20 18:31:16 -07001847 }
1848
Phil Burk062e67a2015-02-11 13:40:50 -08001849 AudioStreamOut *outputStream = NULL;
1850 status_t status = outHwDev->openOutputStream(
1851 &outputStream,
1852 *output,
1853 devices,
1854 flags,
1855 config,
1856 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001857
1858 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001859
Phil Burk062e67a2015-02-11 13:40:50 -08001860 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001861
1862 PlaybackThread *thread;
1863 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001864 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001865 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001866 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1867 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001868 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001869 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001870 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001871 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001872 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001873 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001874 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001875 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001876 return thread;
1877 }
1878
1879 return 0;
1880}
1881
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882status_t AudioFlinger::openOutput(audio_module_handle_t module,
1883 audio_io_handle_t *output,
1884 audio_config_t *config,
1885 audio_devices_t *devices,
1886 const String8& address,
1887 uint32_t *latencyMs,
1888 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889{
Phil Burk062e67a2015-02-11 13:40:50 -08001890 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001891 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 (devices != NULL) ? *devices : 0,
1893 config->sample_rate,
1894 config->format,
1895 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001896 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897
Eric Laurentcf2c0212014-07-25 16:20:43 -07001898 if (*devices == AUDIO_DEVICE_NONE) {
1899 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001901
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 Mutex::Autolock _l(mLock);
1903
Eric Laurentcf2c0212014-07-25 16:20:43 -07001904 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001905 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001906 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907
1908 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001909 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001910
1911 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001912 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001913 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001914 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001915
1916 AutoMutex lock(mHardwareLock);
1917 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001918 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001919 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001920 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001921 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 }
1923
Eric Laurentcf2c0212014-07-25 16:20:43 -07001924 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925}
1926
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001927audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1928 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929{
1930 Mutex::Autolock _l(mLock);
1931 MixerThread *thread1 = checkMixerThread_l(output1);
1932 MixerThread *thread2 = checkMixerThread_l(output2);
1933
1934 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001935 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1936 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001937 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939
Glenn Kasteneeecb982016-02-26 10:44:04 -08001940 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001941 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 thread->addOutputTrack(thread2);
1943 mPlaybackThreads.add(id, thread);
1944 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001945 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 return id;
1947}
1948
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001949status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950{
Glenn Kastend96c5722012-04-25 13:44:49 -07001951 return closeOutput_nonvirtual(output);
1952}
1953
1954status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1955{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 // keep strong reference on the playback thread so that
1957 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001958 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 {
1960 Mutex::Autolock _l(mLock);
1961 thread = checkPlaybackThread_l(output);
1962 if (thread == NULL) {
1963 return BAD_VALUE;
1964 }
1965
Steve Block3856b092011-10-20 11:56:00 +01001966 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001968 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001970 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001971 DuplicatingThread *dupThread =
1972 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001974 }
1975 }
1976 }
1977
1978
1979 mPlaybackThreads.removeItem(output);
1980 // save all effects to the default thread
1981 if (mPlaybackThreads.size()) {
1982 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1983 if (dstThread != NULL) {
1984 // audioflinger lock is held here so the acquisition order of thread locks does not
1985 // matter
1986 Mutex::Autolock _dl(dstThread->mLock);
1987 Mutex::Autolock _sl(thread->mLock);
1988 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1989 for (size_t i = 0; i < effectChains.size(); i ++) {
1990 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991 }
1992 }
1993 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001994 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1995 ioDesc->mIoHandle = output;
1996 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 }
1998 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001999 // The thread entity (active unit of execution) is no longer running here,
2000 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001
Eric Laurentf6870ae2015-05-08 10:50:03 -07002002 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002003 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 }
Eric Laurent83b88082014-06-20 18:31:16 -07002005
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 return NO_ERROR;
2007}
2008
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002009void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002010{
2011 AudioStreamOut *out = thread->clearOutput();
2012 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2013 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002014 delete out;
2015}
2016
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002017void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002018{
2019 mPlaybackThreads.removeItem(thread->mId);
2020 thread->exit();
2021 closeOutputFinish(thread);
2022}
2023
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002024status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025{
2026 Mutex::Autolock _l(mLock);
2027 PlaybackThread *thread = checkPlaybackThread_l(output);
2028
2029 if (thread == NULL) {
2030 return BAD_VALUE;
2031 }
2032
Steve Block3856b092011-10-20 11:56:00 +01002033 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 thread->suspend();
2035
2036 return NO_ERROR;
2037}
2038
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002039status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040{
2041 Mutex::Autolock _l(mLock);
2042 PlaybackThread *thread = checkPlaybackThread_l(output);
2043
2044 if (thread == NULL) {
2045 return BAD_VALUE;
2046 }
2047
Steve Block3856b092011-10-20 11:56:00 +01002048 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049
2050 thread->restore();
2051
2052 return NO_ERROR;
2053}
2054
Eric Laurentcf2c0212014-07-25 16:20:43 -07002055status_t AudioFlinger::openInput(audio_module_handle_t module,
2056 audio_io_handle_t *input,
2057 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002058 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002059 const String8& address,
2060 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002061 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062{
Eric Laurent83b88082014-06-20 18:31:16 -07002063 Mutex::Autolock _l(mLock);
2064
Glenn Kastene7d66712015-03-05 13:46:52 -08002065 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002066 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002067 }
2068
Glenn Kastene7d66712015-03-05 13:46:52 -08002069 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002070
2071 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002072 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002073 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002074 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002076 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002077}
Dima Zavin799a70e2011-04-18 16:57:27 -07002078
Eric Laurent83b88082014-06-20 18:31:16 -07002079sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002080 audio_io_handle_t *input,
2081 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002082 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002083 const String8& address,
2084 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002085 audio_input_flags_t flags)
2086{
Glenn Kastene7d66712015-03-05 13:46:52 -08002087 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002088 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002089 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002090 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002091 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002092
Glenn Kasteneeecb982016-02-26 10:44:04 -08002093 // Audio Policy can request a specific handle for hardware hotword.
2094 // The goal here is not to re-open an already opened input.
2095 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002096 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002097 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2098 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2099 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2100 return 0;
2101 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2102 // This should not happen in a transient state with current design.
2103 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2104 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002105 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002106
Eric Laurentcf2c0212014-07-25 16:20:43 -07002107 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002108 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002109 sp<StreamInHalInterface> inStream;
2110 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002111 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002112 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002113 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002114 inStream.get(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002115 halconfig.sample_rate,
2116 halconfig.format,
2117 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002118 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002119 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002121 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002122 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002123 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002124 audio_is_linear_pcm(config->format) &&
2125 audio_is_linear_pcm(halconfig.format) &&
2126 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002127 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2128 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002129 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002130 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002131 inStream.clear();
2132 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002133 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002134 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 }
2136
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002137 if (status == NO_ERROR && inStream != 0) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002138
Glenn Kasten46909e72013-02-26 09:20:22 -08002139#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002140 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2141 // or (re-)create if current Pipe is idle and does not match the new format
2142 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002143 enum {
2144 TEE_SINK_NO, // don't copy input
2145 TEE_SINK_NEW, // copy input using a new pipe
2146 TEE_SINK_OLD, // copy input using an existing pipe
2147 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002148 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2149 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002150 if (!mTeeSinkInputEnabled) {
2151 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002152 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002153 kind = TEE_SINK_NO;
2154 } else if (mRecordTeeSink == 0) {
2155 kind = TEE_SINK_NEW;
2156 } else if (mRecordTeeSink->getStrongCount() != 1) {
2157 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002158 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002159 kind = TEE_SINK_OLD;
2160 } else {
2161 kind = TEE_SINK_NEW;
2162 }
2163 switch (kind) {
2164 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002165 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002166 size_t numCounterOffers = 0;
2167 const NBAIO_Format offers[1] = {format};
2168 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2169 ALOG_ASSERT(index == 0);
2170 PipeReader *pipeReader = new PipeReader(*pipe);
2171 numCounterOffers = 0;
2172 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2173 ALOG_ASSERT(index == 0);
2174 mRecordTeeSink = pipe;
2175 mRecordTeeSource = pipeReader;
2176 teeSink = pipe;
2177 }
2178 break;
2179 case TEE_SINK_OLD:
2180 teeSink = mRecordTeeSink;
2181 break;
2182 case TEE_SINK_NO:
2183 default:
2184 break;
2185 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002186#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002187
Eric Laurent05067782016-06-01 18:27:28 -07002188 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002189
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002190 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002191 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002192 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002193 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002194 inputStream,
2195 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002196 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002197 devices,
2198 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002199#ifdef TEE_SINK
2200 , teeSink
2201#endif
2202 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002203 mRecordThreads.add(*input, thread);
2204 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002205 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 }
2207
Eric Laurentcf2c0212014-07-25 16:20:43 -07002208 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209 return 0;
2210}
2211
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002212status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213{
Glenn Kastend96c5722012-04-25 13:44:49 -07002214 return closeInput_nonvirtual(input);
2215}
2216
2217status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2218{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 // keep strong reference on the record thread so that
2220 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002221 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 {
2223 Mutex::Autolock _l(mLock);
2224 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002225 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 return BAD_VALUE;
2227 }
2228
Steve Block3856b092011-10-20 11:56:00 +01002229 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002230
2231 // If we still have effect chains, it means that a client still holds a handle
2232 // on at least one effect. We must either move the chain to an existing thread with the
2233 // same session ID or put it aside in case a new record thread is opened for a
2234 // new capture on the same session
2235 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002236 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002237 Mutex::Autolock _sl(thread->mLock);
2238 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002239 // Note: maximum one chain per record thread
2240 if (effectChains.size() != 0) {
2241 chain = effectChains[0];
2242 }
2243 }
2244 if (chain != 0) {
2245 // first check if a record thread is already opened with a client on the same session.
2246 // This should only happen in case of overlap between one thread tear down and the
2247 // creation of its replacement
2248 size_t i;
2249 for (i = 0; i < mRecordThreads.size(); i++) {
2250 sp<RecordThread> t = mRecordThreads.valueAt(i);
2251 if (t == thread) {
2252 continue;
2253 }
2254 if (t->hasAudioSession(chain->sessionId()) != 0) {
2255 Mutex::Autolock _l(t->mLock);
2256 ALOGV("closeInput() found thread %d for effect session %d",
2257 t->id(), chain->sessionId());
2258 t->addEffectChain_l(chain);
2259 break;
2260 }
2261 }
2262 // put the chain aside if we could not find a record thread with the same session id.
2263 if (i == mRecordThreads.size()) {
2264 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002265 }
2266 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002267 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2268 ioDesc->mIoHandle = input;
2269 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 mRecordThreads.removeItem(input);
2271 }
Eric Laurent83b88082014-06-20 18:31:16 -07002272 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2273 // we have a different lock for notification client
2274 closeInputFinish(thread);
2275 return NO_ERROR;
2276}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002278void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002279{
2280 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002281 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002282 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002283 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002284 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002285}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002287void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002288{
2289 mRecordThreads.removeItem(thread->mId);
2290 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291}
2292
Glenn Kastend2304db2014-02-03 07:40:31 -08002293status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294{
2295 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002296 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297
2298 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2299 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002300 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302
2303 return NO_ERROR;
2304}
2305
2306
Glenn Kasteneeecb982016-02-26 10:44:04 -08002307audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308{
Glenn Kasten9d003132016-04-06 14:38:09 -07002309 // This is a binder API, so a malicious client could pass in a bad parameter.
2310 // Check for that before calling the internal API nextUniqueId().
2311 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2312 ALOGE("newAudioUniqueId invalid use %d", use);
2313 return AUDIO_UNIQUE_ID_ALLOCATE;
2314 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002315 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316}
2317
Glenn Kastend848eb42016-03-08 13:42:11 -08002318void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002319{
2320 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002321 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002322 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2323 if (pid != -1 && (caller == getpid_cached)) {
2324 caller = pid;
2325 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002326
Eric Laurent021cf962014-05-13 10:18:14 -07002327 {
2328 Mutex::Autolock _cl(mClientLock);
2329 // Ignore requests received from processes not known as notification client. The request
2330 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2331 // called from a different pid leaving a stale session reference. Also we don't know how
2332 // to clear this reference if the client process dies.
2333 if (mNotificationClients.indexOfKey(caller) < 0) {
2334 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2335 return;
2336 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002337 }
2338
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002339 size_t num = mAudioSessionRefs.size();
2340 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002341 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002342 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2343 ref->mCnt++;
2344 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002345 return;
2346 }
2347 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002348 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2349 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002350}
2351
Glenn Kastend848eb42016-03-08 13:42:11 -08002352void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002353{
2354 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002355 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002356 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2357 if (pid != -1 && (caller == getpid_cached)) {
2358 caller = pid;
2359 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002360 size_t num = mAudioSessionRefs.size();
2361 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002362 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002363 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2364 ref->mCnt--;
2365 ALOGV(" decremented refcount to %d", ref->mCnt);
2366 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002367 mAudioSessionRefs.removeAt(i);
2368 delete ref;
2369 purgeStaleEffects_l();
2370 }
2371 return;
2372 }
2373 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002374 // If the caller is mediaserver it is likely that the session being released was acquired
2375 // on behalf of a process not in notification clients and we ignore the warning.
2376 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002377}
2378
2379void AudioFlinger::purgeStaleEffects_l() {
2380
Steve Block3856b092011-10-20 11:56:00 +01002381 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002382
2383 Vector< sp<EffectChain> > chains;
2384
2385 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2386 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2387 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2388 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002389 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2390 chains.push(ec);
2391 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002392 }
2393 }
2394 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2395 sp<RecordThread> t = mRecordThreads.valueAt(i);
2396 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2397 sp<EffectChain> ec = t->mEffectChains[j];
2398 chains.push(ec);
2399 }
2400 }
2401
2402 for (size_t i = 0; i < chains.size(); i++) {
2403 sp<EffectChain> ec = chains[i];
2404 int sessionid = ec->sessionId();
2405 sp<ThreadBase> t = ec->mThread.promote();
2406 if (t == 0) {
2407 continue;
2408 }
2409 size_t numsessionrefs = mAudioSessionRefs.size();
2410 bool found = false;
2411 for (size_t k = 0; k < numsessionrefs; k++) {
2412 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002413 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002414 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002415 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002416 found = true;
2417 break;
2418 }
2419 }
2420 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002421 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002422 // remove all effects from the chain
2423 while (ec->mEffects.size()) {
2424 sp<EffectModule> effect = ec->mEffects[0];
2425 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002426 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002427 if (effect->purgeHandles()) {
2428 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002429 }
2430 AudioSystem::unregisterEffect(effect->id());
2431 }
2432 }
2433 }
2434 return;
2435}
2436
Glenn Kasteneeecb982016-02-26 10:44:04 -08002437// checkThread_l() must be called with AudioFlinger::mLock held
2438AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2439{
2440 ThreadBase *thread = NULL;
2441 switch (audio_unique_id_get_use(ioHandle)) {
2442 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2443 thread = checkPlaybackThread_l(ioHandle);
2444 break;
2445 case AUDIO_UNIQUE_ID_USE_INPUT:
2446 thread = checkRecordThread_l(ioHandle);
2447 break;
2448 default:
2449 break;
2450 }
2451 return thread;
2452}
2453
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002455AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456{
Glenn Kastena1117922012-01-26 10:53:32 -08002457 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458}
2459
2460// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002461AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462{
2463 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002464 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465}
2466
2467// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002468AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469{
Glenn Kastena1117922012-01-26 10:53:32 -08002470 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471}
2472
Glenn Kasteneeecb982016-02-26 10:44:04 -08002473audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474{
Glenn Kasten9d003132016-04-06 14:38:09 -07002475 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002476 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002477 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2478 for (int retry = 0; retry < maxRetries; retry++) {
2479 // The cast allows wraparound from max positive to min negative instead of abort
2480 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2481 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2482 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2483 // allow wrap by skipping 0 and -1 for session ids
2484 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2485 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2486 return (audio_unique_id_t) (base | use);
2487 }
2488 }
2489 // We have no way of recovering from wraparound
2490 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2491 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492}
2493
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002494AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002495{
2496 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2497 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002498 if(thread->isDuplicating()) {
2499 continue;
2500 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002501 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002502 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002503 return thread;
2504 }
2505 }
2506 return NULL;
2507}
2508
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002509audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002510{
2511 PlaybackThread *thread = primaryPlaybackThread_l();
2512
2513 if (thread == NULL) {
2514 return 0;
2515 }
2516
Eric Laurentf1c04f92012-08-28 14:26:53 -07002517 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002518}
2519
Glenn Kastena7335632016-06-09 17:09:53 -07002520AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2521{
2522 size_t minFrameCount = 0;
2523 PlaybackThread *minThread = NULL;
2524 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2525 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2526 if (!thread->isDuplicating()) {
2527 size_t frameCount = thread->frameCountHAL();
2528 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2529 (frameCount == minFrameCount && thread->hasFastMixer() &&
2530 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2531 minFrameCount = frameCount;
2532 minThread = thread;
2533 }
2534 }
2535 }
2536 return minThread;
2537}
2538
Eric Laurenta011e352012-03-29 15:51:43 -07002539sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002540 audio_session_t triggerSession,
2541 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002542 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002543 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002544{
2545 Mutex::Autolock _l(mLock);
2546
2547 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2548 status_t playStatus = NAME_NOT_FOUND;
2549 status_t recStatus = NAME_NOT_FOUND;
2550 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2551 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2552 if (playStatus == NO_ERROR) {
2553 return event;
2554 }
2555 }
2556 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2557 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2558 if (recStatus == NO_ERROR) {
2559 return event;
2560 }
2561 }
2562 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2563 mPendingSyncEvents.add(event);
2564 } else {
2565 ALOGV("createSyncEvent() invalid event %d", event->type());
2566 event.clear();
2567 }
2568 return event;
2569}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002570
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571// ----------------------------------------------------------------------------
2572// Effect management
2573// ----------------------------------------------------------------------------
2574
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002575sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2576 return mEffectsFactoryHal;
2577}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578
Glenn Kastenf587ba52012-01-26 16:25:10 -08002579status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580{
2581 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002582 if (mEffectsFactoryHal.get()) {
2583 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2584 } else {
2585 return -ENODEV;
2586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587}
2588
Glenn Kastenf587ba52012-01-26 16:25:10 -08002589status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590{
2591 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002592 if (mEffectsFactoryHal.get()) {
2593 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2594 } else {
2595 return -ENODEV;
2596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597}
2598
Glenn Kasten5e92a782012-01-30 07:40:52 -08002599status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002600 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601{
2602 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002603 if (mEffectsFactoryHal.get()) {
2604 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2605 } else {
2606 return -ENODEV;
2607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608}
2609
2610
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002611sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 effect_descriptor_t *pDesc,
2613 const sp<IEffectClient>& effectClient,
2614 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002615 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002616 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002617 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 status_t *status,
2619 int *id,
2620 int *enabled)
2621{
2622 status_t lStatus = NO_ERROR;
2623 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002626 pid_t pid = IPCThreadState::self()->getCallingPid();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002627 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2628 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629
2630 if (pDesc == NULL) {
2631 lStatus = BAD_VALUE;
2632 goto Exit;
2633 }
2634
Eric Laurent84e9a102010-09-23 16:10:16 -07002635 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002636 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002637 lStatus = PERMISSION_DENIED;
2638 goto Exit;
2639 }
2640
Dima Zavinfce7a472011-04-19 22:30:36 -07002641 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002642 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002643 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002644 lStatus = PERMISSION_DENIED;
2645 goto Exit;
2646 }
2647
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002648 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002649 lStatus = NO_INIT;
2650 goto Exit;
2651 }
2652
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002654 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002656 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002658 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 goto Exit;
2660 }
2661 } else {
2662 // if uuid is not specified, look for an available implementation
2663 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002664 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002665 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666 lStatus = BAD_VALUE;
2667 goto Exit;
2668 }
2669 uint32_t numEffects = 0;
2670 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002671 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 bool found = false;
2673
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002674 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002676 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 goto Exit;
2678 }
2679 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002680 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002682 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 continue;
2684 }
2685 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2686 // If matching type found save effect descriptor. If the session is
2687 // 0 and the effect is not auxiliary, continue enumeration in case
2688 // an auxiliary version of this effect type is available
2689 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002690 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002691 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2693 break;
2694 }
2695 }
2696 }
2697 if (!found) {
2698 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002699 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 goto Exit;
2701 }
2702 // For same effect type, chose auxiliary version over insert version if
2703 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002704 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002706 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 }
2708 }
2709
2710 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002711 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2713 lStatus = INVALID_OPERATION;
2714 goto Exit;
2715 }
2716
Eric Laurent59255e42011-07-27 19:49:51 -07002717 // check recording permission for visualizer
2718 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002719 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002720 lStatus = PERMISSION_DENIED;
2721 goto Exit;
2722 }
2723
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002725 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002726 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002727 // if the output returned by getOutputForEffect() is removed before we lock the
2728 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2729 // and we will exit safely
2730 io = AudioSystem::getOutputForEffect(&desc);
2731 ALOGV("createEffect got output %d", io);
2732 }
2733
2734 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735
2736 // If output is not specified try to find a matching audio session ID in one of the
2737 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002738 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2739 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002740 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002741 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002742 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2743 // output must be specified by AudioPolicyManager when using session
2744 // AUDIO_SESSION_OUTPUT_STAGE
2745 lStatus = BAD_VALUE;
2746 goto Exit;
2747 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002748 // look for the thread where the specified audio session is present
2749 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2750 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2751 io = mPlaybackThreads.keyAt(i);
2752 break;
2753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002755 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002756 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2757 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2758 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002759 break;
2760 }
2761 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002762 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002763 // If no output thread contains the requested session ID, default to
2764 // first output. The effect chain will be moved to the correct output
2765 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002766 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002767 io = mPlaybackThreads.keyAt(0);
2768 }
Steve Block3856b092011-10-20 11:56:00 +01002769 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002770 }
2771 ThreadBase *thread = checkRecordThread_l(io);
2772 if (thread == NULL) {
2773 thread = checkPlaybackThread_l(io);
2774 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002775 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002776 lStatus = BAD_VALUE;
2777 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002778 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002779 } else {
2780 // Check if one effect chain was awaiting for an effect to be created on this
2781 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002782 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002783 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002784 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002785 thread->addEffectChain_l(chain);
2786 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002788
Eric Laurent021cf962014-05-13 10:18:14 -07002789 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002791 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002792 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2793 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 if (handle != 0 && id != NULL) {
2795 *id = handle->id();
2796 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002797 if (handle == 0) {
2798 // remove local strong reference to Client with mClientLock held
2799 Mutex::Autolock _cl(mClientLock);
2800 client.clear();
2801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 }
2803
2804Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002805 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 return handle;
2807}
2808
Glenn Kastend848eb42016-03-08 13:42:11 -08002809status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002810 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002811{
Steve Block3856b092011-10-20 11:56:00 +01002812 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002813 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002814 Mutex::Autolock _l(mLock);
2815 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002816 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002817 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 }
Eric Laurentde070132010-07-13 04:45:46 -07002819 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2820 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002821 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002822 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 }
Eric Laurentde070132010-07-13 04:45:46 -07002824 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2825 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002826 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002827 return BAD_VALUE;
2828 }
2829
2830 Mutex::Autolock _dl(dstThread->mLock);
2831 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002832 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833}
2834
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002835// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002836status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002837 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002838 AudioFlinger::PlaybackThread *dstThread,
2839 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002840{
Steve Block3856b092011-10-20 11:56:00 +01002841 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002842 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002843
Eric Laurent59255e42011-07-27 19:49:51 -07002844 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002845 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002846 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002847 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002848 return INVALID_OPERATION;
2849 }
2850
Eric Laurent4c415062016-06-17 16:14:16 -07002851 // Check whether the destination thread and all effects in the chain are compatible
2852 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002853 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002854 " destination thread %p is not compatible with effects in the chain",
2855 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002856 return INVALID_OPERATION;
2857 }
2858
Eric Laurent39e94f82010-07-28 01:32:47 -07002859 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002860 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002861 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002862 // removed.
2863 srcThread->removeEffectChain_l(chain);
2864
2865 // transfer all effects one by one so that new effect chain is created on new thread with
2866 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002867 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002868 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002869 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002870 Vector< sp<EffectModule> > removed;
2871 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002872 while (effect != 0) {
2873 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002874 removed.add(effect);
2875 status = dstThread->addEffect_l(effect);
2876 if (status != NO_ERROR) {
2877 break;
2878 }
Eric Laurentec35a142011-10-05 17:42:25 -07002879 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2880 if (effect->state() == EffectModule::ACTIVE ||
2881 effect->state() == EffectModule::STOPPING) {
2882 effect->start();
2883 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002884 // if the move request is not received from audio policy manager, the effect must be
2885 // re-registered with the new strategy and output
2886 if (dstChain == 0) {
2887 dstChain = effect->chain().promote();
2888 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002889 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002890 status = NO_INIT;
2891 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002892 }
2893 strategy = dstChain->strategy();
2894 }
2895 if (reRegister) {
2896 AudioSystem::unregisterEffect(effect->id());
2897 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002898 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002899 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002900 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002901 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002902 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002903 }
Eric Laurentde070132010-07-13 04:45:46 -07002904 effect = chain->getEffectFromId_l(0);
2905 }
2906
Eric Laurent5baf2af2013-09-12 17:37:00 -07002907 if (status != NO_ERROR) {
2908 for (size_t i = 0; i < removed.size(); i++) {
2909 srcThread->addEffect_l(removed[i]);
2910 if (dstChain != 0 && reRegister) {
2911 AudioSystem::unregisterEffect(removed[i]->id());
2912 AudioSystem::registerEffect(&removed[i]->desc(),
2913 srcThread->id(),
2914 strategy,
2915 sessionId,
2916 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002917 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002918 }
2919 }
2920 }
2921
2922 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923}
2924
Eric Laurent5baf2af2013-09-12 17:37:00 -07002925bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002926{
2927 if (mGlobalEffectEnableTime != 0 &&
2928 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2929 return true;
2930 }
2931
2932 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2933 sp<EffectChain> ec =
2934 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002935 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002936 return true;
2937 }
2938 }
2939 return false;
2940}
2941
Eric Laurent5baf2af2013-09-12 17:37:00 -07002942void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002943{
2944 Mutex::Autolock _l(mLock);
2945
2946 mGlobalEffectEnableTime = systemTime();
2947
2948 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2949 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2950 if (t->mType == ThreadBase::OFFLOAD) {
2951 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2952 }
2953 }
2954
2955}
2956
Eric Laurentaaa44472014-09-12 17:41:50 -07002957status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2958{
Glenn Kastend848eb42016-03-08 13:42:11 -08002959 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002960 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002961 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002962 if (index >= 0) {
2963 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2964 return ALREADY_EXISTS;
2965 }
2966 mOrphanEffectChains.add(session, chain);
2967 return NO_ERROR;
2968}
2969
2970sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2971{
2972 sp<EffectChain> chain;
2973 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002974 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002975 if (index >= 0) {
2976 chain = mOrphanEffectChains.valueAt(index);
2977 mOrphanEffectChains.removeItemsAt(index);
2978 }
2979 return chain;
2980}
2981
2982bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2983{
2984 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002985 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002986 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002987 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002988 if (index >= 0) {
2989 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2990 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002991 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002992 mOrphanEffectChains.removeItemsAt(index);
2993 }
2994 return true;
2995 }
2996 return false;
2997}
2998
2999
Glenn Kastenda6ef132013-01-10 12:31:01 -08003000struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003001#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3002 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003003};
3004
3005int comparEntry(const void *p1, const void *p2)
3006{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003007 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003008}
3009
Glenn Kasten46909e72013-02-26 09:20:22 -08003010#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003011void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012{
Eric Laurent81784c32012-11-19 14:55:58 -08003013 NBAIO_Source *teeSource = source.get();
3014 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003015 // .wav rotation
3016 // There is a benign race condition if 2 threads call this simultaneously.
3017 // They would both traverse the directory, but the result would simply be
3018 // failures at unlink() which are ignored. It's also unlikely since
3019 // normally dumpsys is only done by bugreport or from the command line.
3020 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003021 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003022 size_t teePathLen = strlen(teePath);
3023 DIR *dir = opendir(teePath);
3024 teePath[teePathLen++] = '/';
3025 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003026#define TEE_MAX_SORT 20 // number of entries to sort
3027#define TEE_MAX_KEEP 10 // number of entries to keep
3028 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003029 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003030 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003031 struct dirent de;
3032 struct dirent *result = NULL;
3033 int rc = readdir_r(dir, &de, &result);
3034 if (rc != 0) {
3035 ALOGW("readdir_r failed %d", rc);
3036 break;
3037 }
3038 if (result == NULL) {
3039 break;
3040 }
3041 if (result != &de) {
3042 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3043 break;
3044 }
3045 // ignore non .wav file entries
3046 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003047 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003048 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3049 continue;
3050 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003051 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003052 }
3053 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003054 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003055 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003056 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3057 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003058 (void) unlink(teePath);
3059 }
3060 }
3061 } else {
3062 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003063 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003064 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003065 }
3066 }
Eric Laurent81784c32012-11-19 14:55:58 -08003067 char teeTime[16];
3068 struct timeval tv;
3069 gettimeofday(&tv, NULL);
3070 struct tm tm;
3071 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003072 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3073 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3074 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3075 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003076 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003077 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003078 char wavHeader[44];
3079 memcpy(wavHeader,
3080 "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",
3081 sizeof(wavHeader));
3082 NBAIO_Format format = teeSource->format();
3083 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003084 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003085 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003086 wavHeader[22] = channelCount; // number of channels
3087 wavHeader[24] = sampleRate; // sample rate
3088 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003089 wavHeader[32] = frameSize; // block alignment
3090 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003091 write(teeFd, wavHeader, sizeof(wavHeader));
3092 size_t total = 0;
3093 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003094#define TEE_SINK_READ 1024 // frames per I/O operation
3095 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003096 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003097 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003098 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003099 bool wasFirstRead = firstRead;
3100 firstRead = false;
3101 if (actual <= 0) {
3102 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3103 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003104 }
Eric Laurent81784c32012-11-19 14:55:58 -08003105 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003106 }
Eric Laurent81784c32012-11-19 14:55:58 -08003107 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003108 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003109 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003110 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003111 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003112 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003113 uint32_t temp = 44 + total * frameSize - 8;
3114 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003115 write(teeFd, &temp, sizeof(temp));
3116 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003117 temp = total * frameSize;
3118 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003119 write(teeFd, &temp, sizeof(temp));
3120 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003121 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003122 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003123 }
Eric Laurent59255e42011-07-27 19:49:51 -07003124 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003125 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003126 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003127 }
Eric Laurent59255e42011-07-27 19:49:51 -07003128 }
3129 }
3130}
Glenn Kasten46909e72013-02-26 09:20:22 -08003131#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003132
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133// ----------------------------------------------------------------------------
3134
3135status_t AudioFlinger::onTransact(
3136 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3137{
3138 return BnAudioFlinger::onTransact(code, data, reply, flags);
3139}
3140
Glenn Kasten63238ef2015-03-02 15:50:29 -08003141} // namespace android