blob: 2d05a6d775f9f5830fca039fbbef8859deece23b [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"
Glenn Kasten44deb052012-02-05 18:09:08 -080047#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Andy Hung6770c6f2015-04-07 13:43:36 -070049#include <media/AudioResamplerPublic.h>
50
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070052#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070053#include <audio_effects/effect_ns.h>
54#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Glenn Kasten3b21c502011-12-15 09:52:39 -080056#include <audio_utils/primitives.h>
57
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080059
Glenn Kasten9e58b552013-01-18 15:09:48 -080060#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070061#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080062#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070064#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070066#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080067
Mathias Agopian65ab4712010-07-14 17:59:35 -070068// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
John Grossman1c345192012-03-27 14:00:17 -070070// Note: the following macro is used for extremely verbose logging message. In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well. Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on. Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
Eric Laurentde070132010-07-13 04:45:46 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Glenn Kastenec1d6b52011-12-12 09:04:45 -080085static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
86static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070087static const char kClientLockedString[] = "Client lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Glenn Kasten58912562012-04-03 10:45:00 -070089
John Grossman4ff14ba2012-02-08 16:37:41 -080090nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080091
Eric Laurent81784c32012-11-19 14:55:58 -080092uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070093
Glenn Kasten46909e72013-02-26 09:20:22 -080094#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080095bool AudioFlinger::mTeeSinkInputEnabled = false;
96bool AudioFlinger::mTeeSinkOutputEnabled = false;
97bool AudioFlinger::mTeeSinkTrackEnabled = false;
98
99size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
100size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
101size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109
Marco Nelissenb2208842014-02-07 14:00:50 -0800110const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800111 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530112 case AUDIO_FORMAT_PCM:
113 switch (format) {
114 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
115 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
116 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
117 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
118 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
119 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
120 default:
121 break;
122 }
123 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800124 case AUDIO_FORMAT_MP3: return "mp3";
125 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
126 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
127 case AUDIO_FORMAT_AAC: return "aac";
128 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
129 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
130 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530131 case AUDIO_FORMAT_OPUS: return "opus";
132 case AUDIO_FORMAT_AC3: return "ac-3";
133 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800134 case AUDIO_FORMAT_IEC61937: return "iec61937";
Eric Laurente30f2092016-07-07 18:56:57 -0700135 case AUDIO_FORMAT_DTS: return "dts";
136 case AUDIO_FORMAT_DTS_HD: return "dts-hd";
137 case AUDIO_FORMAT_DOLBY_TRUEHD: return "dolby-truehd";
Marco Nelissenb2208842014-02-07 14:00:50 -0800138 default:
139 break;
140 }
141 return "unknown";
142}
143
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700144static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700145{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700146 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700147 int rc;
148
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700149 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
150 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
151 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
152 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700154 }
155 rc = audio_hw_device_open(mod, dev);
156 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
157 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
158 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700159 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700160 }
Eric Laurent5806b352014-05-22 12:23:26 -0700161 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700162 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
163 rc = BAD_VALUE;
164 goto out;
165 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 return 0;
167
168out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 *dev = NULL;
170 return rc;
171}
172
Mathias Agopian65ab4712010-07-14 17:59:35 -0700173// ----------------------------------------------------------------------------
174
175AudioFlinger::AudioFlinger()
176 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800178 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700179 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800180 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800181 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700182 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800183 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700184 mBtNrecIsOff(false),
185 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700186 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700187 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700188 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700190 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
191 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
192 // zero ID has a special meaning, so unavailable
193 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
194 }
195
Glenn Kasten949a9262013-04-16 12:35:20 -0700196 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800197 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800198 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800199 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
200 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800201 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700202
Wei Jia3f273d12015-11-24 09:06:49 -0800203 // reset battery stats.
204 // if the audio service has crashed, battery stats could be left
205 // in bad state, reset the state upon service start.
206 BatteryNotifier::getInstance().noteResetAudio();
207
Glenn Kasten46909e72013-02-26 09:20:22 -0800208#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800209 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800210 (void) property_get("ro.debuggable", value, "0");
211 int debuggable = atoi(value);
212 int teeEnabled = 0;
213 if (debuggable) {
214 (void) property_get("af.tee", value, "0");
215 teeEnabled = atoi(value);
216 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800217 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700218 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700220 }
221 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800222 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700223 }
224 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800225 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700226 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800227#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700228}
229
230void AudioFlinger::onFirstRef()
231{
Eric Laurent93575202011-01-18 18:39:02 -0800232 Mutex::Autolock _l(mLock);
233
Dima Zavin799a70e2011-04-18 16:57:27 -0700234 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800235 char val_str[PROPERTY_VALUE_MAX] = { 0 };
236 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
237 uint32_t int_val;
238 if (1 == sscanf(val_str, "%u", &int_val)) {
239 mStandbyTimeInNsecs = milliseconds(int_val);
240 ALOGI("Using %u mSec as standby time.", int_val);
241 } else {
242 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
243 ALOGI("Using default %u mSec as standby time.",
244 (uint32_t)(mStandbyTimeInNsecs / 1000000));
245 }
246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247
Eric Laurent1c333e22014-05-20 10:48:17 -0700248 mPatchPanel = new PatchPanel(this);
249
Eric Laurenta4c5a552012-03-29 10:12:40 -0700250 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251}
252
253AudioFlinger::~AudioFlinger()
254{
255 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700256 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700257 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258 }
259 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700260 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700261 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700263
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800264 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
265 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
267 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700269
270 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800271 if (mLogMemoryDealer != 0) {
272 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
273 if (binder != 0) {
274 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
275 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
276 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
277 mUnregisteredWriters.pop();
278 mediaLogService->unregisterWriter(iMemory);
279 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700280 }
281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700282}
283
Eric Laurenta4c5a552012-03-29 10:12:40 -0700284static const char * const audio_interfaces[] = {
285 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
286 AUDIO_HARDWARE_MODULE_ID_A2DP,
287 AUDIO_HARDWARE_MODULE_ID_USB,
288};
289#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
290
Phil Burk062e67a2015-02-11 13:40:50 -0800291AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700292 audio_module_handle_t module,
293 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700294{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295 // if module is 0, the request comes from an old policy manager and we should load
296 // well known modules
297 if (module == 0) {
298 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
299 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
300 loadHwModule_l(audio_interfaces[i]);
301 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700302 // then try to find a module supporting the requested device.
303 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
305 audio_hw_device_t *dev = audioHwDevice->hwDevice();
306 if ((dev->get_supported_devices != NULL) &&
307 (dev->get_supported_devices(dev) & devices) == devices)
308 return audioHwDevice;
309 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700310 } else {
311 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700312 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
313 if (audioHwDevice != NULL) {
314 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700315 }
316 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700317
Dima Zavin799a70e2011-04-18 16:57:27 -0700318 return NULL;
319}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320
Glenn Kasten0f11b512014-01-31 16:18:54 -0800321void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700322{
323 const size_t SIZE = 256;
324 char buffer[SIZE];
325 String8 result;
326
327 result.append("Clients:\n");
328 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800329 sp<Client> client = mClients.valueAt(i).promote();
330 if (client != 0) {
331 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
332 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333 }
334 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700335
Eric Laurentd1b28d42013-09-18 18:47:13 -0700336 result.append("Notification Clients:\n");
337 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
338 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
339 result.append(buffer);
340 }
341
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700342 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800343 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700344 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
345 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800346 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700347 result.append(buffer);
348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350}
351
352
Glenn Kasten0f11b512014-01-31 16:18:54 -0800353void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354{
355 const size_t SIZE = 256;
356 char buffer[SIZE];
357 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800358 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700359
John Grossman4ff14ba2012-02-08 16:37:41 -0800360 snprintf(buffer, SIZE, "Hardware status: %d\n"
361 "Standby Time mSec: %u\n",
362 hardwareStatus,
363 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364 result.append(buffer);
365 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366}
367
Glenn Kasten0f11b512014-01-31 16:18:54 -0800368void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369{
370 const size_t SIZE = 256;
371 char buffer[SIZE];
372 String8 result;
373 snprintf(buffer, SIZE, "Permission Denial: "
374 "can't dump AudioFlinger from pid=%d, uid=%d\n",
375 IPCThreadState::self()->getCallingPid(),
376 IPCThreadState::self()->getCallingUid());
377 result.append(buffer);
378 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379}
380
Eric Laurent81784c32012-11-19 14:55:58 -0800381bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382{
383 bool locked = false;
384 for (int i = 0; i < kDumpLockRetries; ++i) {
385 if (mutex.tryLock() == NO_ERROR) {
386 locked = true;
387 break;
388 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800389 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390 }
391 return locked;
392}
393
394status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
395{
Glenn Kasten44deb052012-02-05 18:09:08 -0800396 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397 dumpPermissionDenial(fd, args);
398 } else {
399 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800400 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 if (!hardwareLocked) {
402 String8 result(kHardwareLockedString);
403 write(fd, result.string(), result.size());
404 } else {
405 mHardwareLock.unlock();
406 }
407
Eric Laurent81784c32012-11-19 14:55:58 -0800408 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409
410 // failed to lock - AudioFlinger is probably deadlocked
411 if (!locked) {
412 String8 result(kDeadlockedString);
413 write(fd, result.string(), result.size());
414 }
415
Eric Laurent021cf962014-05-13 10:18:14 -0700416 bool clientLocked = dumpTryLock(mClientLock);
417 if (!clientLocked) {
418 String8 result(kClientLockedString);
419 write(fd, result.string(), result.size());
420 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700421
422 EffectDumpEffects(fd);
423
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700425 if (clientLocked) {
426 mClientLock.unlock();
427 }
428
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429 dumpInternals(fd, args);
430
431 // dump playback threads
432 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
433 mPlaybackThreads.valueAt(i)->dump(fd, args);
434 }
435
436 // dump record threads
437 for (size_t i = 0; i < mRecordThreads.size(); i++) {
438 mRecordThreads.valueAt(i)->dump(fd, args);
439 }
440
Eric Laurentaaa44472014-09-12 17:41:50 -0700441 // dump orphan effect chains
442 if (mOrphanEffectChains.size() != 0) {
443 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
444 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
445 mOrphanEffectChains.valueAt(i)->dump(fd, args);
446 }
447 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700448 // dump all hardware devs
449 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700450 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700451 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700453
Glenn Kasten46909e72013-02-26 09:20:22 -0800454#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700455 // dump the serially shared record tee sink
456 if (mRecordTeeSource != 0) {
457 dumpTee(fd, mRecordTeeSource);
458 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800459#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700460
Glenn Kastend65d73c2012-06-22 17:21:07 -0700461 if (locked) {
462 mLock.unlock();
463 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800464
465 // append a copy of media.log here by forwarding fd to it, but don't attempt
466 // to lookup the service if it's not running, as it will block for a second
467 if (mLogMemoryDealer != 0) {
468 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
469 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700470 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800471 Vector<String16> args;
472 binder->dump(fd, args);
473 }
474 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700475
476 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700477 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700478 bool unreachableMemory = false;
479 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700480 if (arg == String16("-m")) {
481 dumpMem = true;
482 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700483 unreachableMemory = true;
484 }
485 }
486
Andy Hung07b745e2016-05-23 16:21:07 -0700487 if (dumpMem) {
488 dprintf(fd, "\nDumping memory:\n");
489 std::string s = dumpMemoryAddresses(100 /* limit */);
490 write(fd, s.c_str(), s.size());
491 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700492 if (unreachableMemory) {
493 dprintf(fd, "\nDumping unreachable memory:\n");
494 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700495 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700496 write(fd, s.c_str(), s.size());
497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 }
499 return NO_ERROR;
500}
501
Eric Laurent021cf962014-05-13 10:18:14 -0700502sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800503{
Eric Laurent021cf962014-05-13 10:18:14 -0700504 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800505 // If pid is already in the mClients wp<> map, then use that entry
506 // (for which promote() is always != 0), otherwise create a new entry and Client.
507 sp<Client> client = mClients.valueFor(pid).promote();
508 if (client == 0) {
509 client = new Client(this, pid);
510 mClients.add(pid, client);
511 }
512
513 return client;
514}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515
Glenn Kasten9e58b552013-01-18 15:09:48 -0800516sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
517{
Glenn Kasten481fb672013-09-30 14:39:28 -0700518 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800519 if (mLogMemoryDealer == 0) {
520 return new NBLog::Writer();
521 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800522 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700523 // Similarly if we can't contact the media.log service, also return a dummy writer
524 if (binder == 0) {
525 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800526 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700527 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
528 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
529 // If allocation fails, consult the vector of previously unregistered writers
530 // and garbage-collect one or more them until an allocation succeeds
531 if (shared == 0) {
532 Mutex::Autolock _l(mUnregisteredWritersLock);
533 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
534 {
535 // Pick the oldest stale writer to garbage-collect
536 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
537 mUnregisteredWriters.removeAt(0);
538 mediaLogService->unregisterWriter(iMemory);
539 // Now the media.log remote reference to IMemory is gone. When our last local
540 // reference to IMemory also drops to zero at end of this block,
541 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
542 }
543 // Re-attempt the allocation
544 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
545 if (shared != 0) {
546 goto success;
547 }
548 }
549 // Even after garbage-collecting all old writers, there is still not enough memory,
550 // so return a dummy writer
551 return new NBLog::Writer();
552 }
553success:
554 mediaLogService->registerWriter(shared, size, name);
555 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800556}
557
558void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
559{
Glenn Kasten685ef092013-02-04 08:15:34 -0800560 if (writer == 0) {
561 return;
562 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800563 sp<IMemory> iMemory(writer->getIMemory());
564 if (iMemory == 0) {
565 return;
566 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700567 // Rather than removing the writer immediately, append it to a queue of old writers to
568 // be garbage-collected later. This allows us to continue to view old logs for a while.
569 Mutex::Autolock _l(mUnregisteredWritersLock);
570 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800571}
572
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573// IAudioFlinger interface
574
575
576sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800577 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800579 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700580 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800581 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700582 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800584 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700585 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800586 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800587 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800588 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 status_t *status)
590{
591 sp<PlaybackThread::Track> track;
592 sp<TrackHandle> trackHandle;
593 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800595 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700597 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
598 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
599 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
600 ALOGW_IF(pid != -1 && pid != callingPid,
601 "%s uid %d pid %d tried to pass itself off as pid %d",
602 __func__, callingUid, callingPid, pid);
603 pid = callingPid;
604 }
605
Glenn Kasten263709e2012-01-06 08:40:01 -0800606 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
607 // but if someone uses binder directly they could bypass that and cause us to crash
608 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000609 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 lStatus = BAD_VALUE;
611 goto Exit;
612 }
613
Glenn Kasten53b5d092014-02-05 10:00:23 -0800614 // further sample rate checks are performed by createTrack_l() depending on the thread type
615 if (sampleRate == 0) {
616 ALOGE("createTrack() invalid sample rate %u", sampleRate);
617 lStatus = BAD_VALUE;
618 goto Exit;
619 }
620
621 // further channel mask checks are performed by createTrack_l() depending on the thread type
622 if (!audio_is_output_channel(channelMask)) {
623 ALOGE("createTrack() invalid channel mask %#x", channelMask);
624 lStatus = BAD_VALUE;
625 goto Exit;
626 }
627
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700628 // further format checks are performed by createTrack_l() depending on the thread type
629 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800630 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700631 lStatus = BAD_VALUE;
632 goto Exit;
633 }
634
Glenn Kasten663c2242013-09-24 11:52:37 -0700635 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
636 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
637 lStatus = BAD_VALUE;
638 goto Exit;
639 }
640
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641 {
642 Mutex::Autolock _l(mLock);
643 PlaybackThread *thread = checkPlaybackThread_l(output);
644 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800645 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646 lStatus = BAD_VALUE;
647 goto Exit;
648 }
649
Eric Laurent021cf962014-05-13 10:18:14 -0700650 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651
Glenn Kastene848bd92014-03-13 15:00:32 -0700652 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700653 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800654 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
655 ALOGE("createTrack() invalid session ID %d", *sessionId);
656 lStatus = BAD_VALUE;
657 goto Exit;
658 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700659 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700660 // check if an effect chain with the same session ID is present on another
661 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700662 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700663 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
664 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700665 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700666 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700667 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700668 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700669 }
Eric Laurentde070132010-07-13 04:45:46 -0700670 }
671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700673 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800674 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 if (sessionId != NULL) {
676 *sessionId = lSessionId;
677 }
678 }
Steve Block3856b092011-10-20 11:56:00 +0100679 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680
681 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800682 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800683 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700684 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700685
686 // move effect chain to this output thread if an effect on same session was waiting
687 // for a track to be created
688 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700689 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700690 Mutex::Autolock _dl(thread->mLock);
691 Mutex::Autolock _sl(effectThread->mLock);
692 moveEffectChain_l(lSessionId, effectThread, thread, true);
693 }
Eric Laurenta011e352012-03-29 15:51:43 -0700694
695 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700696 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700697 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
698 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700699 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700700 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700701 } else {
702 mPendingSyncEvents[i]->cancel();
703 }
Eric Laurenta011e352012-03-29 15:51:43 -0700704 mPendingSyncEvents.removeAt(i);
705 i--;
706 }
707 }
708 }
Glenn Kastene198c362013-08-13 09:13:36 -0700709
Glenn Kastend848eb42016-03-08 13:42:11 -0800710 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 }
Glenn Kastene198c362013-08-13 09:13:36 -0700712
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700713 if (lStatus != NO_ERROR) {
714 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700715 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700716 // Don't hold mClientLock when releasing the reference on the track as the
717 // destructor will acquire it.
718 {
719 Mutex::Autolock _cl(mClientLock);
720 client.clear();
721 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700723 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 }
725
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700726 // return handle to client
727 trackHandle = new TrackHandle(track);
728
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700730 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 return trackHandle;
732}
733
Glenn Kasten2c073da2016-02-26 09:14:08 -0800734uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
736 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800737 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800739 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 return 0;
741 }
742 return thread->sampleRate();
743}
744
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800745audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746{
747 Mutex::Autolock _l(mLock);
748 PlaybackThread *thread = checkPlaybackThread_l(output);
749 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000750 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800751 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 }
753 return thread->format();
754}
755
Glenn Kasten2c073da2016-02-26 09:14:08 -0800756size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757{
758 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800759 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800761 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762 return 0;
763 }
Glenn Kasten58912562012-04-03 10:45:00 -0700764 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
765 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 return thread->frameCount();
767}
768
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700769size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
770{
771 Mutex::Autolock _l(mLock);
772 ThreadBase *thread = checkThread_l(ioHandle);
773 if (thread == NULL) {
774 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
775 return 0;
776 }
777 return thread->frameCountHAL();
778}
779
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800780uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781{
782 Mutex::Autolock _l(mLock);
783 PlaybackThread *thread = checkPlaybackThread_l(output);
784 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800785 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 return 0;
787 }
788 return thread->latency();
789}
790
791status_t AudioFlinger::setMasterVolume(float value)
792{
Eric Laurenta1884f92011-08-23 08:25:03 -0700793 status_t ret = initCheck();
794 if (ret != NO_ERROR) {
795 return ret;
796 }
797
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 // check calling permissions
799 if (!settingsAllowed()) {
800 return PERMISSION_DENIED;
801 }
802
Eric Laurenta4c5a552012-03-29 10:12:40 -0700803 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700804 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700805
John Grossmanee578c02012-07-23 17:05:46 -0700806 // Set master volume in the HALs which support it.
807 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
808 AutoMutex lock(mHardwareLock);
809 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800810
John Grossmanee578c02012-07-23 17:05:46 -0700811 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
812 if (dev->canSetMasterVolume()) {
813 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800814 }
John Grossmanee578c02012-07-23 17:05:46 -0700815 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817
John Grossmanee578c02012-07-23 17:05:46 -0700818 // Now set the master volume in each playback thread. Playback threads
819 // assigned to HALs which do not have master volume support will apply
820 // master volume during the mix operation. Threads with HALs which do
821 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700822 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
823 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
824 continue;
825 }
John Grossmanee578c02012-07-23 17:05:46 -0700826 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828
829 return NO_ERROR;
830}
831
Glenn Kastenf78aee72012-01-04 11:00:47 -0800832status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
Eric Laurenta1884f92011-08-23 08:25:03 -0700834 status_t ret = initCheck();
835 if (ret != NO_ERROR) {
836 return ret;
837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838
839 // check calling permissions
840 if (!settingsAllowed()) {
841 return PERMISSION_DENIED;
842 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800843 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000844 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return BAD_VALUE;
846 }
847
848 { // scope for the lock
849 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700850 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700852 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 mHardwareStatus = AUDIO_HW_IDLE;
854 }
855
856 if (NO_ERROR == ret) {
857 Mutex::Autolock _l(mLock);
858 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800859 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700860 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861 }
862
863 return ret;
864}
865
866status_t AudioFlinger::setMicMute(bool state)
867{
Eric Laurenta1884f92011-08-23 08:25:03 -0700868 status_t ret = initCheck();
869 if (ret != NO_ERROR) {
870 return ret;
871 }
872
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 // check calling permissions
874 if (!settingsAllowed()) {
875 return PERMISSION_DENIED;
876 }
877
878 AutoMutex lock(mHardwareLock);
879 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700880 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
881 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
882 status_t result = dev->set_mic_mute(dev, state);
883 if (result != NO_ERROR) {
884 ret = result;
885 }
886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 mHardwareStatus = AUDIO_HW_IDLE;
888 return ret;
889}
890
891bool AudioFlinger::getMicMute() const
892{
Eric Laurenta1884f92011-08-23 08:25:03 -0700893 status_t ret = initCheck();
894 if (ret != NO_ERROR) {
895 return false;
896 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800897 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700898 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800899 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800901 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
902 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
903 status_t result = dev->get_mic_mute(dev, &state);
904 if (result == NO_ERROR) {
905 mute = mute && state;
906 }
907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800909
910 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911}
912
913status_t AudioFlinger::setMasterMute(bool muted)
914{
John Grossmand8f178d2012-07-20 14:51:35 -0700915 status_t ret = initCheck();
916 if (ret != NO_ERROR) {
917 return ret;
918 }
919
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 // check calling permissions
921 if (!settingsAllowed()) {
922 return PERMISSION_DENIED;
923 }
924
John Grossmanee578c02012-07-23 17:05:46 -0700925 Mutex::Autolock _l(mLock);
926 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700927
John Grossmanee578c02012-07-23 17:05:46 -0700928 // Set master mute in the HALs which support it.
929 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
930 AutoMutex lock(mHardwareLock);
931 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700932
John Grossmanee578c02012-07-23 17:05:46 -0700933 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
934 if (dev->canSetMasterMute()) {
935 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700936 }
John Grossmanee578c02012-07-23 17:05:46 -0700937 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700938 }
939
John Grossmanee578c02012-07-23 17:05:46 -0700940 // Now set the master mute in each playback thread. Playback threads
941 // assigned to HALs which do not have master mute support will apply master
942 // mute during the mix operation. Threads with HALs which do support master
943 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700944 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
945 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
946 continue;
947 }
John Grossmanee578c02012-07-23 17:05:46 -0700948 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950
951 return NO_ERROR;
952}
953
954float AudioFlinger::masterVolume() const
955{
Glenn Kasten98067102011-12-13 11:47:54 -0800956 Mutex::Autolock _l(mLock);
957 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958}
959
960bool AudioFlinger::masterMute() const
961{
Glenn Kasten98067102011-12-13 11:47:54 -0800962 Mutex::Autolock _l(mLock);
963 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964}
965
John Grossman4ff14ba2012-02-08 16:37:41 -0800966float AudioFlinger::masterVolume_l() const
967{
John Grossman4ff14ba2012-02-08 16:37:41 -0800968 return mMasterVolume;
969}
970
John Grossmand8f178d2012-07-20 14:51:35 -0700971bool AudioFlinger::masterMute_l() const
972{
John Grossmanee578c02012-07-23 17:05:46 -0700973 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700974}
975
Eric Laurent223fd5c2014-11-11 13:43:36 -0800976status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
977{
978 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
979 ALOGW("setStreamVolume() invalid stream %d", stream);
980 return BAD_VALUE;
981 }
982 pid_t caller = IPCThreadState::self()->getCallingPid();
983 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
984 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
985 return PERMISSION_DENIED;
986 }
987
988 return NO_ERROR;
989}
990
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800991status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
992 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
994 // check calling permissions
995 if (!settingsAllowed()) {
996 return PERMISSION_DENIED;
997 }
998
Eric Laurent223fd5c2014-11-11 13:43:36 -0800999 status_t status = checkStreamType(stream);
1000 if (status != NO_ERROR) {
1001 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001003 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004
1005 AutoMutex lock(mLock);
1006 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -07001007 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 thread = checkPlaybackThread_l(output);
1009 if (thread == NULL) {
1010 return BAD_VALUE;
1011 }
1012 }
1013
1014 mStreamTypes[stream].volume = value;
1015
1016 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001017 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001018 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 }
1020 } else {
1021 thread->setStreamVolume(stream, value);
1022 }
1023
1024 return NO_ERROR;
1025}
1026
Glenn Kastenfff6d712012-01-12 16:38:12 -08001027status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028{
1029 // check calling permissions
1030 if (!settingsAllowed()) {
1031 return PERMISSION_DENIED;
1032 }
1033
Eric Laurent223fd5c2014-11-11 13:43:36 -08001034 status_t status = checkStreamType(stream);
1035 if (status != NO_ERROR) {
1036 return status;
1037 }
1038 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1039
1040 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001041 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 return BAD_VALUE;
1043 }
1044
Eric Laurent93575202011-01-18 18:39:02 -08001045 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001047 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001048 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049
1050 return NO_ERROR;
1051}
1052
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001053float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001055 status_t status = checkStreamType(stream);
1056 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 return 0.0f;
1058 }
1059
1060 AutoMutex lock(mLock);
1061 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001062 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 PlaybackThread *thread = checkPlaybackThread_l(output);
1064 if (thread == NULL) {
1065 return 0.0f;
1066 }
1067 volume = thread->streamVolume(stream);
1068 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001069 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 }
1071
1072 return volume;
1073}
1074
Glenn Kastenfff6d712012-01-12 16:38:12 -08001075bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001077 status_t status = checkStreamType(stream);
1078 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 return true;
1080 }
1081
Glenn Kasten6637baa2012-01-09 09:40:36 -08001082 AutoMutex lock(mLock);
1083 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084}
1085
Eric Laurent054d9d32015-04-24 08:48:48 -07001086
1087void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1088{
1089 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1090 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1091 }
1092}
1093
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001094status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001096 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1097 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001098
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 // check calling permissions
1100 if (!settingsAllowed()) {
1101 return PERMISSION_DENIED;
1102 }
1103
Glenn Kasten142f5192014-03-25 17:44:59 -07001104 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1105 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001106 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001107 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001108 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001109 AutoMutex lock(mHardwareLock);
1110 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1111 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1112 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1113 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1114 final_result = result ?: final_result;
1115 }
1116 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001117 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001118 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1119 AudioParameter param = AudioParameter(keyValuePairs);
1120 String8 value;
1121 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001122 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1123 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001124 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1125 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001126 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001127 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1128 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001129 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001130 // suspend effects associated with those session IDs
1131 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001132 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001133 thread->setEffectSuspended(FX_IID_AEC,
1134 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001135 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001136 thread->setEffectSuspended(FX_IID_NS,
1137 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001138 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001139 }
1140 }
Eric Laurentbee53372011-08-29 12:42:48 -07001141 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001142 }
1143 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001144 String8 screenState;
1145 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1146 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001147 if (isOff != (AudioFlinger::mScreenState & 1)) {
1148 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001149 }
1150 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001151 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001152 }
1153
1154 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1155 // and the thread is exited once the lock is released
1156 sp<ThreadBase> thread;
1157 {
1158 Mutex::Autolock _l(mLock);
1159 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001160 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001162 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001163 // indicate output device change to all input threads for pre processing
1164 AudioParameter param = AudioParameter(keyValuePairs);
1165 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001166 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1167 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001168 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 }
1171 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001172 if (thread != 0) {
1173 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 }
1175 return BAD_VALUE;
1176}
1177
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001178String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001180 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1181 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182
Eric Laurenta4c5a552012-03-29 10:12:40 -07001183 Mutex::Autolock _l(mLock);
1184
Glenn Kasten142f5192014-03-25 17:44:59 -07001185 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001186 String8 out_s8;
1187
Dima Zavin799a70e2011-04-18 16:57:27 -07001188 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001189 char *s;
1190 {
1191 AutoMutex lock(mHardwareLock);
1192 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001193 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001194 s = dev->get_parameters(dev, keys.string());
1195 mHardwareStatus = AUDIO_HW_IDLE;
1196 }
John Grossmanef7740b2012-02-09 11:28:36 -08001197 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001198 free(s);
1199 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001200 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 }
1202
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1204 if (playbackThread != NULL) {
1205 return playbackThread->getParameters(keys);
1206 }
1207 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1208 if (recordThread != NULL) {
1209 return recordThread->getParameters(keys);
1210 }
1211 return String8("");
1212}
1213
Glenn Kastendd8104c2012-07-02 12:42:44 -07001214size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1215 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216{
Eric Laurenta1884f92011-08-23 08:25:03 -07001217 status_t ret = initCheck();
1218 if (ret != NO_ERROR) {
1219 return 0;
1220 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001221 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001222 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001223 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001224 return 0;
1225 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001226
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001227 AutoMutex lock(mHardwareLock);
1228 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001229 audio_config_t config, proposed;
1230 memset(&proposed, 0, sizeof(proposed));
1231 proposed.sample_rate = sampleRate;
1232 proposed.channel_mask = channelMask;
1233 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001234
John Grossmanee578c02012-07-23 17:05:46 -07001235 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001236 size_t frames;
1237 for (;;) {
1238 // Note: config is currently a const parameter for get_input_buffer_size()
1239 // but we use a copy from proposed in case config changes from the call.
1240 config = proposed;
1241 frames = dev->get_input_buffer_size(dev, &config);
1242 if (frames != 0) {
1243 break; // hal success, config is the result
1244 }
1245 // change one parameter of the configuration each iteration to a more "common" value
1246 // to see if the device will support it.
1247 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1248 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1249 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1250 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1251 } else {
1252 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1253 "format %#x, channelMask 0x%X",
1254 sampleRate, format, channelMask);
1255 break; // retries failed, break out of loop with frames == 0.
1256 }
1257 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001258 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001259 if (frames > 0 && config.sample_rate != sampleRate) {
1260 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1261 }
1262 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263}
1264
Glenn Kasten5f972c02014-01-13 09:59:31 -08001265uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267 Mutex::Autolock _l(mLock);
1268
1269 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1270 if (recordThread != NULL) {
1271 return recordThread->getInputFramesLost();
1272 }
1273 return 0;
1274}
1275
1276status_t AudioFlinger::setVoiceVolume(float value)
1277{
Eric Laurenta1884f92011-08-23 08:25:03 -07001278 status_t ret = initCheck();
1279 if (ret != NO_ERROR) {
1280 return ret;
1281 }
1282
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 // check calling permissions
1284 if (!settingsAllowed()) {
1285 return PERMISSION_DENIED;
1286 }
1287
1288 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001289 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001290 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001291 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 mHardwareStatus = AUDIO_HW_IDLE;
1293
1294 return ret;
1295}
1296
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001297status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001298 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 Mutex::Autolock _l(mLock);
1301
1302 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1303 if (playbackThread != NULL) {
1304 return playbackThread->getRenderPosition(halFrames, dspFrames);
1305 }
1306
1307 return BAD_VALUE;
1308}
1309
1310void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1311{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001313 if (client == 0) {
1314 return;
1315 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001316 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001317 {
1318 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001319 if (mNotificationClients.indexOfKey(pid) < 0) {
1320 sp<NotificationClient> notificationClient = new NotificationClient(this,
1321 client,
1322 pid);
1323 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001324
Eric Laurent021cf962014-05-13 10:18:14 -07001325 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001326
Marco Nelissen06b46062014-11-14 07:58:25 -08001327 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001328 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001329 }
1330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331
Eric Laurent021cf962014-05-13 10:18:14 -07001332 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001333 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001334 // the config change is always sent from playback or record threads to avoid deadlock
1335 // with AudioSystem::gLock
1336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1337 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1341 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342 }
1343}
1344
1345void AudioFlinger::removeNotificationClient(pid_t pid)
1346{
1347 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001348 {
1349 Mutex::Autolock _cl(mClientLock);
1350 mNotificationClients.removeItem(pid);
1351 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001352
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001354 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001355 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001356 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001357 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001358 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001359 if (ref->mPid == pid) {
1360 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001361 mAudioSessionRefs.removeAt(i);
1362 delete ref;
1363 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001364 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001365 } else {
1366 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001367 }
1368 }
1369 if (removed) {
1370 purgeStaleEffects_l();
1371 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372}
1373
Eric Laurent73e26b62015-04-27 16:55:58 -07001374void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001375 const sp<AudioIoDescriptor>& ioDesc,
1376 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
Eric Laurent021cf962014-05-13 10:18:14 -07001378 Mutex::Autolock _l(mClientLock);
1379 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001381 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1382 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1383 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 }
1385}
1386
Eric Laurent021cf962014-05-13 10:18:14 -07001387// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388void AudioFlinger::removeClient_l(pid_t pid)
1389{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001390 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001391 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 mClients.removeItem(pid);
1393}
1394
Eric Laurent717e1282012-06-29 16:36:52 -07001395// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001396sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1397 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001398{
1399 sp<PlaybackThread> thread;
1400
1401 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1402 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1403 ALOG_ASSERT(thread == 0);
1404 thread = mPlaybackThreads.valueAt(i);
1405 }
1406 }
1407
1408 return thread;
1409}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412
1413// ----------------------------------------------------------------------------
1414
1415AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1416 : RefBase(),
1417 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001418 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301420 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1421 heapSize *= 1024;
1422 if (!heapSize) {
1423 heapSize = kClientSharedHeapSizeBytes;
1424 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1425 // invalidated tracks
1426 if (!audioFlinger->isLowRamDevice()) {
1427 heapSize *= kClientSharedHeapSizeMultiplier;
1428 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001429 }
1430 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431}
1432
Eric Laurent021cf962014-05-13 10:18:14 -07001433// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434AudioFlinger::Client::~Client()
1435{
1436 mAudioFlinger->removeClient_l(mPid);
1437}
1438
Glenn Kasten435dbe62012-01-30 10:15:48 -08001439sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440{
1441 return mMemoryDealer;
1442}
1443
1444// ----------------------------------------------------------------------------
1445
1446AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1447 const sp<IAudioFlingerClient>& client,
1448 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001449 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450{
1451}
1452
1453AudioFlinger::NotificationClient::~NotificationClient()
1454{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455}
1456
Glenn Kasten0f11b512014-01-31 16:18:54 -08001457void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458{
1459 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001460 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001461}
1462
Mathias Agopian65ab4712010-07-14 17:59:35 -07001463
1464// ----------------------------------------------------------------------------
1465
1466sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001467 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001469 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001470 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001471 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001472 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001473 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001474 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001475 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001476 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001477 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001478 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001479 sp<IMemory>& cblk,
1480 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481 status_t *status)
1482{
1483 sp<RecordThread::RecordTrack> recordTrack;
1484 sp<RecordHandle> recordHandle;
1485 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001487 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488
Glenn Kastend776ac62014-05-07 09:16:09 -07001489 cblk.clear();
1490 buffers.clear();
1491
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001492 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001493 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1494 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001495 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001496 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1497 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001498 updatePid = true;
1499 }
1500
1501 if (updatePid) {
1502 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1503 ALOGW_IF(pid != -1 && pid != callingPid,
1504 "%s uid %d pid %d tried to pass itself off as pid %d",
1505 __func__, callingUid, callingPid, pid);
1506 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001507 }
1508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001510 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001511 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 lStatus = PERMISSION_DENIED;
1513 goto Exit;
1514 }
1515
Glenn Kasten53b5d092014-02-05 10:00:23 -08001516 // further sample rate checks are performed by createRecordTrack_l()
1517 if (sampleRate == 0) {
1518 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522
Andy Hung6770c6f2015-04-07 13:43:36 -07001523 // we don't yet support anything other than linear PCM
1524 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001525 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001526 lStatus = BAD_VALUE;
1527 goto Exit;
1528 }
1529
Glenn Kasten53b5d092014-02-05 10:00:23 -08001530 // further channel mask checks are performed by createRecordTrack_l()
1531 if (!audio_is_input_channel(channelMask)) {
1532 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536
Glenn Kasten05997e22014-03-13 15:08:33 -07001537 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001539 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001541 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 lStatus = BAD_VALUE;
1543 goto Exit;
1544 }
1545
Eric Laurent021cf962014-05-13 10:18:14 -07001546 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001548 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001549 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1550 lStatus = BAD_VALUE;
1551 goto Exit;
1552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 lSessionId = *sessionId;
1554 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001555 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001556 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 if (sessionId != NULL) {
1558 *sessionId = lSessionId;
1559 }
1560 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001561 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001562
Glenn Kasten1879fff2012-07-11 15:36:59 -07001563 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001564 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001565 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001566 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001567
1568 if (lStatus == NO_ERROR) {
1569 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1570 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001571 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001572 if (chain != 0) {
1573 Mutex::Autolock _l(thread->mLock);
1574 thread->addEffectChain_l(chain);
1575 }
1576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 }
Glenn Kastene198c362013-08-13 09:13:36 -07001578
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001579 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001580 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001581 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001582 // Don't hold mClientLock when releasing the reference on the track as the
1583 // destructor will acquire it.
1584 {
1585 Mutex::Autolock _cl(mClientLock);
1586 client.clear();
1587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 goto Exit;
1590 }
1591
Glenn Kastend776ac62014-05-07 09:16:09 -07001592 cblk = recordTrack->getCblk();
1593 buffers = recordTrack->getBuffers();
1594
Glenn Kasten2fc14732013-08-05 14:58:14 -07001595 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597
1598Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001599 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 return recordHandle;
1601}
1602
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001603
1604
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605// ----------------------------------------------------------------------------
1606
Eric Laurenta4c5a552012-03-29 10:12:40 -07001607audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1608{
Eric Laurent44622db2014-08-01 19:00:33 -07001609 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001610 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001611 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001612 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001613 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001614 }
1615 Mutex::Autolock _l(mLock);
1616 return loadHwModule_l(name);
1617}
1618
1619// loadHwModule_l() must be called with AudioFlinger::mLock held
1620audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1621{
1622 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1623 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1624 ALOGW("loadHwModule() module %s already loaded", name);
1625 return mAudioHwDevs.keyAt(i);
1626 }
1627 }
1628
Eric Laurenta4c5a552012-03-29 10:12:40 -07001629 audio_hw_device_t *dev;
1630
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001631 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001632 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001633 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001634 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001635 }
1636
1637 mHardwareStatus = AUDIO_HW_INIT;
1638 rc = dev->init_check(dev);
1639 mHardwareStatus = AUDIO_HW_IDLE;
1640 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001641 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001642 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001643 }
1644
John Grossmanee578c02012-07-23 17:05:46 -07001645 // Check and cache this HAL's level of support for master mute and master
1646 // volume. If this is the first HAL opened, and it supports the get
1647 // methods, use the initial values provided by the HAL as the current
1648 // master mute and volume settings.
1649
1650 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1651 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001652 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001653
1654 if (0 == mAudioHwDevs.size()) {
1655 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1656 if (NULL != dev->get_master_volume) {
1657 float mv;
1658 if (OK == dev->get_master_volume(dev, &mv)) {
1659 mMasterVolume = mv;
1660 }
1661 }
1662
1663 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1664 if (NULL != dev->get_master_mute) {
1665 bool mm;
1666 if (OK == dev->get_master_mute(dev, &mm)) {
1667 mMasterMute = mm;
1668 }
1669 }
1670 }
1671
Eric Laurenta4c5a552012-03-29 10:12:40 -07001672 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001673 if ((NULL != dev->set_master_volume) &&
1674 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1675 flags = static_cast<AudioHwDevice::Flags>(flags |
1676 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1677 }
1678
1679 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1680 if ((NULL != dev->set_master_mute) &&
1681 (OK == dev->set_master_mute(dev, mMasterMute))) {
1682 flags = static_cast<AudioHwDevice::Flags>(flags |
1683 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1684 }
1685
Eric Laurenta4c5a552012-03-29 10:12:40 -07001686 mHardwareStatus = AUDIO_HW_IDLE;
1687 }
1688
Glenn Kastena13cde92016-03-28 15:26:02 -07001689 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001690 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001691
1692 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001693 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001694
1695 return handle;
1696
1697}
1698
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001699// ----------------------------------------------------------------------------
1700
Glenn Kasten3b16c762012-11-14 08:44:39 -08001701uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001702{
1703 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001704 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001705 return thread != NULL ? thread->sampleRate() : 0;
1706}
1707
Glenn Kastene33054e2012-11-14 12:54:39 -08001708size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001709{
1710 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001711 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001712 return thread != NULL ? thread->frameCountHAL() : 0;
1713}
1714
1715// ----------------------------------------------------------------------------
1716
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001717status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1718{
1719 uid_t uid = IPCThreadState::self()->getCallingUid();
1720 if (uid != AID_SYSTEM) {
1721 return PERMISSION_DENIED;
1722 }
1723 Mutex::Autolock _l(mLock);
1724 if (mIsDeviceTypeKnown) {
1725 return INVALID_OPERATION;
1726 }
1727 mIsLowRamDevice = isLowRamDevice;
1728 mIsDeviceTypeKnown = true;
1729 return NO_ERROR;
1730}
1731
Eric Laurent93c3d412014-08-01 14:48:35 -07001732audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1733{
1734 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001735
1736 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1737 if (index >= 0) {
1738 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1739 mHwAvSyncIds.valueAt(index), sessionId);
1740 return mHwAvSyncIds.valueAt(index);
1741 }
1742
1743 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1744 if (dev == NULL) {
1745 return AUDIO_HW_SYNC_INVALID;
1746 }
1747 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1748 AudioParameter param = AudioParameter(String8(reply));
1749 free(reply);
1750
1751 int value;
1752 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1753 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1754 return AUDIO_HW_SYNC_INVALID;
1755 }
1756
1757 // allow only one session for a given HW A/V sync ID.
1758 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1759 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1760 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1761 value, mHwAvSyncIds.keyAt(i));
1762 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001763 break;
1764 }
1765 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001766
1767 mHwAvSyncIds.add(sessionId, value);
1768
1769 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1770 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1771 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001772 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001773 AudioParameter param = AudioParameter();
1774 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1775 thread->setParameters(param.toString());
1776 break;
1777 }
1778 }
1779
1780 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1781 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001782}
1783
Eric Laurent72e3f392015-05-20 14:43:50 -07001784status_t AudioFlinger::systemReady()
1785{
1786 Mutex::Autolock _l(mLock);
1787 ALOGI("%s", __FUNCTION__);
1788 if (mSystemReady) {
1789 ALOGW("%s called twice", __FUNCTION__);
1790 return NO_ERROR;
1791 }
1792 mSystemReady = true;
1793 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1794 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1795 thread->systemReady();
1796 }
1797 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1798 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1799 thread->systemReady();
1800 }
1801 return NO_ERROR;
1802}
1803
Eric Laurentfa90e842014-10-17 18:12:31 -07001804// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1805void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1806{
1807 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1808 if (index >= 0) {
1809 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1810 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1811 AudioParameter param = AudioParameter();
1812 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1813 thread->setParameters(param.toString());
1814 }
1815}
1816
1817
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001818// ----------------------------------------------------------------------------
1819
Eric Laurent83b88082014-06-20 18:31:16 -07001820
1821sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001822 audio_io_handle_t *output,
1823 audio_config_t *config,
1824 audio_devices_t devices,
1825 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001826 audio_output_flags_t flags)
1827{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001828 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001829 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001830 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001831 }
1832
Eric Laurentcf2c0212014-07-25 16:20:43 -07001833 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001834 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1835 } else {
1836 // Audio Policy does not currently request a specific output handle.
1837 // If this is ever needed, see openInput_l() for example code.
1838 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1839 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001840 }
Eric Laurent83b88082014-06-20 18:31:16 -07001841
1842 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1843
Eric Laurent83b88082014-06-20 18:31:16 -07001844 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001845 // This if statement allows overriding the audio policy settings
1846 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1847 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1848 // Check only for Normal Mixing mode
1849 if (kEnableExtendedPrecision) {
1850 // Specify format (uncomment one below to choose)
1851 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1852 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1853 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1854 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001855 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001856 }
1857 if (kEnableExtendedChannels) {
1858 // Specify channel mask (uncomment one below to choose)
1859 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1860 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1861 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1862 }
Eric Laurent83b88082014-06-20 18:31:16 -07001863 }
1864
Phil Burk062e67a2015-02-11 13:40:50 -08001865 AudioStreamOut *outputStream = NULL;
1866 status_t status = outHwDev->openOutputStream(
1867 &outputStream,
1868 *output,
1869 devices,
1870 flags,
1871 config,
1872 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001873
1874 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001875
Phil Burk062e67a2015-02-11 13:40:50 -08001876 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001877
1878 PlaybackThread *thread;
1879 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001880 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001881 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001882 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1883 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001884 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001885 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001886 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001887 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001888 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001889 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001890 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001891 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001892 return thread;
1893 }
1894
1895 return 0;
1896}
1897
Eric Laurentcf2c0212014-07-25 16:20:43 -07001898status_t AudioFlinger::openOutput(audio_module_handle_t module,
1899 audio_io_handle_t *output,
1900 audio_config_t *config,
1901 audio_devices_t *devices,
1902 const String8& address,
1903 uint32_t *latencyMs,
1904 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905{
Phil Burk062e67a2015-02-11 13:40:50 -08001906 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001907 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908 (devices != NULL) ? *devices : 0,
1909 config->sample_rate,
1910 config->format,
1911 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001912 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913
Eric Laurentcf2c0212014-07-25 16:20:43 -07001914 if (*devices == AUDIO_DEVICE_NONE) {
1915 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001917
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 Mutex::Autolock _l(mLock);
1919
Eric Laurentcf2c0212014-07-25 16:20:43 -07001920 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001921 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001922 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923
1924 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001925 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001926
1927 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001928 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001929 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001930 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001931
1932 AutoMutex lock(mHardwareLock);
1933 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001934 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001935 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001936 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001937 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939
Eric Laurentcf2c0212014-07-25 16:20:43 -07001940 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941}
1942
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001943audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1944 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945{
1946 Mutex::Autolock _l(mLock);
1947 MixerThread *thread1 = checkMixerThread_l(output1);
1948 MixerThread *thread2 = checkMixerThread_l(output2);
1949
1950 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001951 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1952 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001953 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 }
1955
Glenn Kasteneeecb982016-02-26 10:44:04 -08001956 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001957 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 thread->addOutputTrack(thread2);
1959 mPlaybackThreads.add(id, thread);
1960 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001961 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 return id;
1963}
1964
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001965status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966{
Glenn Kastend96c5722012-04-25 13:44:49 -07001967 return closeOutput_nonvirtual(output);
1968}
1969
1970status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1971{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 // keep strong reference on the playback thread so that
1973 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001974 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 {
1976 Mutex::Autolock _l(mLock);
1977 thread = checkPlaybackThread_l(output);
1978 if (thread == NULL) {
1979 return BAD_VALUE;
1980 }
1981
Steve Block3856b092011-10-20 11:56:00 +01001982 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001984 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001986 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001987 DuplicatingThread *dupThread =
1988 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001990 }
1991 }
1992 }
1993
1994
1995 mPlaybackThreads.removeItem(output);
1996 // save all effects to the default thread
1997 if (mPlaybackThreads.size()) {
1998 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1999 if (dstThread != NULL) {
2000 // audioflinger lock is held here so the acquisition order of thread locks does not
2001 // matter
2002 Mutex::Autolock _dl(dstThread->mLock);
2003 Mutex::Autolock _sl(thread->mLock);
2004 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2005 for (size_t i = 0; i < effectChains.size(); i ++) {
2006 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 }
2008 }
2009 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002010 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2011 ioDesc->mIoHandle = output;
2012 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002015 // The thread entity (active unit of execution) is no longer running here,
2016 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017
Eric Laurentf6870ae2015-05-08 10:50:03 -07002018 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002019 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
Eric Laurent83b88082014-06-20 18:31:16 -07002021
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 return NO_ERROR;
2023}
2024
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002025void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002026{
2027 AudioStreamOut *out = thread->clearOutput();
2028 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2029 // from now on thread->mOutput is NULL
2030 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
2031 delete out;
2032}
2033
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002034void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002035{
2036 mPlaybackThreads.removeItem(thread->mId);
2037 thread->exit();
2038 closeOutputFinish(thread);
2039}
2040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002041status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042{
2043 Mutex::Autolock _l(mLock);
2044 PlaybackThread *thread = checkPlaybackThread_l(output);
2045
2046 if (thread == NULL) {
2047 return BAD_VALUE;
2048 }
2049
Steve Block3856b092011-10-20 11:56:00 +01002050 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 thread->suspend();
2052
2053 return NO_ERROR;
2054}
2055
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002056status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057{
2058 Mutex::Autolock _l(mLock);
2059 PlaybackThread *thread = checkPlaybackThread_l(output);
2060
2061 if (thread == NULL) {
2062 return BAD_VALUE;
2063 }
2064
Steve Block3856b092011-10-20 11:56:00 +01002065 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066
2067 thread->restore();
2068
2069 return NO_ERROR;
2070}
2071
Eric Laurentcf2c0212014-07-25 16:20:43 -07002072status_t AudioFlinger::openInput(audio_module_handle_t module,
2073 audio_io_handle_t *input,
2074 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002075 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002076 const String8& address,
2077 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002078 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079{
Eric Laurent83b88082014-06-20 18:31:16 -07002080 Mutex::Autolock _l(mLock);
2081
Glenn Kastene7d66712015-03-05 13:46:52 -08002082 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002083 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002084 }
2085
Glenn Kastene7d66712015-03-05 13:46:52 -08002086 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002087
2088 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002089 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002090 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002091 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002093 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002094}
Dima Zavin799a70e2011-04-18 16:57:27 -07002095
Eric Laurent83b88082014-06-20 18:31:16 -07002096sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002097 audio_io_handle_t *input,
2098 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002099 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002100 const String8& address,
2101 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002102 audio_input_flags_t flags)
2103{
Glenn Kastene7d66712015-03-05 13:46:52 -08002104 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002105 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002107 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002108 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002109
Glenn Kasteneeecb982016-02-26 10:44:04 -08002110 // Audio Policy can request a specific handle for hardware hotword.
2111 // The goal here is not to re-open an already opened input.
2112 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002113 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002114 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2115 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2116 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2117 return 0;
2118 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2119 // This should not happen in a transient state with current design.
2120 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2121 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002122 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002123
Eric Laurentcf2c0212014-07-25 16:20:43 -07002124 audio_config_t halconfig = *config;
2125 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002126 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002127 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002128 &inStream, flags, address.string(), source);
2129 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002130 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002131 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002132 halconfig.sample_rate,
2133 halconfig.format,
2134 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002135 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002136 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002138 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002139 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002140 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002141 audio_is_linear_pcm(config->format) &&
2142 audio_is_linear_pcm(halconfig.format) &&
2143 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002144 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2145 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002146 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002147 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002148 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002149 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002150 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002151 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 }
2153
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002154 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002155
Glenn Kasten46909e72013-02-26 09:20:22 -08002156#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002157 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2158 // or (re-)create if current Pipe is idle and does not match the new format
2159 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002160 enum {
2161 TEE_SINK_NO, // don't copy input
2162 TEE_SINK_NEW, // copy input using a new pipe
2163 TEE_SINK_OLD, // copy input using an existing pipe
2164 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002165 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2166 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002167 if (!mTeeSinkInputEnabled) {
2168 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002169 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002170 kind = TEE_SINK_NO;
2171 } else if (mRecordTeeSink == 0) {
2172 kind = TEE_SINK_NEW;
2173 } else if (mRecordTeeSink->getStrongCount() != 1) {
2174 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002175 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002176 kind = TEE_SINK_OLD;
2177 } else {
2178 kind = TEE_SINK_NEW;
2179 }
2180 switch (kind) {
2181 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002182 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002183 size_t numCounterOffers = 0;
2184 const NBAIO_Format offers[1] = {format};
2185 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2186 ALOG_ASSERT(index == 0);
2187 PipeReader *pipeReader = new PipeReader(*pipe);
2188 numCounterOffers = 0;
2189 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2190 ALOG_ASSERT(index == 0);
2191 mRecordTeeSink = pipe;
2192 mRecordTeeSource = pipeReader;
2193 teeSink = pipe;
2194 }
2195 break;
2196 case TEE_SINK_OLD:
2197 teeSink = mRecordTeeSink;
2198 break;
2199 case TEE_SINK_NO:
2200 default:
2201 break;
2202 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002203#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002204
Eric Laurent05067782016-06-01 18:27:28 -07002205 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002206
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002207 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002208 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002209 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002210 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002211 inputStream,
2212 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002213 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002214 devices,
2215 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002216#ifdef TEE_SINK
2217 , teeSink
2218#endif
2219 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002220 mRecordThreads.add(*input, thread);
2221 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002222 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 }
2224
Eric Laurentcf2c0212014-07-25 16:20:43 -07002225 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 return 0;
2227}
2228
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002229status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230{
Glenn Kastend96c5722012-04-25 13:44:49 -07002231 return closeInput_nonvirtual(input);
2232}
2233
2234status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2235{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236 // keep strong reference on the record thread so that
2237 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002238 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 {
2240 Mutex::Autolock _l(mLock);
2241 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002242 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 return BAD_VALUE;
2244 }
2245
Steve Block3856b092011-10-20 11:56:00 +01002246 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002247
2248 // If we still have effect chains, it means that a client still holds a handle
2249 // on at least one effect. We must either move the chain to an existing thread with the
2250 // same session ID or put it aside in case a new record thread is opened for a
2251 // new capture on the same session
2252 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002253 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002254 Mutex::Autolock _sl(thread->mLock);
2255 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002256 // Note: maximum one chain per record thread
2257 if (effectChains.size() != 0) {
2258 chain = effectChains[0];
2259 }
2260 }
2261 if (chain != 0) {
2262 // first check if a record thread is already opened with a client on the same session.
2263 // This should only happen in case of overlap between one thread tear down and the
2264 // creation of its replacement
2265 size_t i;
2266 for (i = 0; i < mRecordThreads.size(); i++) {
2267 sp<RecordThread> t = mRecordThreads.valueAt(i);
2268 if (t == thread) {
2269 continue;
2270 }
2271 if (t->hasAudioSession(chain->sessionId()) != 0) {
2272 Mutex::Autolock _l(t->mLock);
2273 ALOGV("closeInput() found thread %d for effect session %d",
2274 t->id(), chain->sessionId());
2275 t->addEffectChain_l(chain);
2276 break;
2277 }
2278 }
2279 // put the chain aside if we could not find a record thread with the same session id.
2280 if (i == mRecordThreads.size()) {
2281 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002282 }
2283 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002284 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2285 ioDesc->mIoHandle = input;
2286 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 mRecordThreads.removeItem(input);
2288 }
Eric Laurent83b88082014-06-20 18:31:16 -07002289 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2290 // we have a different lock for notification client
2291 closeInputFinish(thread);
2292 return NO_ERROR;
2293}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002295void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002296{
2297 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002298 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002299 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002300 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002301 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002302 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002303}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002305void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002306{
2307 mRecordThreads.removeItem(thread->mId);
2308 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309}
2310
Glenn Kastend2304db2014-02-03 07:40:31 -08002311status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312{
2313 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002314 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315
2316 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2317 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002318 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320
2321 return NO_ERROR;
2322}
2323
2324
Glenn Kasteneeecb982016-02-26 10:44:04 -08002325audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326{
Glenn Kasten9d003132016-04-06 14:38:09 -07002327 // This is a binder API, so a malicious client could pass in a bad parameter.
2328 // Check for that before calling the internal API nextUniqueId().
2329 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2330 ALOGE("newAudioUniqueId invalid use %d", use);
2331 return AUDIO_UNIQUE_ID_ALLOCATE;
2332 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002333 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334}
2335
Glenn Kastend848eb42016-03-08 13:42:11 -08002336void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002337{
2338 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002339 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002340 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2341 if (pid != -1 && (caller == getpid_cached)) {
2342 caller = pid;
2343 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002344
Eric Laurent021cf962014-05-13 10:18:14 -07002345 {
2346 Mutex::Autolock _cl(mClientLock);
2347 // Ignore requests received from processes not known as notification client. The request
2348 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2349 // called from a different pid leaving a stale session reference. Also we don't know how
2350 // to clear this reference if the client process dies.
2351 if (mNotificationClients.indexOfKey(caller) < 0) {
2352 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2353 return;
2354 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002355 }
2356
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002357 size_t num = mAudioSessionRefs.size();
2358 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002359 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002360 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2361 ref->mCnt++;
2362 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002363 return;
2364 }
2365 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002366 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2367 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002368}
2369
Glenn Kastend848eb42016-03-08 13:42:11 -08002370void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002371{
2372 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002373 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002374 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2375 if (pid != -1 && (caller == getpid_cached)) {
2376 caller = pid;
2377 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002378 size_t num = mAudioSessionRefs.size();
2379 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002380 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002381 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2382 ref->mCnt--;
2383 ALOGV(" decremented refcount to %d", ref->mCnt);
2384 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002385 mAudioSessionRefs.removeAt(i);
2386 delete ref;
2387 purgeStaleEffects_l();
2388 }
2389 return;
2390 }
2391 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002392 // If the caller is mediaserver it is likely that the session being released was acquired
2393 // on behalf of a process not in notification clients and we ignore the warning.
2394 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002395}
2396
2397void AudioFlinger::purgeStaleEffects_l() {
2398
Steve Block3856b092011-10-20 11:56:00 +01002399 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002400
2401 Vector< sp<EffectChain> > chains;
2402
2403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2404 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2405 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2406 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002407 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2408 chains.push(ec);
2409 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002410 }
2411 }
2412 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2413 sp<RecordThread> t = mRecordThreads.valueAt(i);
2414 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2415 sp<EffectChain> ec = t->mEffectChains[j];
2416 chains.push(ec);
2417 }
2418 }
2419
2420 for (size_t i = 0; i < chains.size(); i++) {
2421 sp<EffectChain> ec = chains[i];
2422 int sessionid = ec->sessionId();
2423 sp<ThreadBase> t = ec->mThread.promote();
2424 if (t == 0) {
2425 continue;
2426 }
2427 size_t numsessionrefs = mAudioSessionRefs.size();
2428 bool found = false;
2429 for (size_t k = 0; k < numsessionrefs; k++) {
2430 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002431 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002432 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002433 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002434 found = true;
2435 break;
2436 }
2437 }
2438 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002439 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002440 // remove all effects from the chain
2441 while (ec->mEffects.size()) {
2442 sp<EffectModule> effect = ec->mEffects[0];
2443 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002444 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002445 if (effect->purgeHandles()) {
2446 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002447 }
2448 AudioSystem::unregisterEffect(effect->id());
2449 }
2450 }
2451 }
2452 return;
2453}
2454
Glenn Kasteneeecb982016-02-26 10:44:04 -08002455// checkThread_l() must be called with AudioFlinger::mLock held
2456AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2457{
2458 ThreadBase *thread = NULL;
2459 switch (audio_unique_id_get_use(ioHandle)) {
2460 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2461 thread = checkPlaybackThread_l(ioHandle);
2462 break;
2463 case AUDIO_UNIQUE_ID_USE_INPUT:
2464 thread = checkRecordThread_l(ioHandle);
2465 break;
2466 default:
2467 break;
2468 }
2469 return thread;
2470}
2471
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002473AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474{
Glenn Kastena1117922012-01-26 10:53:32 -08002475 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476}
2477
2478// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002479AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480{
2481 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002482 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483}
2484
2485// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002486AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487{
Glenn Kastena1117922012-01-26 10:53:32 -08002488 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489}
2490
Glenn Kasteneeecb982016-02-26 10:44:04 -08002491audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492{
Glenn Kasten9d003132016-04-06 14:38:09 -07002493 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002494 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002495 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2496 for (int retry = 0; retry < maxRetries; retry++) {
2497 // The cast allows wraparound from max positive to min negative instead of abort
2498 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2499 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2500 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2501 // allow wrap by skipping 0 and -1 for session ids
2502 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2503 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2504 return (audio_unique_id_t) (base | use);
2505 }
2506 }
2507 // We have no way of recovering from wraparound
2508 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2509 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510}
2511
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002512AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002513{
2514 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2515 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002516 if(thread->isDuplicating()) {
2517 continue;
2518 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002519 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002520 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002521 return thread;
2522 }
2523 }
2524 return NULL;
2525}
2526
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002527audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002528{
2529 PlaybackThread *thread = primaryPlaybackThread_l();
2530
2531 if (thread == NULL) {
2532 return 0;
2533 }
2534
Eric Laurentf1c04f92012-08-28 14:26:53 -07002535 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002536}
2537
Glenn Kastena7335632016-06-09 17:09:53 -07002538AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2539{
2540 size_t minFrameCount = 0;
2541 PlaybackThread *minThread = NULL;
2542 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2543 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2544 if (!thread->isDuplicating()) {
2545 size_t frameCount = thread->frameCountHAL();
2546 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2547 (frameCount == minFrameCount && thread->hasFastMixer() &&
2548 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2549 minFrameCount = frameCount;
2550 minThread = thread;
2551 }
2552 }
2553 }
2554 return minThread;
2555}
2556
Eric Laurenta011e352012-03-29 15:51:43 -07002557sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002558 audio_session_t triggerSession,
2559 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002560 sync_event_callback_t callBack,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002561 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002562{
2563 Mutex::Autolock _l(mLock);
2564
2565 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2566 status_t playStatus = NAME_NOT_FOUND;
2567 status_t recStatus = NAME_NOT_FOUND;
2568 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2569 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2570 if (playStatus == NO_ERROR) {
2571 return event;
2572 }
2573 }
2574 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2575 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2576 if (recStatus == NO_ERROR) {
2577 return event;
2578 }
2579 }
2580 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2581 mPendingSyncEvents.add(event);
2582 } else {
2583 ALOGV("createSyncEvent() invalid event %d", event->type());
2584 event.clear();
2585 }
2586 return event;
2587}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002588
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589// ----------------------------------------------------------------------------
2590// Effect management
2591// ----------------------------------------------------------------------------
2592
2593
Glenn Kastenf587ba52012-01-26 16:25:10 -08002594status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595{
2596 Mutex::Autolock _l(mLock);
2597 return EffectQueryNumberEffects(numEffects);
2598}
2599
Glenn Kastenf587ba52012-01-26 16:25:10 -08002600status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601{
2602 Mutex::Autolock _l(mLock);
2603 return EffectQueryEffect(index, descriptor);
2604}
2605
Glenn Kasten5e92a782012-01-30 07:40:52 -08002606status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002607 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608{
2609 Mutex::Autolock _l(mLock);
2610 return EffectGetDescriptor(pUuid, descriptor);
2611}
2612
2613
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002614sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 effect_descriptor_t *pDesc,
2616 const sp<IEffectClient>& effectClient,
2617 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002618 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002619 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002620 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 status_t *status,
2622 int *id,
2623 int *enabled)
2624{
2625 status_t lStatus = NO_ERROR;
2626 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002629 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002630 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002631 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632
2633 if (pDesc == NULL) {
2634 lStatus = BAD_VALUE;
2635 goto Exit;
2636 }
2637
Eric Laurent84e9a102010-09-23 16:10:16 -07002638 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002639 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002640 lStatus = PERMISSION_DENIED;
2641 goto Exit;
2642 }
2643
Dima Zavinfce7a472011-04-19 22:30:36 -07002644 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002645 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002646 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002647 lStatus = PERMISSION_DENIED;
2648 goto Exit;
2649 }
2650
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 if (!EffectIsNullUuid(&pDesc->uuid)) {
2653 // if uuid is specified, request effect descriptor
2654 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2655 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002656 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 goto Exit;
2658 }
2659 } else {
2660 // if uuid is not specified, look for an available implementation
2661 // of the required type in effect factory
2662 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002663 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 lStatus = BAD_VALUE;
2665 goto Exit;
2666 }
2667 uint32_t numEffects = 0;
2668 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002669 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 bool found = false;
2671
2672 lStatus = EffectQueryNumberEffects(&numEffects);
2673 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002674 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675 goto Exit;
2676 }
2677 for (uint32_t i = 0; i < numEffects; i++) {
2678 lStatus = EffectQueryEffect(i, &desc);
2679 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002680 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 continue;
2682 }
2683 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2684 // If matching type found save effect descriptor. If the session is
2685 // 0 and the effect is not auxiliary, continue enumeration in case
2686 // an auxiliary version of this effect type is available
2687 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002688 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002689 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2691 break;
2692 }
2693 }
2694 }
2695 if (!found) {
2696 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002697 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 goto Exit;
2699 }
2700 // For same effect type, chose auxiliary version over insert version if
2701 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002702 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002704 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 }
2706 }
2707
2708 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002709 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2711 lStatus = INVALID_OPERATION;
2712 goto Exit;
2713 }
2714
Eric Laurent59255e42011-07-27 19:49:51 -07002715 // check recording permission for visualizer
2716 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002717 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002718 lStatus = PERMISSION_DENIED;
2719 goto Exit;
2720 }
2721
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002723 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002724 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002725 // if the output returned by getOutputForEffect() is removed before we lock the
2726 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2727 // and we will exit safely
2728 io = AudioSystem::getOutputForEffect(&desc);
2729 ALOGV("createEffect got output %d", io);
2730 }
2731
2732 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733
2734 // If output is not specified try to find a matching audio session ID in one of the
2735 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002736 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2737 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002738 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002739 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002740 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2741 // output must be specified by AudioPolicyManager when using session
2742 // AUDIO_SESSION_OUTPUT_STAGE
2743 lStatus = BAD_VALUE;
2744 goto Exit;
2745 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002746 // look for the thread where the specified audio session is present
2747 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2748 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2749 io = mPlaybackThreads.keyAt(i);
2750 break;
2751 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002753 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002754 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2755 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2756 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002757 break;
2758 }
2759 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002760 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002761 // If no output thread contains the requested session ID, default to
2762 // first output. The effect chain will be moved to the correct output
2763 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002764 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002765 io = mPlaybackThreads.keyAt(0);
2766 }
Steve Block3856b092011-10-20 11:56:00 +01002767 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002768 }
2769 ThreadBase *thread = checkRecordThread_l(io);
2770 if (thread == NULL) {
2771 thread = checkPlaybackThread_l(io);
2772 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002773 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002774 lStatus = BAD_VALUE;
2775 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002776 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002777 } else {
2778 // Check if one effect chain was awaiting for an effect to be created on this
2779 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002780 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002781 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002782 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002783 thread->addEffectChain_l(chain);
2784 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002786
Eric Laurent021cf962014-05-13 10:18:14 -07002787 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002789 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002790 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2791 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792 if (handle != 0 && id != NULL) {
2793 *id = handle->id();
2794 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002795 if (handle == 0) {
2796 // remove local strong reference to Client with mClientLock held
2797 Mutex::Autolock _cl(mClientLock);
2798 client.clear();
2799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 }
2801
2802Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002803 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804 return handle;
2805}
2806
Glenn Kastend848eb42016-03-08 13:42:11 -08002807status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002808 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002809{
Steve Block3856b092011-10-20 11:56:00 +01002810 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002811 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002812 Mutex::Autolock _l(mLock);
2813 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002814 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002815 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 }
Eric Laurentde070132010-07-13 04:45:46 -07002817 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2818 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002819 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002820 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 }
Eric Laurentde070132010-07-13 04:45:46 -07002822 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2823 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002824 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002825 return BAD_VALUE;
2826 }
2827
2828 Mutex::Autolock _dl(dstThread->mLock);
2829 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002830 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831}
2832
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002833// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002834status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002835 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002836 AudioFlinger::PlaybackThread *dstThread,
2837 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002838{
Steve Block3856b092011-10-20 11:56:00 +01002839 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002840 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002841
Eric Laurent59255e42011-07-27 19:49:51 -07002842 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002843 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002844 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002845 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002846 return INVALID_OPERATION;
2847 }
2848
Eric Laurent4c415062016-06-17 16:14:16 -07002849 // Check whether the destination thread and all effects in the chain are compatible
2850 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002851 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002852 " destination thread %p is not compatible with effects in the chain",
2853 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002854 return INVALID_OPERATION;
2855 }
2856
Eric Laurent39e94f82010-07-28 01:32:47 -07002857 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002858 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002859 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002860 // removed.
2861 srcThread->removeEffectChain_l(chain);
2862
2863 // transfer all effects one by one so that new effect chain is created on new thread with
2864 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002865 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002866 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002867 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002868 Vector< sp<EffectModule> > removed;
2869 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002870 while (effect != 0) {
2871 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002872 removed.add(effect);
2873 status = dstThread->addEffect_l(effect);
2874 if (status != NO_ERROR) {
2875 break;
2876 }
Eric Laurentec35a142011-10-05 17:42:25 -07002877 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2878 if (effect->state() == EffectModule::ACTIVE ||
2879 effect->state() == EffectModule::STOPPING) {
2880 effect->start();
2881 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002882 // if the move request is not received from audio policy manager, the effect must be
2883 // re-registered with the new strategy and output
2884 if (dstChain == 0) {
2885 dstChain = effect->chain().promote();
2886 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002887 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002888 status = NO_INIT;
2889 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002890 }
2891 strategy = dstChain->strategy();
2892 }
2893 if (reRegister) {
2894 AudioSystem::unregisterEffect(effect->id());
2895 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002896 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002897 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002898 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002899 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002900 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002901 }
Eric Laurentde070132010-07-13 04:45:46 -07002902 effect = chain->getEffectFromId_l(0);
2903 }
2904
Eric Laurent5baf2af2013-09-12 17:37:00 -07002905 if (status != NO_ERROR) {
2906 for (size_t i = 0; i < removed.size(); i++) {
2907 srcThread->addEffect_l(removed[i]);
2908 if (dstChain != 0 && reRegister) {
2909 AudioSystem::unregisterEffect(removed[i]->id());
2910 AudioSystem::registerEffect(&removed[i]->desc(),
2911 srcThread->id(),
2912 strategy,
2913 sessionId,
2914 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002915 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002916 }
2917 }
2918 }
2919
2920 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921}
2922
Eric Laurent5baf2af2013-09-12 17:37:00 -07002923bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002924{
2925 if (mGlobalEffectEnableTime != 0 &&
2926 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2927 return true;
2928 }
2929
2930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2931 sp<EffectChain> ec =
2932 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002933 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002934 return true;
2935 }
2936 }
2937 return false;
2938}
2939
Eric Laurent5baf2af2013-09-12 17:37:00 -07002940void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002941{
2942 Mutex::Autolock _l(mLock);
2943
2944 mGlobalEffectEnableTime = systemTime();
2945
2946 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2947 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2948 if (t->mType == ThreadBase::OFFLOAD) {
2949 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2950 }
2951 }
2952
2953}
2954
Eric Laurentaaa44472014-09-12 17:41:50 -07002955status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2956{
Glenn Kastend848eb42016-03-08 13:42:11 -08002957 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002958 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002959 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002960 if (index >= 0) {
2961 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2962 return ALREADY_EXISTS;
2963 }
2964 mOrphanEffectChains.add(session, chain);
2965 return NO_ERROR;
2966}
2967
2968sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2969{
2970 sp<EffectChain> chain;
2971 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002972 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002973 if (index >= 0) {
2974 chain = mOrphanEffectChains.valueAt(index);
2975 mOrphanEffectChains.removeItemsAt(index);
2976 }
2977 return chain;
2978}
2979
2980bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2981{
2982 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002983 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002984 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002985 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002986 if (index >= 0) {
2987 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2988 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002989 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002990 mOrphanEffectChains.removeItemsAt(index);
2991 }
2992 return true;
2993 }
2994 return false;
2995}
2996
2997
Glenn Kastenda6ef132013-01-10 12:31:01 -08002998struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002999#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3000 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003001};
3002
3003int comparEntry(const void *p1, const void *p2)
3004{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003005 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003006}
3007
Glenn Kasten46909e72013-02-26 09:20:22 -08003008#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003009void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010{
Eric Laurent81784c32012-11-19 14:55:58 -08003011 NBAIO_Source *teeSource = source.get();
3012 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003013 // .wav rotation
3014 // There is a benign race condition if 2 threads call this simultaneously.
3015 // They would both traverse the directory, but the result would simply be
3016 // failures at unlink() which are ignored. It's also unlikely since
3017 // normally dumpsys is only done by bugreport or from the command line.
3018 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003019 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003020 size_t teePathLen = strlen(teePath);
3021 DIR *dir = opendir(teePath);
3022 teePath[teePathLen++] = '/';
3023 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003024#define TEE_MAX_SORT 20 // number of entries to sort
3025#define TEE_MAX_KEEP 10 // number of entries to keep
3026 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003027 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003028 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003029 struct dirent de;
3030 struct dirent *result = NULL;
3031 int rc = readdir_r(dir, &de, &result);
3032 if (rc != 0) {
3033 ALOGW("readdir_r failed %d", rc);
3034 break;
3035 }
3036 if (result == NULL) {
3037 break;
3038 }
3039 if (result != &de) {
3040 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3041 break;
3042 }
3043 // ignore non .wav file entries
3044 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003045 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003046 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3047 continue;
3048 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003049 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003050 }
3051 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003052 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003053 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003054 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3055 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003056 (void) unlink(teePath);
3057 }
3058 }
3059 } else {
3060 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003061 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003062 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 }
3064 }
Eric Laurent81784c32012-11-19 14:55:58 -08003065 char teeTime[16];
3066 struct timeval tv;
3067 gettimeofday(&tv, NULL);
3068 struct tm tm;
3069 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003070 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3071 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3072 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3073 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003074 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003075 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003076 char wavHeader[44];
3077 memcpy(wavHeader,
3078 "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",
3079 sizeof(wavHeader));
3080 NBAIO_Format format = teeSource->format();
3081 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003082 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003083 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003084 wavHeader[22] = channelCount; // number of channels
3085 wavHeader[24] = sampleRate; // sample rate
3086 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003087 wavHeader[32] = frameSize; // block alignment
3088 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003089 write(teeFd, wavHeader, sizeof(wavHeader));
3090 size_t total = 0;
3091 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003092#define TEE_SINK_READ 1024 // frames per I/O operation
3093 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003094 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003095 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003096 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003097 bool wasFirstRead = firstRead;
3098 firstRead = false;
3099 if (actual <= 0) {
3100 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3101 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003102 }
Eric Laurent81784c32012-11-19 14:55:58 -08003103 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003104 }
Eric Laurent81784c32012-11-19 14:55:58 -08003105 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003106 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003107 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003108 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003109 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003110 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003111 uint32_t temp = 44 + total * frameSize - 8;
3112 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003113 write(teeFd, &temp, sizeof(temp));
3114 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003115 temp = total * frameSize;
3116 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003117 write(teeFd, &temp, sizeof(temp));
3118 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003119 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003120 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003121 }
Eric Laurent59255e42011-07-27 19:49:51 -07003122 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003123 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003124 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003125 }
Eric Laurent59255e42011-07-27 19:49:51 -07003126 }
3127 }
3128}
Glenn Kasten46909e72013-02-26 09:20:22 -08003129#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003130
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131// ----------------------------------------------------------------------------
3132
3133status_t AudioFlinger::onTransact(
3134 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3135{
3136 return BnAudioFlinger::onTransact(code, data, reply, flags);
3137}
3138
Glenn Kasten63238ef2015-03-02 15:50:29 -08003139} // namespace android