blob: 121ff9d2b896f358bf66d3ea95a47246b167ecf3 [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);
Eric Laurent17a58b22016-08-17 13:53:12 +0200249 // FIXME: bug 30737845: trigger audioserver restart if main audioflinger lock
250 // is held continuously for more than 3 seconds
251 mLockWatch = new LockWatch(mLock, String8("AudioFlinger"));
Eric Laurenta4c5a552012-03-29 10:12:40 -0700252 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253}
254
255AudioFlinger::~AudioFlinger()
256{
257 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700258 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700259 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260 }
261 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700262 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700263 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700265
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800266 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
267 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700268 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
269 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700271
272 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800273 if (mLogMemoryDealer != 0) {
274 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
275 if (binder != 0) {
276 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
277 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
278 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
279 mUnregisteredWriters.pop();
280 mediaLogService->unregisterWriter(iMemory);
281 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700282 }
283 }
Eric Laurent17a58b22016-08-17 13:53:12 +0200284 mLockWatch->requestExitAndWait();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285}
286
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287static const char * const audio_interfaces[] = {
288 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
289 AUDIO_HARDWARE_MODULE_ID_A2DP,
290 AUDIO_HARDWARE_MODULE_ID_USB,
291};
292#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
293
Phil Burk062e67a2015-02-11 13:40:50 -0800294AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700295 audio_module_handle_t module,
296 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700297{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298 // if module is 0, the request comes from an old policy manager and we should load
299 // well known modules
300 if (module == 0) {
301 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
302 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
303 loadHwModule_l(audio_interfaces[i]);
304 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700305 // then try to find a module supporting the requested device.
306 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
307 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
308 audio_hw_device_t *dev = audioHwDevice->hwDevice();
309 if ((dev->get_supported_devices != NULL) &&
310 (dev->get_supported_devices(dev) & devices) == devices)
311 return audioHwDevice;
312 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700313 } else {
314 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700315 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
316 if (audioHwDevice != NULL) {
317 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700318 }
319 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700320
Dima Zavin799a70e2011-04-18 16:57:27 -0700321 return NULL;
322}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700323
Glenn Kasten0f11b512014-01-31 16:18:54 -0800324void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
329
330 result.append("Clients:\n");
331 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800332 sp<Client> client = mClients.valueAt(i).promote();
333 if (client != 0) {
334 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
335 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336 }
337 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700338
Eric Laurentd1b28d42013-09-18 18:47:13 -0700339 result.append("Notification Clients:\n");
340 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
341 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
342 result.append(buffer);
343 }
344
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700345 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800346 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700347 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
348 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800349 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700350 result.append(buffer);
351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
355
Glenn Kasten0f11b512014-01-31 16:18:54 -0800356void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357{
358 const size_t SIZE = 256;
359 char buffer[SIZE];
360 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800361 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362
John Grossman4ff14ba2012-02-08 16:37:41 -0800363 snprintf(buffer, SIZE, "Hardware status: %d\n"
364 "Standby Time mSec: %u\n",
365 hardwareStatus,
366 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 result.append(buffer);
368 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369}
370
Glenn Kasten0f11b512014-01-31 16:18:54 -0800371void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372{
373 const size_t SIZE = 256;
374 char buffer[SIZE];
375 String8 result;
376 snprintf(buffer, SIZE, "Permission Denial: "
377 "can't dump AudioFlinger from pid=%d, uid=%d\n",
378 IPCThreadState::self()->getCallingPid(),
379 IPCThreadState::self()->getCallingUid());
380 result.append(buffer);
381 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382}
383
Eric Laurent81784c32012-11-19 14:55:58 -0800384bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385{
386 bool locked = false;
387 for (int i = 0; i < kDumpLockRetries; ++i) {
388 if (mutex.tryLock() == NO_ERROR) {
389 locked = true;
390 break;
391 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800392 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 }
394 return locked;
395}
396
397status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
398{
Glenn Kasten44deb052012-02-05 18:09:08 -0800399 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 dumpPermissionDenial(fd, args);
401 } else {
402 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800403 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 if (!hardwareLocked) {
405 String8 result(kHardwareLockedString);
406 write(fd, result.string(), result.size());
407 } else {
408 mHardwareLock.unlock();
409 }
410
Eric Laurent81784c32012-11-19 14:55:58 -0800411 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412
413 // failed to lock - AudioFlinger is probably deadlocked
414 if (!locked) {
415 String8 result(kDeadlockedString);
416 write(fd, result.string(), result.size());
417 }
418
Eric Laurent021cf962014-05-13 10:18:14 -0700419 bool clientLocked = dumpTryLock(mClientLock);
420 if (!clientLocked) {
421 String8 result(kClientLockedString);
422 write(fd, result.string(), result.size());
423 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700424
425 EffectDumpEffects(fd);
426
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700428 if (clientLocked) {
429 mClientLock.unlock();
430 }
431
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 dumpInternals(fd, args);
433
434 // dump playback threads
435 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
436 mPlaybackThreads.valueAt(i)->dump(fd, args);
437 }
438
439 // dump record threads
440 for (size_t i = 0; i < mRecordThreads.size(); i++) {
441 mRecordThreads.valueAt(i)->dump(fd, args);
442 }
443
Eric Laurentaaa44472014-09-12 17:41:50 -0700444 // dump orphan effect chains
445 if (mOrphanEffectChains.size() != 0) {
446 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
447 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
448 mOrphanEffectChains.valueAt(i)->dump(fd, args);
449 }
450 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700451 // dump all hardware devs
452 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700453 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700454 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700456
Glenn Kasten46909e72013-02-26 09:20:22 -0800457#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700458 // dump the serially shared record tee sink
459 if (mRecordTeeSource != 0) {
460 dumpTee(fd, mRecordTeeSource);
461 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800462#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700463
Glenn Kastend65d73c2012-06-22 17:21:07 -0700464 if (locked) {
465 mLock.unlock();
466 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800467
468 // append a copy of media.log here by forwarding fd to it, but don't attempt
469 // to lookup the service if it's not running, as it will block for a second
470 if (mLogMemoryDealer != 0) {
471 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
472 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700473 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800474 Vector<String16> args;
475 binder->dump(fd, args);
476 }
477 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700478
479 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700480 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700481 bool unreachableMemory = false;
482 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700483 if (arg == String16("-m")) {
484 dumpMem = true;
485 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700486 unreachableMemory = true;
487 }
488 }
489
Andy Hung07b745e2016-05-23 16:21:07 -0700490 if (dumpMem) {
491 dprintf(fd, "\nDumping memory:\n");
492 std::string s = dumpMemoryAddresses(100 /* limit */);
493 write(fd, s.c_str(), s.size());
494 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700495 if (unreachableMemory) {
496 dprintf(fd, "\nDumping unreachable memory:\n");
497 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700498 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700499 write(fd, s.c_str(), s.size());
500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 }
502 return NO_ERROR;
503}
504
Eric Laurent021cf962014-05-13 10:18:14 -0700505sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800506{
Eric Laurent021cf962014-05-13 10:18:14 -0700507 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800508 // If pid is already in the mClients wp<> map, then use that entry
509 // (for which promote() is always != 0), otherwise create a new entry and Client.
510 sp<Client> client = mClients.valueFor(pid).promote();
511 if (client == 0) {
512 client = new Client(this, pid);
513 mClients.add(pid, client);
514 }
515
516 return client;
517}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518
Glenn Kasten9e58b552013-01-18 15:09:48 -0800519sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
520{
Glenn Kasten481fb672013-09-30 14:39:28 -0700521 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800522 if (mLogMemoryDealer == 0) {
523 return new NBLog::Writer();
524 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800525 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700526 // Similarly if we can't contact the media.log service, also return a dummy writer
527 if (binder == 0) {
528 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800529 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700530 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
531 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
532 // If allocation fails, consult the vector of previously unregistered writers
533 // and garbage-collect one or more them until an allocation succeeds
534 if (shared == 0) {
535 Mutex::Autolock _l(mUnregisteredWritersLock);
536 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
537 {
538 // Pick the oldest stale writer to garbage-collect
539 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
540 mUnregisteredWriters.removeAt(0);
541 mediaLogService->unregisterWriter(iMemory);
542 // Now the media.log remote reference to IMemory is gone. When our last local
543 // reference to IMemory also drops to zero at end of this block,
544 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
545 }
546 // Re-attempt the allocation
547 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
548 if (shared != 0) {
549 goto success;
550 }
551 }
552 // Even after garbage-collecting all old writers, there is still not enough memory,
553 // so return a dummy writer
554 return new NBLog::Writer();
555 }
556success:
557 mediaLogService->registerWriter(shared, size, name);
558 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800559}
560
561void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
562{
Glenn Kasten685ef092013-02-04 08:15:34 -0800563 if (writer == 0) {
564 return;
565 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800566 sp<IMemory> iMemory(writer->getIMemory());
567 if (iMemory == 0) {
568 return;
569 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700570 // Rather than removing the writer immediately, append it to a queue of old writers to
571 // be garbage-collected later. This allows us to continue to view old logs for a while.
572 Mutex::Autolock _l(mUnregisteredWritersLock);
573 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800574}
575
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576// IAudioFlinger interface
577
578
579sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800580 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800582 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700583 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800584 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700585 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800587 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700588 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800589 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800590 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800591 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 status_t *status)
593{
594 sp<PlaybackThread::Track> track;
595 sp<TrackHandle> trackHandle;
596 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800598 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700600 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
601 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
602 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
603 ALOGW_IF(pid != -1 && pid != callingPid,
604 "%s uid %d pid %d tried to pass itself off as pid %d",
605 __func__, callingUid, callingPid, pid);
606 pid = callingPid;
607 }
608
Glenn Kasten263709e2012-01-06 08:40:01 -0800609 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
610 // but if someone uses binder directly they could bypass that and cause us to crash
611 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000612 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 lStatus = BAD_VALUE;
614 goto Exit;
615 }
616
Glenn Kasten53b5d092014-02-05 10:00:23 -0800617 // further sample rate checks are performed by createTrack_l() depending on the thread type
618 if (sampleRate == 0) {
619 ALOGE("createTrack() invalid sample rate %u", sampleRate);
620 lStatus = BAD_VALUE;
621 goto Exit;
622 }
623
624 // further channel mask checks are performed by createTrack_l() depending on the thread type
625 if (!audio_is_output_channel(channelMask)) {
626 ALOGE("createTrack() invalid channel mask %#x", channelMask);
627 lStatus = BAD_VALUE;
628 goto Exit;
629 }
630
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700631 // further format checks are performed by createTrack_l() depending on the thread type
632 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800633 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700634 lStatus = BAD_VALUE;
635 goto Exit;
636 }
637
Glenn Kasten663c2242013-09-24 11:52:37 -0700638 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
639 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
640 lStatus = BAD_VALUE;
641 goto Exit;
642 }
643
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 {
645 Mutex::Autolock _l(mLock);
646 PlaybackThread *thread = checkPlaybackThread_l(output);
647 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800648 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 lStatus = BAD_VALUE;
650 goto Exit;
651 }
652
Eric Laurent021cf962014-05-13 10:18:14 -0700653 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654
Glenn Kastene848bd92014-03-13 15:00:32 -0700655 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700656 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800657 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
658 ALOGE("createTrack() invalid session ID %d", *sessionId);
659 lStatus = BAD_VALUE;
660 goto Exit;
661 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700662 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700663 // check if an effect chain with the same session ID is present on another
664 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700665 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700666 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
667 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700668 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700669 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700670 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700671 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700672 }
Eric Laurentde070132010-07-13 04:45:46 -0700673 }
674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700676 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800677 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 if (sessionId != NULL) {
679 *sessionId = lSessionId;
680 }
681 }
Steve Block3856b092011-10-20 11:56:00 +0100682 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683
684 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800685 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800686 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700687 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700688
689 // move effect chain to this output thread if an effect on same session was waiting
690 // for a track to be created
691 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700692 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700693 Mutex::Autolock _dl(thread->mLock);
694 Mutex::Autolock _sl(effectThread->mLock);
695 moveEffectChain_l(lSessionId, effectThread, thread, true);
696 }
Eric Laurenta011e352012-03-29 15:51:43 -0700697
698 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700699 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700700 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
701 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700702 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700703 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700704 } else {
705 mPendingSyncEvents[i]->cancel();
706 }
Eric Laurenta011e352012-03-29 15:51:43 -0700707 mPendingSyncEvents.removeAt(i);
708 i--;
709 }
710 }
711 }
Glenn Kastene198c362013-08-13 09:13:36 -0700712
Glenn Kastend848eb42016-03-08 13:42:11 -0800713 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714 }
Glenn Kastene198c362013-08-13 09:13:36 -0700715
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700716 if (lStatus != NO_ERROR) {
717 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700718 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700719 // Don't hold mClientLock when releasing the reference on the track as the
720 // destructor will acquire it.
721 {
722 Mutex::Autolock _cl(mClientLock);
723 client.clear();
724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700726 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 }
728
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700729 // return handle to client
730 trackHandle = new TrackHandle(track);
731
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700733 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 return trackHandle;
735}
736
Glenn Kasten2c073da2016-02-26 09:14:08 -0800737uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
739 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800740 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800742 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 return 0;
744 }
745 return thread->sampleRate();
746}
747
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800748audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749{
750 Mutex::Autolock _l(mLock);
751 PlaybackThread *thread = checkPlaybackThread_l(output);
752 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000753 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800754 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 }
756 return thread->format();
757}
758
Glenn Kasten2c073da2016-02-26 09:14:08 -0800759size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760{
761 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800762 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800764 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 return 0;
766 }
Glenn Kasten58912562012-04-03 10:45:00 -0700767 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
768 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 return thread->frameCount();
770}
771
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700772size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
773{
774 Mutex::Autolock _l(mLock);
775 ThreadBase *thread = checkThread_l(ioHandle);
776 if (thread == NULL) {
777 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
778 return 0;
779 }
780 return thread->frameCountHAL();
781}
782
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800783uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784{
785 Mutex::Autolock _l(mLock);
786 PlaybackThread *thread = checkPlaybackThread_l(output);
787 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800788 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 return 0;
790 }
791 return thread->latency();
792}
793
794status_t AudioFlinger::setMasterVolume(float value)
795{
Eric Laurenta1884f92011-08-23 08:25:03 -0700796 status_t ret = initCheck();
797 if (ret != NO_ERROR) {
798 return ret;
799 }
800
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 // check calling permissions
802 if (!settingsAllowed()) {
803 return PERMISSION_DENIED;
804 }
805
Eric Laurenta4c5a552012-03-29 10:12:40 -0700806 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700807 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700808
John Grossmanee578c02012-07-23 17:05:46 -0700809 // Set master volume in the HALs which support it.
810 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
811 AutoMutex lock(mHardwareLock);
812 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800813
John Grossmanee578c02012-07-23 17:05:46 -0700814 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
815 if (dev->canSetMasterVolume()) {
816 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800817 }
John Grossmanee578c02012-07-23 17:05:46 -0700818 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820
John Grossmanee578c02012-07-23 17:05:46 -0700821 // Now set the master volume in each playback thread. Playback threads
822 // assigned to HALs which do not have master volume support will apply
823 // master volume during the mix operation. Threads with HALs which do
824 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700825 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
826 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
827 continue;
828 }
John Grossmanee578c02012-07-23 17:05:46 -0700829 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831
832 return NO_ERROR;
833}
834
Glenn Kastenf78aee72012-01-04 11:00:47 -0800835status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836{
Eric Laurenta1884f92011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return ret;
840 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841
842 // check calling permissions
843 if (!settingsAllowed()) {
844 return PERMISSION_DENIED;
845 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800846 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000847 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 return BAD_VALUE;
849 }
850
851 { // scope for the lock
852 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700853 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700855 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 mHardwareStatus = AUDIO_HW_IDLE;
857 }
858
859 if (NO_ERROR == ret) {
860 Mutex::Autolock _l(mLock);
861 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800862 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700863 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 }
865
866 return ret;
867}
868
869status_t AudioFlinger::setMicMute(bool state)
870{
Eric Laurenta1884f92011-08-23 08:25:03 -0700871 status_t ret = initCheck();
872 if (ret != NO_ERROR) {
873 return ret;
874 }
875
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876 // check calling permissions
877 if (!settingsAllowed()) {
878 return PERMISSION_DENIED;
879 }
880
881 AutoMutex lock(mHardwareLock);
882 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700883 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
884 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
885 status_t result = dev->set_mic_mute(dev, state);
886 if (result != NO_ERROR) {
887 ret = result;
888 }
889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 mHardwareStatus = AUDIO_HW_IDLE;
891 return ret;
892}
893
894bool AudioFlinger::getMicMute() const
895{
Eric Laurenta1884f92011-08-23 08:25:03 -0700896 status_t ret = initCheck();
897 if (ret != NO_ERROR) {
898 return false;
899 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800900 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700901 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800902 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800904 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
905 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
906 status_t result = dev->get_mic_mute(dev, &state);
907 if (result == NO_ERROR) {
908 mute = mute && state;
909 }
910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800912
913 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914}
915
916status_t AudioFlinger::setMasterMute(bool muted)
917{
John Grossmand8f178d2012-07-20 14:51:35 -0700918 status_t ret = initCheck();
919 if (ret != NO_ERROR) {
920 return ret;
921 }
922
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923 // check calling permissions
924 if (!settingsAllowed()) {
925 return PERMISSION_DENIED;
926 }
927
John Grossmanee578c02012-07-23 17:05:46 -0700928 Mutex::Autolock _l(mLock);
929 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700930
John Grossmanee578c02012-07-23 17:05:46 -0700931 // Set master mute in the HALs which support it.
932 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
933 AutoMutex lock(mHardwareLock);
934 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700935
John Grossmanee578c02012-07-23 17:05:46 -0700936 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
937 if (dev->canSetMasterMute()) {
938 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700939 }
John Grossmanee578c02012-07-23 17:05:46 -0700940 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700941 }
942
John Grossmanee578c02012-07-23 17:05:46 -0700943 // Now set the master mute in each playback thread. Playback threads
944 // assigned to HALs which do not have master mute support will apply master
945 // mute during the mix operation. Threads with HALs which do support master
946 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700947 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
948 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
949 continue;
950 }
John Grossmanee578c02012-07-23 17:05:46 -0700951 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700952 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953
954 return NO_ERROR;
955}
956
957float AudioFlinger::masterVolume() const
958{
Glenn Kasten98067102011-12-13 11:47:54 -0800959 Mutex::Autolock _l(mLock);
960 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961}
962
963bool AudioFlinger::masterMute() const
964{
Glenn Kasten98067102011-12-13 11:47:54 -0800965 Mutex::Autolock _l(mLock);
966 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967}
968
John Grossman4ff14ba2012-02-08 16:37:41 -0800969float AudioFlinger::masterVolume_l() const
970{
John Grossman4ff14ba2012-02-08 16:37:41 -0800971 return mMasterVolume;
972}
973
John Grossmand8f178d2012-07-20 14:51:35 -0700974bool AudioFlinger::masterMute_l() const
975{
John Grossmanee578c02012-07-23 17:05:46 -0700976 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700977}
978
Eric Laurent223fd5c2014-11-11 13:43:36 -0800979status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
980{
981 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
982 ALOGW("setStreamVolume() invalid stream %d", stream);
983 return BAD_VALUE;
984 }
985 pid_t caller = IPCThreadState::self()->getCallingPid();
986 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
987 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
988 return PERMISSION_DENIED;
989 }
990
991 return NO_ERROR;
992}
993
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800994status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
995 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
997 // check calling permissions
998 if (!settingsAllowed()) {
999 return PERMISSION_DENIED;
1000 }
1001
Eric Laurent223fd5c2014-11-11 13:43:36 -08001002 status_t status = checkStreamType(stream);
1003 if (status != NO_ERROR) {
1004 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001006 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007
1008 AutoMutex lock(mLock);
1009 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -07001010 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 thread = checkPlaybackThread_l(output);
1012 if (thread == NULL) {
1013 return BAD_VALUE;
1014 }
1015 }
1016
1017 mStreamTypes[stream].volume = value;
1018
1019 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001020 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001021 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 }
1023 } else {
1024 thread->setStreamVolume(stream, value);
1025 }
1026
1027 return NO_ERROR;
1028}
1029
Glenn Kastenfff6d712012-01-12 16:38:12 -08001030status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031{
1032 // check calling permissions
1033 if (!settingsAllowed()) {
1034 return PERMISSION_DENIED;
1035 }
1036
Eric Laurent223fd5c2014-11-11 13:43:36 -08001037 status_t status = checkStreamType(stream);
1038 if (status != NO_ERROR) {
1039 return status;
1040 }
1041 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1042
1043 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001044 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 return BAD_VALUE;
1046 }
1047
Eric Laurent93575202011-01-18 18:39:02 -08001048 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001050 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001051 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052
1053 return NO_ERROR;
1054}
1055
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001056float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001058 status_t status = checkStreamType(stream);
1059 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 return 0.0f;
1061 }
1062
1063 AutoMutex lock(mLock);
1064 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001065 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 PlaybackThread *thread = checkPlaybackThread_l(output);
1067 if (thread == NULL) {
1068 return 0.0f;
1069 }
1070 volume = thread->streamVolume(stream);
1071 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001072 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
1075 return volume;
1076}
1077
Glenn Kastenfff6d712012-01-12 16:38:12 -08001078bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001080 status_t status = checkStreamType(stream);
1081 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 return true;
1083 }
1084
Glenn Kasten6637baa2012-01-09 09:40:36 -08001085 AutoMutex lock(mLock);
1086 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087}
1088
Eric Laurent054d9d32015-04-24 08:48:48 -07001089
1090void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1091{
1092 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1093 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1094 }
1095}
1096
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001097status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001099 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1100 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001101
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 // check calling permissions
1103 if (!settingsAllowed()) {
1104 return PERMISSION_DENIED;
1105 }
1106
Glenn Kasten142f5192014-03-25 17:44:59 -07001107 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1108 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001109 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001110 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001111 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001112 AutoMutex lock(mHardwareLock);
1113 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1114 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1115 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1116 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1117 final_result = result ?: final_result;
1118 }
1119 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001120 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001121 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1122 AudioParameter param = AudioParameter(keyValuePairs);
1123 String8 value;
1124 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001125 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1126 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001127 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1128 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001129 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001130 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1131 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001132 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001133 // suspend effects associated with those session IDs
1134 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001135 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001136 thread->setEffectSuspended(FX_IID_AEC,
1137 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001138 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001139 thread->setEffectSuspended(FX_IID_NS,
1140 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001141 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001142 }
1143 }
Eric Laurentbee53372011-08-29 12:42:48 -07001144 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001145 }
1146 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001147 String8 screenState;
1148 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1149 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001150 if (isOff != (AudioFlinger::mScreenState & 1)) {
1151 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001152 }
1153 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001154 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 }
1156
1157 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1158 // and the thread is exited once the lock is released
1159 sp<ThreadBase> thread;
1160 {
1161 Mutex::Autolock _l(mLock);
1162 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001163 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001165 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001166 // indicate output device change to all input threads for pre processing
1167 AudioParameter param = AudioParameter(keyValuePairs);
1168 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001169 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1170 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001171 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 }
1174 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001175 if (thread != 0) {
1176 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 }
1178 return BAD_VALUE;
1179}
1180
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001181String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001183 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1184 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185
Eric Laurenta4c5a552012-03-29 10:12:40 -07001186 Mutex::Autolock _l(mLock);
1187
Glenn Kasten142f5192014-03-25 17:44:59 -07001188 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001189 String8 out_s8;
1190
Dima Zavin799a70e2011-04-18 16:57:27 -07001191 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001192 char *s;
1193 {
1194 AutoMutex lock(mHardwareLock);
1195 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001196 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001197 s = dev->get_parameters(dev, keys.string());
1198 mHardwareStatus = AUDIO_HW_IDLE;
1199 }
John Grossmanef7740b2012-02-09 11:28:36 -08001200 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001201 free(s);
1202 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001203 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 }
1205
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1207 if (playbackThread != NULL) {
1208 return playbackThread->getParameters(keys);
1209 }
1210 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1211 if (recordThread != NULL) {
1212 return recordThread->getParameters(keys);
1213 }
1214 return String8("");
1215}
1216
Glenn Kastendd8104c2012-07-02 12:42:44 -07001217size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1218 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219{
Eric Laurenta1884f92011-08-23 08:25:03 -07001220 status_t ret = initCheck();
1221 if (ret != NO_ERROR) {
1222 return 0;
1223 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001224 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001225 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001226 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001227 return 0;
1228 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001229
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001230 AutoMutex lock(mHardwareLock);
1231 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001232 audio_config_t config, proposed;
1233 memset(&proposed, 0, sizeof(proposed));
1234 proposed.sample_rate = sampleRate;
1235 proposed.channel_mask = channelMask;
1236 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001237
John Grossmanee578c02012-07-23 17:05:46 -07001238 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001239 size_t frames;
1240 for (;;) {
1241 // Note: config is currently a const parameter for get_input_buffer_size()
1242 // but we use a copy from proposed in case config changes from the call.
1243 config = proposed;
1244 frames = dev->get_input_buffer_size(dev, &config);
1245 if (frames != 0) {
1246 break; // hal success, config is the result
1247 }
1248 // change one parameter of the configuration each iteration to a more "common" value
1249 // to see if the device will support it.
1250 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1251 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1252 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1253 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1254 } else {
1255 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1256 "format %#x, channelMask 0x%X",
1257 sampleRate, format, channelMask);
1258 break; // retries failed, break out of loop with frames == 0.
1259 }
1260 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001261 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001262 if (frames > 0 && config.sample_rate != sampleRate) {
1263 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1264 }
1265 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266}
1267
Glenn Kasten5f972c02014-01-13 09:59:31 -08001268uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 Mutex::Autolock _l(mLock);
1271
1272 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1273 if (recordThread != NULL) {
1274 return recordThread->getInputFramesLost();
1275 }
1276 return 0;
1277}
1278
1279status_t AudioFlinger::setVoiceVolume(float value)
1280{
Eric Laurenta1884f92011-08-23 08:25:03 -07001281 status_t ret = initCheck();
1282 if (ret != NO_ERROR) {
1283 return ret;
1284 }
1285
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 // check calling permissions
1287 if (!settingsAllowed()) {
1288 return PERMISSION_DENIED;
1289 }
1290
1291 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001292 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001293 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001294 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 mHardwareStatus = AUDIO_HW_IDLE;
1296
1297 return ret;
1298}
1299
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001300status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001301 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 Mutex::Autolock _l(mLock);
1304
1305 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1306 if (playbackThread != NULL) {
1307 return playbackThread->getRenderPosition(halFrames, dspFrames);
1308 }
1309
1310 return BAD_VALUE;
1311}
1312
1313void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1314{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001316 if (client == 0) {
1317 return;
1318 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001319 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001320 {
1321 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001322 if (mNotificationClients.indexOfKey(pid) < 0) {
1323 sp<NotificationClient> notificationClient = new NotificationClient(this,
1324 client,
1325 pid);
1326 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327
Eric Laurent021cf962014-05-13 10:18:14 -07001328 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329
Marco Nelissen06b46062014-11-14 07:58:25 -08001330 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001331 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001332 }
1333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334
Eric Laurent021cf962014-05-13 10:18:14 -07001335 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001336 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001337 // the config change is always sent from playback or record threads to avoid deadlock
1338 // with AudioSystem::gLock
1339 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1340 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001343 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1344 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001345 }
1346}
1347
1348void AudioFlinger::removeNotificationClient(pid_t pid)
1349{
1350 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001351 {
1352 Mutex::Autolock _cl(mClientLock);
1353 mNotificationClients.removeItem(pid);
1354 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001355
Steve Block3856b092011-10-20 11:56:00 +01001356 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001357 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001358 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001359 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001360 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001361 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001362 if (ref->mPid == pid) {
1363 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001364 mAudioSessionRefs.removeAt(i);
1365 delete ref;
1366 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001367 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001368 } else {
1369 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001370 }
1371 }
1372 if (removed) {
1373 purgeStaleEffects_l();
1374 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375}
1376
Eric Laurent73e26b62015-04-27 16:55:58 -07001377void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001378 const sp<AudioIoDescriptor>& ioDesc,
1379 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380{
Eric Laurent021cf962014-05-13 10:18:14 -07001381 Mutex::Autolock _l(mClientLock);
1382 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001384 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1385 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1386 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 }
1388}
1389
Eric Laurent021cf962014-05-13 10:18:14 -07001390// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391void AudioFlinger::removeClient_l(pid_t pid)
1392{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001393 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001394 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 mClients.removeItem(pid);
1396}
1397
Eric Laurent717e1282012-06-29 16:36:52 -07001398// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001399sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1400 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001401{
1402 sp<PlaybackThread> thread;
1403
1404 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1405 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1406 ALOG_ASSERT(thread == 0);
1407 thread = mPlaybackThreads.valueAt(i);
1408 }
1409 }
1410
1411 return thread;
1412}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415
1416// ----------------------------------------------------------------------------
1417
1418AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1419 : RefBase(),
1420 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001421 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301423 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1424 heapSize *= 1024;
1425 if (!heapSize) {
1426 heapSize = kClientSharedHeapSizeBytes;
1427 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1428 // invalidated tracks
1429 if (!audioFlinger->isLowRamDevice()) {
1430 heapSize *= kClientSharedHeapSizeMultiplier;
1431 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001432 }
1433 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434}
1435
Eric Laurent021cf962014-05-13 10:18:14 -07001436// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437AudioFlinger::Client::~Client()
1438{
1439 mAudioFlinger->removeClient_l(mPid);
1440}
1441
Glenn Kasten435dbe62012-01-30 10:15:48 -08001442sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443{
1444 return mMemoryDealer;
1445}
1446
1447// ----------------------------------------------------------------------------
1448
1449AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1450 const sp<IAudioFlingerClient>& client,
1451 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001452 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453{
1454}
1455
1456AudioFlinger::NotificationClient::~NotificationClient()
1457{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001458}
1459
Glenn Kasten0f11b512014-01-31 16:18:54 -08001460void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001461{
1462 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001463 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464}
1465
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466
1467// ----------------------------------------------------------------------------
1468
1469sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001470 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001472 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001473 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001474 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001475 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001476 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001477 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001478 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001479 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001480 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001481 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001482 sp<IMemory>& cblk,
1483 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 status_t *status)
1485{
1486 sp<RecordThread::RecordTrack> recordTrack;
1487 sp<RecordHandle> recordHandle;
1488 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001490 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491
Glenn Kastend776ac62014-05-07 09:16:09 -07001492 cblk.clear();
1493 buffers.clear();
1494
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001495 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001496 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1497 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001498 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001499 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1500 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001501 updatePid = true;
1502 }
1503
1504 if (updatePid) {
1505 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1506 ALOGW_IF(pid != -1 && pid != callingPid,
1507 "%s uid %d pid %d tried to pass itself off as pid %d",
1508 __func__, callingUid, callingPid, pid);
1509 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001510 }
1511
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001513 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001514 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 lStatus = PERMISSION_DENIED;
1516 goto Exit;
1517 }
1518
Glenn Kasten53b5d092014-02-05 10:00:23 -08001519 // further sample rate checks are performed by createRecordTrack_l()
1520 if (sampleRate == 0) {
1521 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
1525
Andy Hung6770c6f2015-04-07 13:43:36 -07001526 // we don't yet support anything other than linear PCM
1527 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001528 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001529 lStatus = BAD_VALUE;
1530 goto Exit;
1531 }
1532
Glenn Kasten53b5d092014-02-05 10:00:23 -08001533 // further channel mask checks are performed by createRecordTrack_l()
1534 if (!audio_is_input_channel(channelMask)) {
1535 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1536 lStatus = BAD_VALUE;
1537 goto Exit;
1538 }
1539
Glenn Kasten05997e22014-03-13 15:08:33 -07001540 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001542 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001544 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 lStatus = BAD_VALUE;
1546 goto Exit;
1547 }
1548
Eric Laurent021cf962014-05-13 10:18:14 -07001549 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001551 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001552 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1553 lStatus = BAD_VALUE;
1554 goto Exit;
1555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 lSessionId = *sessionId;
1557 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001558 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001559 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 if (sessionId != NULL) {
1561 *sessionId = lSessionId;
1562 }
1563 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001564 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001565
Glenn Kasten1879fff2012-07-11 15:36:59 -07001566 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001567 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001568 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001569 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001570
1571 if (lStatus == NO_ERROR) {
1572 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1573 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001574 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001575 if (chain != 0) {
1576 Mutex::Autolock _l(thread->mLock);
1577 thread->addEffectChain_l(chain);
1578 }
1579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 }
Glenn Kastene198c362013-08-13 09:13:36 -07001581
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001582 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001583 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001584 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001585 // Don't hold mClientLock when releasing the reference on the track as the
1586 // destructor will acquire it.
1587 {
1588 Mutex::Autolock _cl(mClientLock);
1589 client.clear();
1590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 goto Exit;
1593 }
1594
Glenn Kastend776ac62014-05-07 09:16:09 -07001595 cblk = recordTrack->getCblk();
1596 buffers = recordTrack->getBuffers();
1597
Glenn Kasten2fc14732013-08-05 14:58:14 -07001598 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600
1601Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001602 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 return recordHandle;
1604}
1605
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001606
1607
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608// ----------------------------------------------------------------------------
1609
Eric Laurenta4c5a552012-03-29 10:12:40 -07001610audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1611{
Eric Laurent44622db2014-08-01 19:00:33 -07001612 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001613 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001614 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001615 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001616 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001617 }
1618 Mutex::Autolock _l(mLock);
1619 return loadHwModule_l(name);
1620}
1621
1622// loadHwModule_l() must be called with AudioFlinger::mLock held
1623audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1624{
1625 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1626 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1627 ALOGW("loadHwModule() module %s already loaded", name);
1628 return mAudioHwDevs.keyAt(i);
1629 }
1630 }
1631
Eric Laurenta4c5a552012-03-29 10:12:40 -07001632 audio_hw_device_t *dev;
1633
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001634 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001635 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001636 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001637 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001638 }
1639
1640 mHardwareStatus = AUDIO_HW_INIT;
1641 rc = dev->init_check(dev);
1642 mHardwareStatus = AUDIO_HW_IDLE;
1643 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001644 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001645 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001646 }
1647
John Grossmanee578c02012-07-23 17:05:46 -07001648 // Check and cache this HAL's level of support for master mute and master
1649 // volume. If this is the first HAL opened, and it supports the get
1650 // methods, use the initial values provided by the HAL as the current
1651 // master mute and volume settings.
1652
1653 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1654 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001655 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001656
1657 if (0 == mAudioHwDevs.size()) {
1658 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1659 if (NULL != dev->get_master_volume) {
1660 float mv;
1661 if (OK == dev->get_master_volume(dev, &mv)) {
1662 mMasterVolume = mv;
1663 }
1664 }
1665
1666 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1667 if (NULL != dev->get_master_mute) {
1668 bool mm;
1669 if (OK == dev->get_master_mute(dev, &mm)) {
1670 mMasterMute = mm;
1671 }
1672 }
1673 }
1674
Eric Laurenta4c5a552012-03-29 10:12:40 -07001675 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001676 if ((NULL != dev->set_master_volume) &&
1677 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1678 flags = static_cast<AudioHwDevice::Flags>(flags |
1679 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1680 }
1681
1682 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1683 if ((NULL != dev->set_master_mute) &&
1684 (OK == dev->set_master_mute(dev, mMasterMute))) {
1685 flags = static_cast<AudioHwDevice::Flags>(flags |
1686 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1687 }
1688
Eric Laurenta4c5a552012-03-29 10:12:40 -07001689 mHardwareStatus = AUDIO_HW_IDLE;
1690 }
1691
Glenn Kastena13cde92016-03-28 15:26:02 -07001692 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001693 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001694
1695 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001696 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001697
1698 return handle;
1699
1700}
1701
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001702// ----------------------------------------------------------------------------
1703
Glenn Kasten3b16c762012-11-14 08:44:39 -08001704uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001705{
1706 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001707 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001708 return thread != NULL ? thread->sampleRate() : 0;
1709}
1710
Glenn Kastene33054e2012-11-14 12:54:39 -08001711size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001712{
1713 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001714 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001715 return thread != NULL ? thread->frameCountHAL() : 0;
1716}
1717
1718// ----------------------------------------------------------------------------
1719
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001720status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1721{
1722 uid_t uid = IPCThreadState::self()->getCallingUid();
1723 if (uid != AID_SYSTEM) {
1724 return PERMISSION_DENIED;
1725 }
1726 Mutex::Autolock _l(mLock);
1727 if (mIsDeviceTypeKnown) {
1728 return INVALID_OPERATION;
1729 }
1730 mIsLowRamDevice = isLowRamDevice;
1731 mIsDeviceTypeKnown = true;
1732 return NO_ERROR;
1733}
1734
Eric Laurent93c3d412014-08-01 14:48:35 -07001735audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1736{
1737 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001738
1739 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1740 if (index >= 0) {
1741 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1742 mHwAvSyncIds.valueAt(index), sessionId);
1743 return mHwAvSyncIds.valueAt(index);
1744 }
1745
1746 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1747 if (dev == NULL) {
1748 return AUDIO_HW_SYNC_INVALID;
1749 }
1750 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1751 AudioParameter param = AudioParameter(String8(reply));
1752 free(reply);
1753
1754 int value;
1755 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1756 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1757 return AUDIO_HW_SYNC_INVALID;
1758 }
1759
1760 // allow only one session for a given HW A/V sync ID.
1761 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1762 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1763 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1764 value, mHwAvSyncIds.keyAt(i));
1765 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001766 break;
1767 }
1768 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001769
1770 mHwAvSyncIds.add(sessionId, value);
1771
1772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1773 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1774 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001775 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001776 AudioParameter param = AudioParameter();
1777 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1778 thread->setParameters(param.toString());
1779 break;
1780 }
1781 }
1782
1783 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1784 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001785}
1786
Eric Laurent72e3f392015-05-20 14:43:50 -07001787status_t AudioFlinger::systemReady()
1788{
1789 Mutex::Autolock _l(mLock);
1790 ALOGI("%s", __FUNCTION__);
1791 if (mSystemReady) {
1792 ALOGW("%s called twice", __FUNCTION__);
1793 return NO_ERROR;
1794 }
1795 mSystemReady = true;
1796 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1797 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1798 thread->systemReady();
1799 }
1800 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1801 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1802 thread->systemReady();
1803 }
1804 return NO_ERROR;
1805}
1806
Eric Laurentfa90e842014-10-17 18:12:31 -07001807// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1808void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1809{
1810 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1811 if (index >= 0) {
1812 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1813 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1814 AudioParameter param = AudioParameter();
1815 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1816 thread->setParameters(param.toString());
1817 }
1818}
1819
1820
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001821// ----------------------------------------------------------------------------
1822
Eric Laurent83b88082014-06-20 18:31:16 -07001823
1824sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001825 audio_io_handle_t *output,
1826 audio_config_t *config,
1827 audio_devices_t devices,
1828 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001829 audio_output_flags_t flags)
1830{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001831 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001832 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001833 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001834 }
1835
Eric Laurentcf2c0212014-07-25 16:20:43 -07001836 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001837 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1838 } else {
1839 // Audio Policy does not currently request a specific output handle.
1840 // If this is ever needed, see openInput_l() for example code.
1841 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1842 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001843 }
Eric Laurent83b88082014-06-20 18:31:16 -07001844
1845 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1846
Eric Laurent83b88082014-06-20 18:31:16 -07001847 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001848 // This if statement allows overriding the audio policy settings
1849 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1850 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1851 // Check only for Normal Mixing mode
1852 if (kEnableExtendedPrecision) {
1853 // Specify format (uncomment one below to choose)
1854 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1855 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1856 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1857 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001858 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001859 }
1860 if (kEnableExtendedChannels) {
1861 // Specify channel mask (uncomment one below to choose)
1862 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1863 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1864 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1865 }
Eric Laurent83b88082014-06-20 18:31:16 -07001866 }
1867
Phil Burk062e67a2015-02-11 13:40:50 -08001868 AudioStreamOut *outputStream = NULL;
1869 status_t status = outHwDev->openOutputStream(
1870 &outputStream,
1871 *output,
1872 devices,
1873 flags,
1874 config,
1875 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001876
1877 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001878
Phil Burk062e67a2015-02-11 13:40:50 -08001879 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001880
1881 PlaybackThread *thread;
1882 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001883 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001884 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001885 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1886 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001887 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001888 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001889 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001890 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001891 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001893 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001894 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001895 return thread;
1896 }
1897
1898 return 0;
1899}
1900
Eric Laurentcf2c0212014-07-25 16:20:43 -07001901status_t AudioFlinger::openOutput(audio_module_handle_t module,
1902 audio_io_handle_t *output,
1903 audio_config_t *config,
1904 audio_devices_t *devices,
1905 const String8& address,
1906 uint32_t *latencyMs,
1907 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908{
Phil Burk062e67a2015-02-11 13:40:50 -08001909 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001910 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001911 (devices != NULL) ? *devices : 0,
1912 config->sample_rate,
1913 config->format,
1914 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001915 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
Eric Laurentcf2c0212014-07-25 16:20:43 -07001917 if (*devices == AUDIO_DEVICE_NONE) {
1918 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001920
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 Mutex::Autolock _l(mLock);
1922
Eric Laurentcf2c0212014-07-25 16:20:43 -07001923 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001924 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001925 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926
1927 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001928 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001929
1930 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001931 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001932 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001933 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001934
1935 AutoMutex lock(mHardwareLock);
1936 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001937 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001938 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001939 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001940 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 }
1942
Eric Laurentcf2c0212014-07-25 16:20:43 -07001943 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944}
1945
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001946audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1947 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948{
1949 Mutex::Autolock _l(mLock);
1950 MixerThread *thread1 = checkMixerThread_l(output1);
1951 MixerThread *thread2 = checkMixerThread_l(output2);
1952
1953 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001954 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1955 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001956 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 }
1958
Glenn Kasteneeecb982016-02-26 10:44:04 -08001959 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001960 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 thread->addOutputTrack(thread2);
1962 mPlaybackThreads.add(id, thread);
1963 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001964 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 return id;
1966}
1967
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001968status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969{
Glenn Kastend96c5722012-04-25 13:44:49 -07001970 return closeOutput_nonvirtual(output);
1971}
1972
1973status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1974{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 // keep strong reference on the playback thread so that
1976 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001977 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 {
1979 Mutex::Autolock _l(mLock);
1980 thread = checkPlaybackThread_l(output);
1981 if (thread == NULL) {
1982 return BAD_VALUE;
1983 }
1984
Steve Block3856b092011-10-20 11:56:00 +01001985 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001987 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001989 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001990 DuplicatingThread *dupThread =
1991 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001993 }
1994 }
1995 }
1996
1997
1998 mPlaybackThreads.removeItem(output);
1999 // save all effects to the default thread
2000 if (mPlaybackThreads.size()) {
2001 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2002 if (dstThread != NULL) {
2003 // audioflinger lock is held here so the acquisition order of thread locks does not
2004 // matter
2005 Mutex::Autolock _dl(dstThread->mLock);
2006 Mutex::Autolock _sl(thread->mLock);
2007 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2008 for (size_t i = 0; i < effectChains.size(); i ++) {
2009 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 }
2011 }
2012 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002013 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2014 ioDesc->mIoHandle = output;
2015 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 }
2017 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002018 // The thread entity (active unit of execution) is no longer running here,
2019 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020
Eric Laurentf6870ae2015-05-08 10:50:03 -07002021 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002022 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 }
Eric Laurent83b88082014-06-20 18:31:16 -07002024
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 return NO_ERROR;
2026}
2027
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002028void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002029{
2030 AudioStreamOut *out = thread->clearOutput();
2031 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2032 // from now on thread->mOutput is NULL
2033 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
2034 delete out;
2035}
2036
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002037void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002038{
2039 mPlaybackThreads.removeItem(thread->mId);
2040 thread->exit();
2041 closeOutputFinish(thread);
2042}
2043
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002044status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045{
2046 Mutex::Autolock _l(mLock);
2047 PlaybackThread *thread = checkPlaybackThread_l(output);
2048
2049 if (thread == NULL) {
2050 return BAD_VALUE;
2051 }
2052
Steve Block3856b092011-10-20 11:56:00 +01002053 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 thread->suspend();
2055
2056 return NO_ERROR;
2057}
2058
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002059status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060{
2061 Mutex::Autolock _l(mLock);
2062 PlaybackThread *thread = checkPlaybackThread_l(output);
2063
2064 if (thread == NULL) {
2065 return BAD_VALUE;
2066 }
2067
Steve Block3856b092011-10-20 11:56:00 +01002068 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069
2070 thread->restore();
2071
2072 return NO_ERROR;
2073}
2074
Eric Laurentcf2c0212014-07-25 16:20:43 -07002075status_t AudioFlinger::openInput(audio_module_handle_t module,
2076 audio_io_handle_t *input,
2077 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002078 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002079 const String8& address,
2080 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002081 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082{
Eric Laurent83b88082014-06-20 18:31:16 -07002083 Mutex::Autolock _l(mLock);
2084
Glenn Kastene7d66712015-03-05 13:46:52 -08002085 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002087 }
2088
Glenn Kastene7d66712015-03-05 13:46:52 -08002089 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002090
2091 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002092 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002093 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002094 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002096 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002097}
Dima Zavin799a70e2011-04-18 16:57:27 -07002098
Eric Laurent83b88082014-06-20 18:31:16 -07002099sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002100 audio_io_handle_t *input,
2101 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002102 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002103 const String8& address,
2104 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002105 audio_input_flags_t flags)
2106{
Glenn Kastene7d66712015-03-05 13:46:52 -08002107 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002108 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002109 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002110 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002111 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002112
Glenn Kasteneeecb982016-02-26 10:44:04 -08002113 // Audio Policy can request a specific handle for hardware hotword.
2114 // The goal here is not to re-open an already opened input.
2115 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002116 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002117 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2118 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2119 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2120 return 0;
2121 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2122 // This should not happen in a transient state with current design.
2123 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2124 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002125 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002126
Eric Laurentcf2c0212014-07-25 16:20:43 -07002127 audio_config_t halconfig = *config;
2128 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002129 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002130 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002131 &inStream, flags, address.string(), source);
2132 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002133 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002134 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002135 halconfig.sample_rate,
2136 halconfig.format,
2137 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002138 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002139 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002141 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002142 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002143 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002144 audio_is_linear_pcm(config->format) &&
2145 audio_is_linear_pcm(halconfig.format) &&
2146 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002147 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2148 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002149 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002150 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002151 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002152 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002153 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002154 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 }
2156
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002157 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002158
Glenn Kasten46909e72013-02-26 09:20:22 -08002159#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002160 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2161 // or (re-)create if current Pipe is idle and does not match the new format
2162 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002163 enum {
2164 TEE_SINK_NO, // don't copy input
2165 TEE_SINK_NEW, // copy input using a new pipe
2166 TEE_SINK_OLD, // copy input using an existing pipe
2167 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002168 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2169 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002170 if (!mTeeSinkInputEnabled) {
2171 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002172 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002173 kind = TEE_SINK_NO;
2174 } else if (mRecordTeeSink == 0) {
2175 kind = TEE_SINK_NEW;
2176 } else if (mRecordTeeSink->getStrongCount() != 1) {
2177 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002178 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002179 kind = TEE_SINK_OLD;
2180 } else {
2181 kind = TEE_SINK_NEW;
2182 }
2183 switch (kind) {
2184 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002185 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002186 size_t numCounterOffers = 0;
2187 const NBAIO_Format offers[1] = {format};
2188 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2189 ALOG_ASSERT(index == 0);
2190 PipeReader *pipeReader = new PipeReader(*pipe);
2191 numCounterOffers = 0;
2192 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2193 ALOG_ASSERT(index == 0);
2194 mRecordTeeSink = pipe;
2195 mRecordTeeSource = pipeReader;
2196 teeSink = pipe;
2197 }
2198 break;
2199 case TEE_SINK_OLD:
2200 teeSink = mRecordTeeSink;
2201 break;
2202 case TEE_SINK_NO:
2203 default:
2204 break;
2205 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002206#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002207
Eric Laurent05067782016-06-01 18:27:28 -07002208 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002209
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002210 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002211 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002212 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002213 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002214 inputStream,
2215 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002216 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002217 devices,
2218 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002219#ifdef TEE_SINK
2220 , teeSink
2221#endif
2222 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002223 mRecordThreads.add(*input, thread);
2224 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002225 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 }
2227
Eric Laurentcf2c0212014-07-25 16:20:43 -07002228 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 return 0;
2230}
2231
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002232status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233{
Glenn Kastend96c5722012-04-25 13:44:49 -07002234 return closeInput_nonvirtual(input);
2235}
2236
2237status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2238{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 // keep strong reference on the record thread so that
2240 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002241 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 {
2243 Mutex::Autolock _l(mLock);
2244 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002245 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 return BAD_VALUE;
2247 }
2248
Steve Block3856b092011-10-20 11:56:00 +01002249 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002250
2251 // If we still have effect chains, it means that a client still holds a handle
2252 // on at least one effect. We must either move the chain to an existing thread with the
2253 // same session ID or put it aside in case a new record thread is opened for a
2254 // new capture on the same session
2255 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002256 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002257 Mutex::Autolock _sl(thread->mLock);
2258 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002259 // Note: maximum one chain per record thread
2260 if (effectChains.size() != 0) {
2261 chain = effectChains[0];
2262 }
2263 }
2264 if (chain != 0) {
2265 // first check if a record thread is already opened with a client on the same session.
2266 // This should only happen in case of overlap between one thread tear down and the
2267 // creation of its replacement
2268 size_t i;
2269 for (i = 0; i < mRecordThreads.size(); i++) {
2270 sp<RecordThread> t = mRecordThreads.valueAt(i);
2271 if (t == thread) {
2272 continue;
2273 }
2274 if (t->hasAudioSession(chain->sessionId()) != 0) {
2275 Mutex::Autolock _l(t->mLock);
2276 ALOGV("closeInput() found thread %d for effect session %d",
2277 t->id(), chain->sessionId());
2278 t->addEffectChain_l(chain);
2279 break;
2280 }
2281 }
2282 // put the chain aside if we could not find a record thread with the same session id.
2283 if (i == mRecordThreads.size()) {
2284 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002285 }
2286 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002287 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2288 ioDesc->mIoHandle = input;
2289 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 mRecordThreads.removeItem(input);
2291 }
Eric Laurent83b88082014-06-20 18:31:16 -07002292 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2293 // we have a different lock for notification client
2294 closeInputFinish(thread);
2295 return NO_ERROR;
2296}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002298void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002299{
2300 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002301 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002302 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002303 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002304 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002305 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002306}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002308void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002309{
2310 mRecordThreads.removeItem(thread->mId);
2311 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312}
2313
Glenn Kastend2304db2014-02-03 07:40:31 -08002314status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315{
2316 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002317 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318
2319 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2320 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002321 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323
2324 return NO_ERROR;
2325}
2326
2327
Glenn Kasteneeecb982016-02-26 10:44:04 -08002328audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329{
Glenn Kasten9d003132016-04-06 14:38:09 -07002330 // This is a binder API, so a malicious client could pass in a bad parameter.
2331 // Check for that before calling the internal API nextUniqueId().
2332 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2333 ALOGE("newAudioUniqueId invalid use %d", use);
2334 return AUDIO_UNIQUE_ID_ALLOCATE;
2335 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002336 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337}
2338
Glenn Kastend848eb42016-03-08 13:42:11 -08002339void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002340{
2341 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002342 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002343 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2344 if (pid != -1 && (caller == getpid_cached)) {
2345 caller = pid;
2346 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002347
Eric Laurent021cf962014-05-13 10:18:14 -07002348 {
2349 Mutex::Autolock _cl(mClientLock);
2350 // Ignore requests received from processes not known as notification client. The request
2351 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2352 // called from a different pid leaving a stale session reference. Also we don't know how
2353 // to clear this reference if the client process dies.
2354 if (mNotificationClients.indexOfKey(caller) < 0) {
2355 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2356 return;
2357 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002358 }
2359
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002360 size_t num = mAudioSessionRefs.size();
2361 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002362 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002363 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2364 ref->mCnt++;
2365 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002366 return;
2367 }
2368 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002369 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2370 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002371}
2372
Glenn Kastend848eb42016-03-08 13:42:11 -08002373void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002374{
2375 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002376 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002377 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2378 if (pid != -1 && (caller == getpid_cached)) {
2379 caller = pid;
2380 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002381 size_t num = mAudioSessionRefs.size();
2382 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002383 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002384 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2385 ref->mCnt--;
2386 ALOGV(" decremented refcount to %d", ref->mCnt);
2387 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002388 mAudioSessionRefs.removeAt(i);
2389 delete ref;
2390 purgeStaleEffects_l();
2391 }
2392 return;
2393 }
2394 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002395 // If the caller is mediaserver it is likely that the session being released was acquired
2396 // on behalf of a process not in notification clients and we ignore the warning.
2397 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002398}
2399
2400void AudioFlinger::purgeStaleEffects_l() {
2401
Steve Block3856b092011-10-20 11:56:00 +01002402 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002403
2404 Vector< sp<EffectChain> > chains;
2405
2406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2407 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2408 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2409 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002410 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2411 chains.push(ec);
2412 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002413 }
2414 }
2415 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2416 sp<RecordThread> t = mRecordThreads.valueAt(i);
2417 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2418 sp<EffectChain> ec = t->mEffectChains[j];
2419 chains.push(ec);
2420 }
2421 }
2422
2423 for (size_t i = 0; i < chains.size(); i++) {
2424 sp<EffectChain> ec = chains[i];
2425 int sessionid = ec->sessionId();
2426 sp<ThreadBase> t = ec->mThread.promote();
2427 if (t == 0) {
2428 continue;
2429 }
2430 size_t numsessionrefs = mAudioSessionRefs.size();
2431 bool found = false;
2432 for (size_t k = 0; k < numsessionrefs; k++) {
2433 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002434 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002435 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002436 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002437 found = true;
2438 break;
2439 }
2440 }
2441 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002442 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002443 // remove all effects from the chain
2444 while (ec->mEffects.size()) {
2445 sp<EffectModule> effect = ec->mEffects[0];
2446 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002447 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002448 if (effect->purgeHandles()) {
2449 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002450 }
2451 AudioSystem::unregisterEffect(effect->id());
2452 }
2453 }
2454 }
2455 return;
2456}
2457
Glenn Kasteneeecb982016-02-26 10:44:04 -08002458// checkThread_l() must be called with AudioFlinger::mLock held
2459AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2460{
2461 ThreadBase *thread = NULL;
2462 switch (audio_unique_id_get_use(ioHandle)) {
2463 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2464 thread = checkPlaybackThread_l(ioHandle);
2465 break;
2466 case AUDIO_UNIQUE_ID_USE_INPUT:
2467 thread = checkRecordThread_l(ioHandle);
2468 break;
2469 default:
2470 break;
2471 }
2472 return thread;
2473}
2474
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002476AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477{
Glenn Kastena1117922012-01-26 10:53:32 -08002478 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479}
2480
2481// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002482AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483{
2484 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002485 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486}
2487
2488// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002489AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490{
Glenn Kastena1117922012-01-26 10:53:32 -08002491 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492}
2493
Glenn Kasteneeecb982016-02-26 10:44:04 -08002494audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495{
Glenn Kasten9d003132016-04-06 14:38:09 -07002496 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002497 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002498 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2499 for (int retry = 0; retry < maxRetries; retry++) {
2500 // The cast allows wraparound from max positive to min negative instead of abort
2501 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2502 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2503 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2504 // allow wrap by skipping 0 and -1 for session ids
2505 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2506 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2507 return (audio_unique_id_t) (base | use);
2508 }
2509 }
2510 // We have no way of recovering from wraparound
2511 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2512 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513}
2514
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002515AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002516{
2517 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2518 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002519 if(thread->isDuplicating()) {
2520 continue;
2521 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002522 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002523 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002524 return thread;
2525 }
2526 }
2527 return NULL;
2528}
2529
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002530audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002531{
2532 PlaybackThread *thread = primaryPlaybackThread_l();
2533
2534 if (thread == NULL) {
2535 return 0;
2536 }
2537
Eric Laurentf1c04f92012-08-28 14:26:53 -07002538 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002539}
2540
Glenn Kastena7335632016-06-09 17:09:53 -07002541AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2542{
2543 size_t minFrameCount = 0;
2544 PlaybackThread *minThread = NULL;
2545 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2546 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2547 if (!thread->isDuplicating()) {
2548 size_t frameCount = thread->frameCountHAL();
2549 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2550 (frameCount == minFrameCount && thread->hasFastMixer() &&
2551 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2552 minFrameCount = frameCount;
2553 minThread = thread;
2554 }
2555 }
2556 }
2557 return minThread;
2558}
2559
Eric Laurenta011e352012-03-29 15:51:43 -07002560sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002561 audio_session_t triggerSession,
2562 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002563 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002564 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002565{
2566 Mutex::Autolock _l(mLock);
2567
2568 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2569 status_t playStatus = NAME_NOT_FOUND;
2570 status_t recStatus = NAME_NOT_FOUND;
2571 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2572 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2573 if (playStatus == NO_ERROR) {
2574 return event;
2575 }
2576 }
2577 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2578 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2579 if (recStatus == NO_ERROR) {
2580 return event;
2581 }
2582 }
2583 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2584 mPendingSyncEvents.add(event);
2585 } else {
2586 ALOGV("createSyncEvent() invalid event %d", event->type());
2587 event.clear();
2588 }
2589 return event;
2590}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002591
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592// ----------------------------------------------------------------------------
2593// Effect management
2594// ----------------------------------------------------------------------------
2595
2596
Glenn Kastenf587ba52012-01-26 16:25:10 -08002597status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598{
2599 Mutex::Autolock _l(mLock);
2600 return EffectQueryNumberEffects(numEffects);
2601}
2602
Glenn Kastenf587ba52012-01-26 16:25:10 -08002603status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604{
2605 Mutex::Autolock _l(mLock);
2606 return EffectQueryEffect(index, descriptor);
2607}
2608
Glenn Kasten5e92a782012-01-30 07:40:52 -08002609status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002610 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611{
2612 Mutex::Autolock _l(mLock);
2613 return EffectGetDescriptor(pUuid, descriptor);
2614}
2615
2616
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002617sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 effect_descriptor_t *pDesc,
2619 const sp<IEffectClient>& effectClient,
2620 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002621 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002622 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002623 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 status_t *status,
2625 int *id,
2626 int *enabled)
2627{
2628 status_t lStatus = NO_ERROR;
2629 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002632 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002633 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002634 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635
2636 if (pDesc == NULL) {
2637 lStatus = BAD_VALUE;
2638 goto Exit;
2639 }
2640
Eric Laurent84e9a102010-09-23 16:10:16 -07002641 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002642 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002643 lStatus = PERMISSION_DENIED;
2644 goto Exit;
2645 }
2646
Dima Zavinfce7a472011-04-19 22:30:36 -07002647 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002648 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002649 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002650 lStatus = PERMISSION_DENIED;
2651 goto Exit;
2652 }
2653
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 if (!EffectIsNullUuid(&pDesc->uuid)) {
2656 // if uuid is specified, request effect descriptor
2657 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2658 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002659 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 goto Exit;
2661 }
2662 } else {
2663 // if uuid is not specified, look for an available implementation
2664 // of the required type in effect factory
2665 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002666 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 lStatus = BAD_VALUE;
2668 goto Exit;
2669 }
2670 uint32_t numEffects = 0;
2671 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002672 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673 bool found = false;
2674
2675 lStatus = EffectQueryNumberEffects(&numEffects);
2676 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002677 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 goto Exit;
2679 }
2680 for (uint32_t i = 0; i < numEffects; i++) {
2681 lStatus = EffectQueryEffect(i, &desc);
2682 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002683 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 continue;
2685 }
2686 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2687 // If matching type found save effect descriptor. If the session is
2688 // 0 and the effect is not auxiliary, continue enumeration in case
2689 // an auxiliary version of this effect type is available
2690 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002691 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002692 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2694 break;
2695 }
2696 }
2697 }
2698 if (!found) {
2699 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002700 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 goto Exit;
2702 }
2703 // For same effect type, chose auxiliary version over insert version if
2704 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002705 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002707 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 }
2709 }
2710
2711 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002712 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2714 lStatus = INVALID_OPERATION;
2715 goto Exit;
2716 }
2717
Eric Laurent59255e42011-07-27 19:49:51 -07002718 // check recording permission for visualizer
2719 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002720 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002721 lStatus = PERMISSION_DENIED;
2722 goto Exit;
2723 }
2724
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002726 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002727 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002728 // if the output returned by getOutputForEffect() is removed before we lock the
2729 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2730 // and we will exit safely
2731 io = AudioSystem::getOutputForEffect(&desc);
2732 ALOGV("createEffect got output %d", io);
2733 }
2734
2735 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002736
2737 // If output is not specified try to find a matching audio session ID in one of the
2738 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002739 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2740 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002741 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002742 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002743 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2744 // output must be specified by AudioPolicyManager when using session
2745 // AUDIO_SESSION_OUTPUT_STAGE
2746 lStatus = BAD_VALUE;
2747 goto Exit;
2748 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002749 // look for the thread where the specified audio session is present
2750 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2751 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2752 io = mPlaybackThreads.keyAt(i);
2753 break;
2754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002756 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002757 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2758 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2759 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002760 break;
2761 }
2762 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002763 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002764 // If no output thread contains the requested session ID, default to
2765 // first output. The effect chain will be moved to the correct output
2766 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002767 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002768 io = mPlaybackThreads.keyAt(0);
2769 }
Steve Block3856b092011-10-20 11:56:00 +01002770 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002771 }
2772 ThreadBase *thread = checkRecordThread_l(io);
2773 if (thread == NULL) {
2774 thread = checkPlaybackThread_l(io);
2775 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002776 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002777 lStatus = BAD_VALUE;
2778 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002779 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002780 } else {
2781 // Check if one effect chain was awaiting for an effect to be created on this
2782 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002783 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002784 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002785 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002786 thread->addEffectChain_l(chain);
2787 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002789
Eric Laurent021cf962014-05-13 10:18:14 -07002790 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002792 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002793 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2794 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 if (handle != 0 && id != NULL) {
2796 *id = handle->id();
2797 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002798 if (handle == 0) {
2799 // remove local strong reference to Client with mClientLock held
2800 Mutex::Autolock _cl(mClientLock);
2801 client.clear();
2802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 }
2804
2805Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002806 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 return handle;
2808}
2809
Glenn Kastend848eb42016-03-08 13:42:11 -08002810status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002811 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002812{
Steve Block3856b092011-10-20 11:56:00 +01002813 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002814 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002815 Mutex::Autolock _l(mLock);
2816 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002817 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002818 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819 }
Eric Laurentde070132010-07-13 04:45:46 -07002820 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2821 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002822 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002823 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 }
Eric Laurentde070132010-07-13 04:45:46 -07002825 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2826 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002827 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002828 return BAD_VALUE;
2829 }
2830
2831 Mutex::Autolock _dl(dstThread->mLock);
2832 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002833 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834}
2835
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002836// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002837status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002838 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002839 AudioFlinger::PlaybackThread *dstThread,
2840 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002841{
Steve Block3856b092011-10-20 11:56:00 +01002842 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002843 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002844
Eric Laurent59255e42011-07-27 19:49:51 -07002845 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002846 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002847 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002848 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002849 return INVALID_OPERATION;
2850 }
2851
Eric Laurent4c415062016-06-17 16:14:16 -07002852 // Check whether the destination thread and all effects in the chain are compatible
2853 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002854 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002855 " destination thread %p is not compatible with effects in the chain",
2856 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002857 return INVALID_OPERATION;
2858 }
2859
Eric Laurent39e94f82010-07-28 01:32:47 -07002860 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002861 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002862 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002863 // removed.
2864 srcThread->removeEffectChain_l(chain);
2865
2866 // transfer all effects one by one so that new effect chain is created on new thread with
2867 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002868 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002869 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002870 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002871 Vector< sp<EffectModule> > removed;
2872 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002873 while (effect != 0) {
2874 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002875 removed.add(effect);
2876 status = dstThread->addEffect_l(effect);
2877 if (status != NO_ERROR) {
2878 break;
2879 }
Eric Laurentec35a142011-10-05 17:42:25 -07002880 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2881 if (effect->state() == EffectModule::ACTIVE ||
2882 effect->state() == EffectModule::STOPPING) {
2883 effect->start();
2884 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002885 // if the move request is not received from audio policy manager, the effect must be
2886 // re-registered with the new strategy and output
2887 if (dstChain == 0) {
2888 dstChain = effect->chain().promote();
2889 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002890 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002891 status = NO_INIT;
2892 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002893 }
2894 strategy = dstChain->strategy();
2895 }
2896 if (reRegister) {
2897 AudioSystem::unregisterEffect(effect->id());
2898 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002899 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002900 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002901 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002902 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002903 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002904 }
Eric Laurentde070132010-07-13 04:45:46 -07002905 effect = chain->getEffectFromId_l(0);
2906 }
2907
Eric Laurent5baf2af2013-09-12 17:37:00 -07002908 if (status != NO_ERROR) {
2909 for (size_t i = 0; i < removed.size(); i++) {
2910 srcThread->addEffect_l(removed[i]);
2911 if (dstChain != 0 && reRegister) {
2912 AudioSystem::unregisterEffect(removed[i]->id());
2913 AudioSystem::registerEffect(&removed[i]->desc(),
2914 srcThread->id(),
2915 strategy,
2916 sessionId,
2917 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002918 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002919 }
2920 }
2921 }
2922
2923 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924}
2925
Eric Laurent5baf2af2013-09-12 17:37:00 -07002926bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002927{
2928 if (mGlobalEffectEnableTime != 0 &&
2929 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2930 return true;
2931 }
2932
2933 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2934 sp<EffectChain> ec =
2935 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002936 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002937 return true;
2938 }
2939 }
2940 return false;
2941}
2942
Eric Laurent5baf2af2013-09-12 17:37:00 -07002943void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002944{
2945 Mutex::Autolock _l(mLock);
2946
2947 mGlobalEffectEnableTime = systemTime();
2948
2949 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2950 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2951 if (t->mType == ThreadBase::OFFLOAD) {
2952 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2953 }
2954 }
2955
2956}
2957
Eric Laurentaaa44472014-09-12 17:41:50 -07002958status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2959{
Glenn Kastend848eb42016-03-08 13:42:11 -08002960 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002961 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002962 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002963 if (index >= 0) {
2964 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2965 return ALREADY_EXISTS;
2966 }
2967 mOrphanEffectChains.add(session, chain);
2968 return NO_ERROR;
2969}
2970
2971sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2972{
2973 sp<EffectChain> chain;
2974 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002975 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002976 if (index >= 0) {
2977 chain = mOrphanEffectChains.valueAt(index);
2978 mOrphanEffectChains.removeItemsAt(index);
2979 }
2980 return chain;
2981}
2982
2983bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2984{
2985 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002986 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002987 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002988 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002989 if (index >= 0) {
2990 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2991 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002992 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002993 mOrphanEffectChains.removeItemsAt(index);
2994 }
2995 return true;
2996 }
2997 return false;
2998}
2999
3000
Glenn Kastenda6ef132013-01-10 12:31:01 -08003001struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003002#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3003 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003004};
3005
3006int comparEntry(const void *p1, const void *p2)
3007{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003008 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003009}
3010
Glenn Kasten46909e72013-02-26 09:20:22 -08003011#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003012void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013{
Eric Laurent81784c32012-11-19 14:55:58 -08003014 NBAIO_Source *teeSource = source.get();
3015 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003016 // .wav rotation
3017 // There is a benign race condition if 2 threads call this simultaneously.
3018 // They would both traverse the directory, but the result would simply be
3019 // failures at unlink() which are ignored. It's also unlikely since
3020 // normally dumpsys is only done by bugreport or from the command line.
3021 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003022 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003023 size_t teePathLen = strlen(teePath);
3024 DIR *dir = opendir(teePath);
3025 teePath[teePathLen++] = '/';
3026 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003027#define TEE_MAX_SORT 20 // number of entries to sort
3028#define TEE_MAX_KEEP 10 // number of entries to keep
3029 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003030 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003031 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003032 struct dirent de;
3033 struct dirent *result = NULL;
3034 int rc = readdir_r(dir, &de, &result);
3035 if (rc != 0) {
3036 ALOGW("readdir_r failed %d", rc);
3037 break;
3038 }
3039 if (result == NULL) {
3040 break;
3041 }
3042 if (result != &de) {
3043 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3044 break;
3045 }
3046 // ignore non .wav file entries
3047 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003048 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003049 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3050 continue;
3051 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003052 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003053 }
3054 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003055 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003056 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003057 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3058 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003059 (void) unlink(teePath);
3060 }
3061 }
3062 } else {
3063 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003064 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003065 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003066 }
3067 }
Eric Laurent81784c32012-11-19 14:55:58 -08003068 char teeTime[16];
3069 struct timeval tv;
3070 gettimeofday(&tv, NULL);
3071 struct tm tm;
3072 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003073 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3074 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3075 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3076 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003077 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003078 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003079 char wavHeader[44];
3080 memcpy(wavHeader,
3081 "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",
3082 sizeof(wavHeader));
3083 NBAIO_Format format = teeSource->format();
3084 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003085 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003086 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003087 wavHeader[22] = channelCount; // number of channels
3088 wavHeader[24] = sampleRate; // sample rate
3089 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003090 wavHeader[32] = frameSize; // block alignment
3091 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003092 write(teeFd, wavHeader, sizeof(wavHeader));
3093 size_t total = 0;
3094 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003095#define TEE_SINK_READ 1024 // frames per I/O operation
3096 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003097 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003098 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003099 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003100 bool wasFirstRead = firstRead;
3101 firstRead = false;
3102 if (actual <= 0) {
3103 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3104 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003105 }
Eric Laurent81784c32012-11-19 14:55:58 -08003106 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003107 }
Eric Laurent81784c32012-11-19 14:55:58 -08003108 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003109 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003110 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003111 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003112 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003113 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003114 uint32_t temp = 44 + total * frameSize - 8;
3115 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003116 write(teeFd, &temp, sizeof(temp));
3117 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003118 temp = total * frameSize;
3119 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003120 write(teeFd, &temp, sizeof(temp));
3121 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003122 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003123 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003124 }
Eric Laurent59255e42011-07-27 19:49:51 -07003125 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003126 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003127 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003128 }
Eric Laurent59255e42011-07-27 19:49:51 -07003129 }
3130 }
3131}
Glenn Kasten46909e72013-02-26 09:20:22 -08003132#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003133
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134// ----------------------------------------------------------------------------
3135
3136status_t AudioFlinger::onTransact(
3137 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3138{
3139 return BnAudioFlinger::onTransact(code, data, reply, flags);
3140}
3141
Glenn Kasten63238ef2015-03-02 15:50:29 -08003142} // namespace android