blob: 9ec97d1a7551c59db182560581aafdb6398a1fcc [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070034#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070047#include "EffectsFactoryHalInterface.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080048#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Andy Hung6770c6f2015-04-07 13:43:36 -070050#include <media/AudioResamplerPublic.h>
51
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";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070088static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten58912562012-04-03 10:45:00 -070090
John Grossman4ff14ba2012-02-08 16:37:41 -080091nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080092
Eric Laurent81784c32012-11-19 14:55:58 -080093uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070094
Glenn Kasten46909e72013-02-26 09:20:22 -080095#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080096bool AudioFlinger::mTeeSinkInputEnabled = false;
97bool AudioFlinger::mTeeSinkOutputEnabled = false;
98bool AudioFlinger::mTeeSinkTrackEnabled = false;
99
100size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
101size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
102size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104
Eric Laurent813e2a72013-08-31 12:59:48 -0700105// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
106// we define a minimum time during which a global effect is considered enabled.
107static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109// ----------------------------------------------------------------------------
110
Marco Nelissenb2208842014-02-07 14:00:50 -0800111const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800112 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530113 case AUDIO_FORMAT_PCM:
114 switch (format) {
115 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
116 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
117 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
118 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
119 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
120 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
121 default:
122 break;
123 }
124 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800125 case AUDIO_FORMAT_MP3: return "mp3";
126 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
127 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
128 case AUDIO_FORMAT_AAC: return "aac";
129 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
130 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
131 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530132 case AUDIO_FORMAT_OPUS: return "opus";
133 case AUDIO_FORMAT_AC3: return "ac-3";
134 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800135 case AUDIO_FORMAT_IEC61937: return "iec61937";
Eric Laurente30f2092016-07-07 18:56:57 -0700136 case AUDIO_FORMAT_DTS: return "dts";
137 case AUDIO_FORMAT_DTS_HD: return "dts-hd";
138 case AUDIO_FORMAT_DOLBY_TRUEHD: return "dolby-truehd";
Marco Nelissenb2208842014-02-07 14:00:50 -0800139 default:
140 break;
141 }
142 return "unknown";
143}
144
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700145static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700146{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700147 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700148 int rc;
149
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700150 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
151 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
152 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
153 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700154 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700155 }
156 rc = audio_hw_device_open(mod, dev);
157 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
158 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
159 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700160 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700161 }
Eric Laurent5806b352014-05-22 12:23:26 -0700162 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700163 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
164 rc = BAD_VALUE;
165 goto out;
166 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700167 return 0;
168
169out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 *dev = NULL;
171 return rc;
172}
173
Mathias Agopian65ab4712010-07-14 17:59:35 -0700174// ----------------------------------------------------------------------------
175
176AudioFlinger::AudioFlinger()
177 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800179 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700180 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800181 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800182 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700183 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800184 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700185 mBtNrecIsOff(false),
186 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700187 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700188 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700189 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700190{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700191 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
192 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
193 // zero ID has a special meaning, so unavailable
194 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
195 }
196
Glenn Kasten949a9262013-04-16 12:35:20 -0700197 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800198 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800199 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800200 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
201 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800202 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700203
Wei Jia3f273d12015-11-24 09:06:49 -0800204 // reset battery stats.
205 // if the audio service has crashed, battery stats could be left
206 // in bad state, reset the state upon service start.
207 BatteryNotifier::getInstance().noteResetAudio();
208
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700209 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
210
Glenn Kasten46909e72013-02-26 09:20:22 -0800211#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800212 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800213 (void) property_get("ro.debuggable", value, "0");
214 int debuggable = atoi(value);
215 int teeEnabled = 0;
216 if (debuggable) {
217 (void) property_get("af.tee", value, "0");
218 teeEnabled = atoi(value);
219 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800220 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700221 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800222 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700223 }
224 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800225 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700226 }
227 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800228 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700229 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800230#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700231}
232
233void AudioFlinger::onFirstRef()
234{
Eric Laurent93575202011-01-18 18:39:02 -0800235 Mutex::Autolock _l(mLock);
236
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800238 char val_str[PROPERTY_VALUE_MAX] = { 0 };
239 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
240 uint32_t int_val;
241 if (1 == sscanf(val_str, "%u", &int_val)) {
242 mStandbyTimeInNsecs = milliseconds(int_val);
243 ALOGI("Using %u mSec as standby time.", int_val);
244 } else {
245 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
246 ALOGI("Using default %u mSec as standby time.",
247 (uint32_t)(mStandbyTimeInNsecs / 1000000));
248 }
249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250
Eric Laurent1c333e22014-05-20 10:48:17 -0700251 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700252
Eric Laurenta4c5a552012-03-29 10:12:40 -0700253 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254}
255
256AudioFlinger::~AudioFlinger()
257{
258 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700259 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700260 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261 }
262 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700263 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700264 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700266
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800267 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
268 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
270 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700271 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700272
273 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800274 if (mLogMemoryDealer != 0) {
275 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
276 if (binder != 0) {
277 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
278 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
279 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
280 mUnregisteredWriters.pop();
281 mediaLogService->unregisterWriter(iMemory);
282 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700283 }
284 }
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
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700425 if (mEffectsFactoryHal.get() != NULL) {
426 mEffectsFactoryHal->dumpEffects(fd);
427 } else {
428 String8 result(kNoEffectsFactory);
429 write(fd, result.string(), result.size());
430 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700431
Mathias Agopian65ab4712010-07-14 17:59:35 -0700432 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700433 if (clientLocked) {
434 mClientLock.unlock();
435 }
436
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 dumpInternals(fd, args);
438
439 // dump playback threads
440 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
441 mPlaybackThreads.valueAt(i)->dump(fd, args);
442 }
443
444 // dump record threads
445 for (size_t i = 0; i < mRecordThreads.size(); i++) {
446 mRecordThreads.valueAt(i)->dump(fd, args);
447 }
448
Eric Laurentaaa44472014-09-12 17:41:50 -0700449 // dump orphan effect chains
450 if (mOrphanEffectChains.size() != 0) {
451 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
452 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
453 mOrphanEffectChains.valueAt(i)->dump(fd, args);
454 }
455 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700456 // dump all hardware devs
457 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700458 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700459 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700461
Glenn Kasten46909e72013-02-26 09:20:22 -0800462#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700463 // dump the serially shared record tee sink
464 if (mRecordTeeSource != 0) {
465 dumpTee(fd, mRecordTeeSource);
466 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800467#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700468
Glenn Kastend65d73c2012-06-22 17:21:07 -0700469 if (locked) {
470 mLock.unlock();
471 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800472
473 // append a copy of media.log here by forwarding fd to it, but don't attempt
474 // to lookup the service if it's not running, as it will block for a second
475 if (mLogMemoryDealer != 0) {
476 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
477 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700478 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800479 Vector<String16> args;
480 binder->dump(fd, args);
481 }
482 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700483
484 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700485 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700486 bool unreachableMemory = false;
487 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700488 if (arg == String16("-m")) {
489 dumpMem = true;
490 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700491 unreachableMemory = true;
492 }
493 }
494
Andy Hung07b745e2016-05-23 16:21:07 -0700495 if (dumpMem) {
496 dprintf(fd, "\nDumping memory:\n");
497 std::string s = dumpMemoryAddresses(100 /* limit */);
498 write(fd, s.c_str(), s.size());
499 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700500 if (unreachableMemory) {
501 dprintf(fd, "\nDumping unreachable memory:\n");
502 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700503 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700504 write(fd, s.c_str(), s.size());
505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506 }
507 return NO_ERROR;
508}
509
Eric Laurent021cf962014-05-13 10:18:14 -0700510sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800511{
Eric Laurent021cf962014-05-13 10:18:14 -0700512 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800513 // If pid is already in the mClients wp<> map, then use that entry
514 // (for which promote() is always != 0), otherwise create a new entry and Client.
515 sp<Client> client = mClients.valueFor(pid).promote();
516 if (client == 0) {
517 client = new Client(this, pid);
518 mClients.add(pid, client);
519 }
520
521 return client;
522}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700523
Glenn Kasten9e58b552013-01-18 15:09:48 -0800524sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
525{
Glenn Kasten481fb672013-09-30 14:39:28 -0700526 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800527 if (mLogMemoryDealer == 0) {
528 return new NBLog::Writer();
529 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800530 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700531 // Similarly if we can't contact the media.log service, also return a dummy writer
532 if (binder == 0) {
533 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800534 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700535 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
536 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
537 // If allocation fails, consult the vector of previously unregistered writers
538 // and garbage-collect one or more them until an allocation succeeds
539 if (shared == 0) {
540 Mutex::Autolock _l(mUnregisteredWritersLock);
541 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
542 {
543 // Pick the oldest stale writer to garbage-collect
544 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
545 mUnregisteredWriters.removeAt(0);
546 mediaLogService->unregisterWriter(iMemory);
547 // Now the media.log remote reference to IMemory is gone. When our last local
548 // reference to IMemory also drops to zero at end of this block,
549 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
550 }
551 // Re-attempt the allocation
552 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
553 if (shared != 0) {
554 goto success;
555 }
556 }
557 // Even after garbage-collecting all old writers, there is still not enough memory,
558 // so return a dummy writer
559 return new NBLog::Writer();
560 }
561success:
562 mediaLogService->registerWriter(shared, size, name);
563 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800564}
565
566void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
567{
Glenn Kasten685ef092013-02-04 08:15:34 -0800568 if (writer == 0) {
569 return;
570 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800571 sp<IMemory> iMemory(writer->getIMemory());
572 if (iMemory == 0) {
573 return;
574 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700575 // Rather than removing the writer immediately, append it to a queue of old writers to
576 // be garbage-collected later. This allows us to continue to view old logs for a while.
577 Mutex::Autolock _l(mUnregisteredWritersLock);
578 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800579}
580
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581// IAudioFlinger interface
582
583
584sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800585 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800587 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700588 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800589 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700590 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800592 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700593 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800594 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800595 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800596 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 status_t *status)
598{
599 sp<PlaybackThread::Track> track;
600 sp<TrackHandle> trackHandle;
601 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800603 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700605 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
606 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
607 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
608 ALOGW_IF(pid != -1 && pid != callingPid,
609 "%s uid %d pid %d tried to pass itself off as pid %d",
610 __func__, callingUid, callingPid, pid);
611 pid = callingPid;
612 }
613
Glenn Kasten263709e2012-01-06 08:40:01 -0800614 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
615 // but if someone uses binder directly they could bypass that and cause us to crash
616 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000617 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618 lStatus = BAD_VALUE;
619 goto Exit;
620 }
621
Glenn Kasten53b5d092014-02-05 10:00:23 -0800622 // further sample rate checks are performed by createTrack_l() depending on the thread type
623 if (sampleRate == 0) {
624 ALOGE("createTrack() invalid sample rate %u", sampleRate);
625 lStatus = BAD_VALUE;
626 goto Exit;
627 }
628
629 // further channel mask checks are performed by createTrack_l() depending on the thread type
630 if (!audio_is_output_channel(channelMask)) {
631 ALOGE("createTrack() invalid channel mask %#x", channelMask);
632 lStatus = BAD_VALUE;
633 goto Exit;
634 }
635
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700636 // further format checks are performed by createTrack_l() depending on the thread type
637 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800638 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700639 lStatus = BAD_VALUE;
640 goto Exit;
641 }
642
Glenn Kasten663c2242013-09-24 11:52:37 -0700643 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
644 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
645 lStatus = BAD_VALUE;
646 goto Exit;
647 }
648
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 {
650 Mutex::Autolock _l(mLock);
651 PlaybackThread *thread = checkPlaybackThread_l(output);
652 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800653 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 lStatus = BAD_VALUE;
655 goto Exit;
656 }
657
Eric Laurent021cf962014-05-13 10:18:14 -0700658 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659
Glenn Kastene848bd92014-03-13 15:00:32 -0700660 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700661 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800662 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
663 ALOGE("createTrack() invalid session ID %d", *sessionId);
664 lStatus = BAD_VALUE;
665 goto Exit;
666 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700667 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700668 // check if an effect chain with the same session ID is present on another
669 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700670 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700671 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
672 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700673 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700674 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700675 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700676 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700677 }
Eric Laurentde070132010-07-13 04:45:46 -0700678 }
679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700681 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800682 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683 if (sessionId != NULL) {
684 *sessionId = lSessionId;
685 }
686 }
Steve Block3856b092011-10-20 11:56:00 +0100687 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688
689 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800690 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800691 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700692 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700693
694 // move effect chain to this output thread if an effect on same session was waiting
695 // for a track to be created
696 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700697 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700698 Mutex::Autolock _dl(thread->mLock);
699 Mutex::Autolock _sl(effectThread->mLock);
700 moveEffectChain_l(lSessionId, effectThread, thread, true);
701 }
Eric Laurenta011e352012-03-29 15:51:43 -0700702
703 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700704 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700705 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
706 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700707 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700708 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700709 } else {
710 mPendingSyncEvents[i]->cancel();
711 }
Eric Laurenta011e352012-03-29 15:51:43 -0700712 mPendingSyncEvents.removeAt(i);
713 i--;
714 }
715 }
716 }
Glenn Kastene198c362013-08-13 09:13:36 -0700717
Glenn Kastend848eb42016-03-08 13:42:11 -0800718 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 }
Glenn Kastene198c362013-08-13 09:13:36 -0700720
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700721 if (lStatus != NO_ERROR) {
722 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700723 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700724 // Don't hold mClientLock when releasing the reference on the track as the
725 // destructor will acquire it.
726 {
727 Mutex::Autolock _cl(mClientLock);
728 client.clear();
729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700731 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 }
733
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700734 // return handle to client
735 trackHandle = new TrackHandle(track);
736
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700738 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739 return trackHandle;
740}
741
Glenn Kasten2c073da2016-02-26 09:14:08 -0800742uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743{
744 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800745 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800747 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 return 0;
749 }
750 return thread->sampleRate();
751}
752
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800753audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754{
755 Mutex::Autolock _l(mLock);
756 PlaybackThread *thread = checkPlaybackThread_l(output);
757 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000758 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800759 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 }
761 return thread->format();
762}
763
Glenn Kasten2c073da2016-02-26 09:14:08 -0800764size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765{
766 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800767 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800769 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return 0;
771 }
Glenn Kasten58912562012-04-03 10:45:00 -0700772 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
773 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774 return thread->frameCount();
775}
776
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700777size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
778{
779 Mutex::Autolock _l(mLock);
780 ThreadBase *thread = checkThread_l(ioHandle);
781 if (thread == NULL) {
782 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
783 return 0;
784 }
785 return thread->frameCountHAL();
786}
787
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800788uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
790 Mutex::Autolock _l(mLock);
791 PlaybackThread *thread = checkPlaybackThread_l(output);
792 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800793 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 return 0;
795 }
796 return thread->latency();
797}
798
799status_t AudioFlinger::setMasterVolume(float value)
800{
Eric Laurenta1884f92011-08-23 08:25:03 -0700801 status_t ret = initCheck();
802 if (ret != NO_ERROR) {
803 return ret;
804 }
805
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 // check calling permissions
807 if (!settingsAllowed()) {
808 return PERMISSION_DENIED;
809 }
810
Eric Laurenta4c5a552012-03-29 10:12:40 -0700811 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700812 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700813
John Grossmanee578c02012-07-23 17:05:46 -0700814 // Set master volume in the HALs which support it.
815 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
816 AutoMutex lock(mHardwareLock);
817 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800818
John Grossmanee578c02012-07-23 17:05:46 -0700819 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
820 if (dev->canSetMasterVolume()) {
821 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800822 }
John Grossmanee578c02012-07-23 17:05:46 -0700823 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825
John Grossmanee578c02012-07-23 17:05:46 -0700826 // Now set the master volume in each playback thread. Playback threads
827 // assigned to HALs which do not have master volume support will apply
828 // master volume during the mix operation. Threads with HALs which do
829 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700830 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
831 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
832 continue;
833 }
John Grossmanee578c02012-07-23 17:05:46 -0700834 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836
837 return NO_ERROR;
838}
839
Glenn Kastenf78aee72012-01-04 11:00:47 -0800840status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841{
Eric Laurenta1884f92011-08-23 08:25:03 -0700842 status_t ret = initCheck();
843 if (ret != NO_ERROR) {
844 return ret;
845 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846
847 // check calling permissions
848 if (!settingsAllowed()) {
849 return PERMISSION_DENIED;
850 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800851 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000852 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 return BAD_VALUE;
854 }
855
856 { // scope for the lock
857 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700858 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700860 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861 mHardwareStatus = AUDIO_HW_IDLE;
862 }
863
864 if (NO_ERROR == ret) {
865 Mutex::Autolock _l(mLock);
866 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800867 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700868 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869 }
870
871 return ret;
872}
873
874status_t AudioFlinger::setMicMute(bool state)
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700888 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
889 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
890 status_t result = dev->set_mic_mute(dev, state);
891 if (result != NO_ERROR) {
892 ret = result;
893 }
894 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 mHardwareStatus = AUDIO_HW_IDLE;
896 return ret;
897}
898
899bool AudioFlinger::getMicMute() const
900{
Eric Laurenta1884f92011-08-23 08:25:03 -0700901 status_t ret = initCheck();
902 if (ret != NO_ERROR) {
903 return false;
904 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800905 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700906 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800907 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800909 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
910 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
911 status_t result = dev->get_mic_mute(dev, &state);
912 if (result == NO_ERROR) {
913 mute = mute && state;
914 }
915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800917
918 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919}
920
921status_t AudioFlinger::setMasterMute(bool muted)
922{
John Grossmand8f178d2012-07-20 14:51:35 -0700923 status_t ret = initCheck();
924 if (ret != NO_ERROR) {
925 return ret;
926 }
927
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 // check calling permissions
929 if (!settingsAllowed()) {
930 return PERMISSION_DENIED;
931 }
932
John Grossmanee578c02012-07-23 17:05:46 -0700933 Mutex::Autolock _l(mLock);
934 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700935
John Grossmanee578c02012-07-23 17:05:46 -0700936 // Set master mute in the HALs which support it.
937 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
938 AutoMutex lock(mHardwareLock);
939 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700940
John Grossmanee578c02012-07-23 17:05:46 -0700941 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
942 if (dev->canSetMasterMute()) {
943 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700944 }
John Grossmanee578c02012-07-23 17:05:46 -0700945 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700946 }
947
John Grossmanee578c02012-07-23 17:05:46 -0700948 // Now set the master mute in each playback thread. Playback threads
949 // assigned to HALs which do not have master mute support will apply master
950 // mute during the mix operation. Threads with HALs which do support master
951 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700952 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
953 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
954 continue;
955 }
John Grossmanee578c02012-07-23 17:05:46 -0700956 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958
959 return NO_ERROR;
960}
961
962float AudioFlinger::masterVolume() const
963{
Glenn Kasten98067102011-12-13 11:47:54 -0800964 Mutex::Autolock _l(mLock);
965 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966}
967
968bool AudioFlinger::masterMute() const
969{
Glenn Kasten98067102011-12-13 11:47:54 -0800970 Mutex::Autolock _l(mLock);
971 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972}
973
John Grossman4ff14ba2012-02-08 16:37:41 -0800974float AudioFlinger::masterVolume_l() const
975{
John Grossman4ff14ba2012-02-08 16:37:41 -0800976 return mMasterVolume;
977}
978
John Grossmand8f178d2012-07-20 14:51:35 -0700979bool AudioFlinger::masterMute_l() const
980{
John Grossmanee578c02012-07-23 17:05:46 -0700981 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700982}
983
Eric Laurent223fd5c2014-11-11 13:43:36 -0800984status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
985{
986 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
987 ALOGW("setStreamVolume() invalid stream %d", stream);
988 return BAD_VALUE;
989 }
990 pid_t caller = IPCThreadState::self()->getCallingPid();
991 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
992 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
993 return PERMISSION_DENIED;
994 }
995
996 return NO_ERROR;
997}
998
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800999status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1000 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001{
1002 // check calling permissions
1003 if (!settingsAllowed()) {
1004 return PERMISSION_DENIED;
1005 }
1006
Eric Laurent223fd5c2014-11-11 13:43:36 -08001007 status_t status = checkStreamType(stream);
1008 if (status != NO_ERROR) {
1009 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001011 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012
1013 AutoMutex lock(mLock);
1014 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -07001015 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 thread = checkPlaybackThread_l(output);
1017 if (thread == NULL) {
1018 return BAD_VALUE;
1019 }
1020 }
1021
1022 mStreamTypes[stream].volume = value;
1023
1024 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001025 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001026 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 }
1028 } else {
1029 thread->setStreamVolume(stream, value);
1030 }
1031
1032 return NO_ERROR;
1033}
1034
Glenn Kastenfff6d712012-01-12 16:38:12 -08001035status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036{
1037 // check calling permissions
1038 if (!settingsAllowed()) {
1039 return PERMISSION_DENIED;
1040 }
1041
Eric Laurent223fd5c2014-11-11 13:43:36 -08001042 status_t status = checkStreamType(stream);
1043 if (status != NO_ERROR) {
1044 return status;
1045 }
1046 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1047
1048 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001049 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050 return BAD_VALUE;
1051 }
1052
Eric Laurent93575202011-01-18 18:39:02 -08001053 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001055 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001056 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057
1058 return NO_ERROR;
1059}
1060
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001061float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001063 status_t status = checkStreamType(stream);
1064 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 return 0.0f;
1066 }
1067
1068 AutoMutex lock(mLock);
1069 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001070 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 PlaybackThread *thread = checkPlaybackThread_l(output);
1072 if (thread == NULL) {
1073 return 0.0f;
1074 }
1075 volume = thread->streamVolume(stream);
1076 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001077 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 }
1079
1080 return volume;
1081}
1082
Glenn Kastenfff6d712012-01-12 16:38:12 -08001083bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001085 status_t status = checkStreamType(stream);
1086 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 return true;
1088 }
1089
Glenn Kasten6637baa2012-01-09 09:40:36 -08001090 AutoMutex lock(mLock);
1091 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092}
1093
Eric Laurent054d9d32015-04-24 08:48:48 -07001094
1095void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1096{
1097 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1098 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1099 }
1100}
1101
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001102status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001104 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1105 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001106
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 // check calling permissions
1108 if (!settingsAllowed()) {
1109 return PERMISSION_DENIED;
1110 }
1111
Glenn Kasten142f5192014-03-25 17:44:59 -07001112 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1113 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001114 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001115 // result will remain NO_INIT if no audio device is present
1116 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001117 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001118 AutoMutex lock(mHardwareLock);
1119 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1120 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1121 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1122 status_t result = dev->set_parameters(dev, keyValuePairs.string());
Eric Laurentd21bcd22016-09-08 18:25:54 -07001123 // return success if at least one audio device accepts the parameters as not all
1124 // HALs are requested to support all parameters. If no audio device supports the
1125 // requested parameters, the last error is reported.
1126 if (final_result != NO_ERROR) {
1127 final_result = result;
1128 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001129 }
1130 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001131 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001132 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1133 AudioParameter param = AudioParameter(keyValuePairs);
1134 String8 value;
1135 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001136 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1137 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001138 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1139 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001140 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001141 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1142 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001143 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001144 // suspend effects associated with those session IDs
1145 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001146 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001147 thread->setEffectSuspended(FX_IID_AEC,
1148 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001149 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001150 thread->setEffectSuspended(FX_IID_NS,
1151 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001152 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001153 }
1154 }
Eric Laurentbee53372011-08-29 12:42:48 -07001155 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001156 }
1157 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001158 String8 screenState;
1159 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1160 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001161 if (isOff != (AudioFlinger::mScreenState & 1)) {
1162 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001163 }
1164 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001165 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 }
1167
1168 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1169 // and the thread is exited once the lock is released
1170 sp<ThreadBase> thread;
1171 {
1172 Mutex::Autolock _l(mLock);
1173 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001174 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001176 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001177 // indicate output device change to all input threads for pre processing
1178 AudioParameter param = AudioParameter(keyValuePairs);
1179 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001180 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1181 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001182 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 }
1185 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001186 if (thread != 0) {
1187 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 }
1189 return BAD_VALUE;
1190}
1191
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001192String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001194 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1195 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196
Eric Laurenta4c5a552012-03-29 10:12:40 -07001197 Mutex::Autolock _l(mLock);
1198
Glenn Kasten142f5192014-03-25 17:44:59 -07001199 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001200 String8 out_s8;
1201
Dima Zavin799a70e2011-04-18 16:57:27 -07001202 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001203 char *s;
1204 {
1205 AutoMutex lock(mHardwareLock);
1206 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001207 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001208 s = dev->get_parameters(dev, keys.string());
1209 mHardwareStatus = AUDIO_HW_IDLE;
1210 }
John Grossmanef7740b2012-02-09 11:28:36 -08001211 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001212 free(s);
1213 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001214 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 }
1216
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1218 if (playbackThread != NULL) {
1219 return playbackThread->getParameters(keys);
1220 }
1221 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1222 if (recordThread != NULL) {
1223 return recordThread->getParameters(keys);
1224 }
1225 return String8("");
1226}
1227
Glenn Kastendd8104c2012-07-02 12:42:44 -07001228size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1229 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230{
Eric Laurenta1884f92011-08-23 08:25:03 -07001231 status_t ret = initCheck();
1232 if (ret != NO_ERROR) {
1233 return 0;
1234 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001235 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001236 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001237 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001238 return 0;
1239 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001240
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001241 AutoMutex lock(mHardwareLock);
1242 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001243 audio_config_t config, proposed;
1244 memset(&proposed, 0, sizeof(proposed));
1245 proposed.sample_rate = sampleRate;
1246 proposed.channel_mask = channelMask;
1247 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001248
John Grossmanee578c02012-07-23 17:05:46 -07001249 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001250 size_t frames;
1251 for (;;) {
1252 // Note: config is currently a const parameter for get_input_buffer_size()
1253 // but we use a copy from proposed in case config changes from the call.
1254 config = proposed;
1255 frames = dev->get_input_buffer_size(dev, &config);
1256 if (frames != 0) {
1257 break; // hal success, config is the result
1258 }
1259 // change one parameter of the configuration each iteration to a more "common" value
1260 // to see if the device will support it.
1261 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1262 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1263 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1264 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1265 } else {
1266 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1267 "format %#x, channelMask 0x%X",
1268 sampleRate, format, channelMask);
1269 break; // retries failed, break out of loop with frames == 0.
1270 }
1271 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001272 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001273 if (frames > 0 && config.sample_rate != sampleRate) {
1274 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1275 }
1276 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277}
1278
Glenn Kasten5f972c02014-01-13 09:59:31 -08001279uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 Mutex::Autolock _l(mLock);
1282
1283 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1284 if (recordThread != NULL) {
1285 return recordThread->getInputFramesLost();
1286 }
1287 return 0;
1288}
1289
1290status_t AudioFlinger::setVoiceVolume(float value)
1291{
Eric Laurenta1884f92011-08-23 08:25:03 -07001292 status_t ret = initCheck();
1293 if (ret != NO_ERROR) {
1294 return ret;
1295 }
1296
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 // check calling permissions
1298 if (!settingsAllowed()) {
1299 return PERMISSION_DENIED;
1300 }
1301
1302 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001303 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001304 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001305 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306 mHardwareStatus = AUDIO_HW_IDLE;
1307
1308 return ret;
1309}
1310
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001311status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001312 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314 Mutex::Autolock _l(mLock);
1315
1316 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1317 if (playbackThread != NULL) {
1318 return playbackThread->getRenderPosition(halFrames, dspFrames);
1319 }
1320
1321 return BAD_VALUE;
1322}
1323
1324void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1325{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001326 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001327 if (client == 0) {
1328 return;
1329 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001330 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001331 {
1332 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001333 if (mNotificationClients.indexOfKey(pid) < 0) {
1334 sp<NotificationClient> notificationClient = new NotificationClient(this,
1335 client,
1336 pid);
1337 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338
Eric Laurent021cf962014-05-13 10:18:14 -07001339 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340
Marco Nelissen06b46062014-11-14 07:58:25 -08001341 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001342 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001343 }
1344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001345
Eric Laurent021cf962014-05-13 10:18:14 -07001346 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001347 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001348 // the config change is always sent from playback or record threads to avoid deadlock
1349 // with AudioSystem::gLock
1350 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1351 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001354 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1355 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356 }
1357}
1358
1359void AudioFlinger::removeNotificationClient(pid_t pid)
1360{
1361 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001362 {
1363 Mutex::Autolock _cl(mClientLock);
1364 mNotificationClients.removeItem(pid);
1365 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001366
Steve Block3856b092011-10-20 11:56:00 +01001367 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001368 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001369 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001370 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001371 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001372 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001373 if (ref->mPid == pid) {
1374 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001375 mAudioSessionRefs.removeAt(i);
1376 delete ref;
1377 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001378 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001379 } else {
1380 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001381 }
1382 }
1383 if (removed) {
1384 purgeStaleEffects_l();
1385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386}
1387
Eric Laurent73e26b62015-04-27 16:55:58 -07001388void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001389 const sp<AudioIoDescriptor>& ioDesc,
1390 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391{
Eric Laurent021cf962014-05-13 10:18:14 -07001392 Mutex::Autolock _l(mClientLock);
1393 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001395 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1396 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398 }
1399}
1400
Eric Laurent021cf962014-05-13 10:18:14 -07001401// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402void AudioFlinger::removeClient_l(pid_t pid)
1403{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001404 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001405 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 mClients.removeItem(pid);
1407}
1408
Eric Laurent717e1282012-06-29 16:36:52 -07001409// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001410sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1411 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001412{
1413 sp<PlaybackThread> thread;
1414
1415 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1416 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1417 ALOG_ASSERT(thread == 0);
1418 thread = mPlaybackThreads.valueAt(i);
1419 }
1420 }
1421
1422 return thread;
1423}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426
1427// ----------------------------------------------------------------------------
1428
1429AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1430 : RefBase(),
1431 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001432 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301434 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1435 heapSize *= 1024;
1436 if (!heapSize) {
1437 heapSize = kClientSharedHeapSizeBytes;
1438 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1439 // invalidated tracks
1440 if (!audioFlinger->isLowRamDevice()) {
1441 heapSize *= kClientSharedHeapSizeMultiplier;
1442 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001443 }
1444 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445}
1446
Eric Laurent021cf962014-05-13 10:18:14 -07001447// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448AudioFlinger::Client::~Client()
1449{
1450 mAudioFlinger->removeClient_l(mPid);
1451}
1452
Glenn Kasten435dbe62012-01-30 10:15:48 -08001453sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454{
1455 return mMemoryDealer;
1456}
1457
1458// ----------------------------------------------------------------------------
1459
1460AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1461 const sp<IAudioFlingerClient>& client,
1462 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001463 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464{
1465}
1466
1467AudioFlinger::NotificationClient::~NotificationClient()
1468{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469}
1470
Glenn Kasten0f11b512014-01-31 16:18:54 -08001471void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472{
1473 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001474 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475}
1476
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477
1478// ----------------------------------------------------------------------------
1479
1480sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001481 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001483 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001484 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001485 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001486 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001487 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001488 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001489 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001490 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001491 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001492 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001493 sp<IMemory>& cblk,
1494 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495 status_t *status)
1496{
1497 sp<RecordThread::RecordTrack> recordTrack;
1498 sp<RecordHandle> recordHandle;
1499 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001501 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502
Glenn Kastend776ac62014-05-07 09:16:09 -07001503 cblk.clear();
1504 buffers.clear();
1505
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001506 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001507 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1508 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001509 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001510 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1511 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001512 updatePid = true;
1513 }
1514
1515 if (updatePid) {
1516 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1517 ALOGW_IF(pid != -1 && pid != callingPid,
1518 "%s uid %d pid %d tried to pass itself off as pid %d",
1519 __func__, callingUid, callingPid, pid);
1520 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001521 }
1522
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001524 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001525 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 lStatus = PERMISSION_DENIED;
1527 goto Exit;
1528 }
1529
Glenn Kasten53b5d092014-02-05 10:00:23 -08001530 // further sample rate checks are performed by createRecordTrack_l()
1531 if (sampleRate == 0) {
1532 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536
Andy Hung6770c6f2015-04-07 13:43:36 -07001537 // we don't yet support anything other than linear PCM
1538 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001539 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001540 lStatus = BAD_VALUE;
1541 goto Exit;
1542 }
1543
Glenn Kasten53b5d092014-02-05 10:00:23 -08001544 // further channel mask checks are performed by createRecordTrack_l()
1545 if (!audio_is_input_channel(channelMask)) {
1546 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1547 lStatus = BAD_VALUE;
1548 goto Exit;
1549 }
1550
Glenn Kasten05997e22014-03-13 15:08:33 -07001551 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001553 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001555 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 lStatus = BAD_VALUE;
1557 goto Exit;
1558 }
1559
Eric Laurent021cf962014-05-13 10:18:14 -07001560 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001562 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001563 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1564 lStatus = BAD_VALUE;
1565 goto Exit;
1566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 lSessionId = *sessionId;
1568 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001569 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001570 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 if (sessionId != NULL) {
1572 *sessionId = lSessionId;
1573 }
1574 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001575 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001576
Glenn Kasten1879fff2012-07-11 15:36:59 -07001577 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001578 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001579 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001580 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001581
1582 if (lStatus == NO_ERROR) {
1583 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1584 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001585 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001586 if (chain != 0) {
1587 Mutex::Autolock _l(thread->mLock);
1588 thread->addEffectChain_l(chain);
1589 }
1590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 }
Glenn Kastene198c362013-08-13 09:13:36 -07001592
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001593 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001594 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001595 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001596 // Don't hold mClientLock when releasing the reference on the track as the
1597 // destructor will acquire it.
1598 {
1599 Mutex::Autolock _cl(mClientLock);
1600 client.clear();
1601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 goto Exit;
1604 }
1605
Glenn Kastend776ac62014-05-07 09:16:09 -07001606 cblk = recordTrack->getCblk();
1607 buffers = recordTrack->getBuffers();
1608
Glenn Kasten2fc14732013-08-05 14:58:14 -07001609 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611
1612Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001613 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 return recordHandle;
1615}
1616
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001617
1618
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619// ----------------------------------------------------------------------------
1620
Eric Laurenta4c5a552012-03-29 10:12:40 -07001621audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1622{
Eric Laurent44622db2014-08-01 19:00:33 -07001623 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001624 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001625 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001626 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001627 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001628 }
1629 Mutex::Autolock _l(mLock);
1630 return loadHwModule_l(name);
1631}
1632
1633// loadHwModule_l() must be called with AudioFlinger::mLock held
1634audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1635{
1636 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1637 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1638 ALOGW("loadHwModule() module %s already loaded", name);
1639 return mAudioHwDevs.keyAt(i);
1640 }
1641 }
1642
Eric Laurenta4c5a552012-03-29 10:12:40 -07001643 audio_hw_device_t *dev;
1644
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001645 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001646 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001647 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001648 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001649 }
1650
1651 mHardwareStatus = AUDIO_HW_INIT;
1652 rc = dev->init_check(dev);
1653 mHardwareStatus = AUDIO_HW_IDLE;
1654 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001655 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001656 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001657 }
1658
John Grossmanee578c02012-07-23 17:05:46 -07001659 // Check and cache this HAL's level of support for master mute and master
1660 // volume. If this is the first HAL opened, and it supports the get
1661 // methods, use the initial values provided by the HAL as the current
1662 // master mute and volume settings.
1663
1664 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1665 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001666 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001667
1668 if (0 == mAudioHwDevs.size()) {
1669 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1670 if (NULL != dev->get_master_volume) {
1671 float mv;
1672 if (OK == dev->get_master_volume(dev, &mv)) {
1673 mMasterVolume = mv;
1674 }
1675 }
1676
1677 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1678 if (NULL != dev->get_master_mute) {
1679 bool mm;
1680 if (OK == dev->get_master_mute(dev, &mm)) {
1681 mMasterMute = mm;
1682 }
1683 }
1684 }
1685
Eric Laurenta4c5a552012-03-29 10:12:40 -07001686 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001687 if ((NULL != dev->set_master_volume) &&
1688 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1689 flags = static_cast<AudioHwDevice::Flags>(flags |
1690 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1691 }
1692
1693 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1694 if ((NULL != dev->set_master_mute) &&
1695 (OK == dev->set_master_mute(dev, mMasterMute))) {
1696 flags = static_cast<AudioHwDevice::Flags>(flags |
1697 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1698 }
1699
Eric Laurenta4c5a552012-03-29 10:12:40 -07001700 mHardwareStatus = AUDIO_HW_IDLE;
1701 }
1702
Glenn Kastena13cde92016-03-28 15:26:02 -07001703 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001704 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001705
1706 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001707 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001708
1709 return handle;
1710
1711}
1712
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001713// ----------------------------------------------------------------------------
1714
Glenn Kasten3b16c762012-11-14 08:44:39 -08001715uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001716{
1717 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001718 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001719 return thread != NULL ? thread->sampleRate() : 0;
1720}
1721
Glenn Kastene33054e2012-11-14 12:54:39 -08001722size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001723{
1724 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001725 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001726 return thread != NULL ? thread->frameCountHAL() : 0;
1727}
1728
1729// ----------------------------------------------------------------------------
1730
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001731status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1732{
1733 uid_t uid = IPCThreadState::self()->getCallingUid();
1734 if (uid != AID_SYSTEM) {
1735 return PERMISSION_DENIED;
1736 }
1737 Mutex::Autolock _l(mLock);
1738 if (mIsDeviceTypeKnown) {
1739 return INVALID_OPERATION;
1740 }
1741 mIsLowRamDevice = isLowRamDevice;
1742 mIsDeviceTypeKnown = true;
1743 return NO_ERROR;
1744}
1745
Eric Laurent93c3d412014-08-01 14:48:35 -07001746audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1747{
1748 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001749
1750 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1751 if (index >= 0) {
1752 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1753 mHwAvSyncIds.valueAt(index), sessionId);
1754 return mHwAvSyncIds.valueAt(index);
1755 }
1756
1757 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1758 if (dev == NULL) {
1759 return AUDIO_HW_SYNC_INVALID;
1760 }
1761 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1762 AudioParameter param = AudioParameter(String8(reply));
1763 free(reply);
1764
1765 int value;
1766 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1767 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1768 return AUDIO_HW_SYNC_INVALID;
1769 }
1770
1771 // allow only one session for a given HW A/V sync ID.
1772 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1773 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1774 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1775 value, mHwAvSyncIds.keyAt(i));
1776 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001777 break;
1778 }
1779 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001780
1781 mHwAvSyncIds.add(sessionId, value);
1782
1783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1784 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1785 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001786 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001787 AudioParameter param = AudioParameter();
1788 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1789 thread->setParameters(param.toString());
1790 break;
1791 }
1792 }
1793
1794 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1795 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001796}
1797
Eric Laurent72e3f392015-05-20 14:43:50 -07001798status_t AudioFlinger::systemReady()
1799{
1800 Mutex::Autolock _l(mLock);
1801 ALOGI("%s", __FUNCTION__);
1802 if (mSystemReady) {
1803 ALOGW("%s called twice", __FUNCTION__);
1804 return NO_ERROR;
1805 }
1806 mSystemReady = true;
1807 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1808 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1809 thread->systemReady();
1810 }
1811 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1812 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1813 thread->systemReady();
1814 }
1815 return NO_ERROR;
1816}
1817
Eric Laurentfa90e842014-10-17 18:12:31 -07001818// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1819void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1820{
1821 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1822 if (index >= 0) {
1823 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1824 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1825 AudioParameter param = AudioParameter();
1826 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1827 thread->setParameters(param.toString());
1828 }
1829}
1830
1831
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001832// ----------------------------------------------------------------------------
1833
Eric Laurent83b88082014-06-20 18:31:16 -07001834
1835sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001836 audio_io_handle_t *output,
1837 audio_config_t *config,
1838 audio_devices_t devices,
1839 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001840 audio_output_flags_t flags)
1841{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001842 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001843 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001844 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001845 }
1846
Eric Laurentcf2c0212014-07-25 16:20:43 -07001847 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001848 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1849 } else {
1850 // Audio Policy does not currently request a specific output handle.
1851 // If this is ever needed, see openInput_l() for example code.
1852 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1853 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001854 }
Eric Laurent83b88082014-06-20 18:31:16 -07001855
1856 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1857
Eric Laurent83b88082014-06-20 18:31:16 -07001858 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001859 // This if statement allows overriding the audio policy settings
1860 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1861 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1862 // Check only for Normal Mixing mode
1863 if (kEnableExtendedPrecision) {
1864 // Specify format (uncomment one below to choose)
1865 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1866 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1867 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1868 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001869 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001870 }
1871 if (kEnableExtendedChannels) {
1872 // Specify channel mask (uncomment one below to choose)
1873 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1874 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1875 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1876 }
Eric Laurent83b88082014-06-20 18:31:16 -07001877 }
1878
Phil Burk062e67a2015-02-11 13:40:50 -08001879 AudioStreamOut *outputStream = NULL;
1880 status_t status = outHwDev->openOutputStream(
1881 &outputStream,
1882 *output,
1883 devices,
1884 flags,
1885 config,
1886 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001887
1888 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001889
Phil Burk062e67a2015-02-11 13:40:50 -08001890 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001891
1892 PlaybackThread *thread;
1893 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001894 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001895 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001896 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1897 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001898 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001899 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001900 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001901 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001902 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001903 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001904 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001905 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001906 return thread;
1907 }
1908
1909 return 0;
1910}
1911
Eric Laurentcf2c0212014-07-25 16:20:43 -07001912status_t AudioFlinger::openOutput(audio_module_handle_t module,
1913 audio_io_handle_t *output,
1914 audio_config_t *config,
1915 audio_devices_t *devices,
1916 const String8& address,
1917 uint32_t *latencyMs,
1918 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919{
Phil Burk062e67a2015-02-11 13:40:50 -08001920 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001922 (devices != NULL) ? *devices : 0,
1923 config->sample_rate,
1924 config->format,
1925 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001926 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927
Eric Laurentcf2c0212014-07-25 16:20:43 -07001928 if (*devices == AUDIO_DEVICE_NONE) {
1929 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001931
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 Mutex::Autolock _l(mLock);
1933
Eric Laurentcf2c0212014-07-25 16:20:43 -07001934 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001935 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001936 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937
1938 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001939 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001940
1941 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001942 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001943 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001944 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001945
1946 AutoMutex lock(mHardwareLock);
1947 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001948 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001949 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001950 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001951 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 }
1953
Eric Laurentcf2c0212014-07-25 16:20:43 -07001954 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955}
1956
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001957audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1958 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959{
1960 Mutex::Autolock _l(mLock);
1961 MixerThread *thread1 = checkMixerThread_l(output1);
1962 MixerThread *thread2 = checkMixerThread_l(output2);
1963
1964 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001965 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1966 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001967 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 }
1969
Glenn Kasteneeecb982016-02-26 10:44:04 -08001970 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001971 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 thread->addOutputTrack(thread2);
1973 mPlaybackThreads.add(id, thread);
1974 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001975 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 return id;
1977}
1978
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001979status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980{
Glenn Kastend96c5722012-04-25 13:44:49 -07001981 return closeOutput_nonvirtual(output);
1982}
1983
1984status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1985{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 // keep strong reference on the playback thread so that
1987 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001988 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 {
1990 Mutex::Autolock _l(mLock);
1991 thread = checkPlaybackThread_l(output);
1992 if (thread == NULL) {
1993 return BAD_VALUE;
1994 }
1995
Steve Block3856b092011-10-20 11:56:00 +01001996 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001998 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07002000 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002001 DuplicatingThread *dupThread =
2002 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002004 }
2005 }
2006 }
2007
2008
2009 mPlaybackThreads.removeItem(output);
2010 // save all effects to the default thread
2011 if (mPlaybackThreads.size()) {
2012 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2013 if (dstThread != NULL) {
2014 // audioflinger lock is held here so the acquisition order of thread locks does not
2015 // matter
2016 Mutex::Autolock _dl(dstThread->mLock);
2017 Mutex::Autolock _sl(thread->mLock);
2018 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
2019 for (size_t i = 0; i < effectChains.size(); i ++) {
2020 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 }
2022 }
2023 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002024 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2025 ioDesc->mIoHandle = output;
2026 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 }
2028 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002029 // The thread entity (active unit of execution) is no longer running here,
2030 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031
Eric Laurentf6870ae2015-05-08 10:50:03 -07002032 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002033 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 }
Eric Laurent83b88082014-06-20 18:31:16 -07002035
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 return NO_ERROR;
2037}
2038
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002039void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002040{
2041 AudioStreamOut *out = thread->clearOutput();
2042 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2043 // from now on thread->mOutput is NULL
2044 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
2045 delete out;
2046}
2047
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002048void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002049{
2050 mPlaybackThreads.removeItem(thread->mId);
2051 thread->exit();
2052 closeOutputFinish(thread);
2053}
2054
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002055status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056{
2057 Mutex::Autolock _l(mLock);
2058 PlaybackThread *thread = checkPlaybackThread_l(output);
2059
2060 if (thread == NULL) {
2061 return BAD_VALUE;
2062 }
2063
Steve Block3856b092011-10-20 11:56:00 +01002064 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 thread->suspend();
2066
2067 return NO_ERROR;
2068}
2069
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002070status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071{
2072 Mutex::Autolock _l(mLock);
2073 PlaybackThread *thread = checkPlaybackThread_l(output);
2074
2075 if (thread == NULL) {
2076 return BAD_VALUE;
2077 }
2078
Steve Block3856b092011-10-20 11:56:00 +01002079 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080
2081 thread->restore();
2082
2083 return NO_ERROR;
2084}
2085
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086status_t AudioFlinger::openInput(audio_module_handle_t module,
2087 audio_io_handle_t *input,
2088 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002089 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002090 const String8& address,
2091 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002092 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093{
Eric Laurent83b88082014-06-20 18:31:16 -07002094 Mutex::Autolock _l(mLock);
2095
Glenn Kastene7d66712015-03-05 13:46:52 -08002096 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002097 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002098 }
2099
Glenn Kastene7d66712015-03-05 13:46:52 -08002100 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002101
2102 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002103 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002104 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002105 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002107 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002108}
Dima Zavin799a70e2011-04-18 16:57:27 -07002109
Eric Laurent83b88082014-06-20 18:31:16 -07002110sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002111 audio_io_handle_t *input,
2112 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002113 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 const String8& address,
2115 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002116 audio_input_flags_t flags)
2117{
Glenn Kastene7d66712015-03-05 13:46:52 -08002118 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002119 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002120 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002121 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002122 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002123
Glenn Kasteneeecb982016-02-26 10:44:04 -08002124 // Audio Policy can request a specific handle for hardware hotword.
2125 // The goal here is not to re-open an already opened input.
2126 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002127 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002128 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2129 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2130 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2131 return 0;
2132 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2133 // This should not happen in a transient state with current design.
2134 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2135 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002136 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002137
Eric Laurentcf2c0212014-07-25 16:20:43 -07002138 audio_config_t halconfig = *config;
2139 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002140 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002141 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002142 &inStream, flags, address.string(), source);
2143 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002144 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002145 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002146 halconfig.sample_rate,
2147 halconfig.format,
2148 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002149 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002150 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002152 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002153 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002154 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002155 audio_is_linear_pcm(config->format) &&
2156 audio_is_linear_pcm(halconfig.format) &&
2157 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002158 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2159 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002160 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002161 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002162 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002163 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002164 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002165 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 }
2167
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002168 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002169
Glenn Kasten46909e72013-02-26 09:20:22 -08002170#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002171 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2172 // or (re-)create if current Pipe is idle and does not match the new format
2173 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002174 enum {
2175 TEE_SINK_NO, // don't copy input
2176 TEE_SINK_NEW, // copy input using a new pipe
2177 TEE_SINK_OLD, // copy input using an existing pipe
2178 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002179 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2180 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002181 if (!mTeeSinkInputEnabled) {
2182 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002183 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002184 kind = TEE_SINK_NO;
2185 } else if (mRecordTeeSink == 0) {
2186 kind = TEE_SINK_NEW;
2187 } else if (mRecordTeeSink->getStrongCount() != 1) {
2188 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002189 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002190 kind = TEE_SINK_OLD;
2191 } else {
2192 kind = TEE_SINK_NEW;
2193 }
2194 switch (kind) {
2195 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002196 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002197 size_t numCounterOffers = 0;
2198 const NBAIO_Format offers[1] = {format};
2199 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2200 ALOG_ASSERT(index == 0);
2201 PipeReader *pipeReader = new PipeReader(*pipe);
2202 numCounterOffers = 0;
2203 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2204 ALOG_ASSERT(index == 0);
2205 mRecordTeeSink = pipe;
2206 mRecordTeeSource = pipeReader;
2207 teeSink = pipe;
2208 }
2209 break;
2210 case TEE_SINK_OLD:
2211 teeSink = mRecordTeeSink;
2212 break;
2213 case TEE_SINK_NO:
2214 default:
2215 break;
2216 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002217#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002218
Eric Laurent05067782016-06-01 18:27:28 -07002219 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002220
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002221 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002222 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002223 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002224 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002225 inputStream,
2226 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002227 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002228 devices,
2229 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002230#ifdef TEE_SINK
2231 , teeSink
2232#endif
2233 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002234 mRecordThreads.add(*input, thread);
2235 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002236 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 }
2238
Eric Laurentcf2c0212014-07-25 16:20:43 -07002239 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 return 0;
2241}
2242
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002243status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244{
Glenn Kastend96c5722012-04-25 13:44:49 -07002245 return closeInput_nonvirtual(input);
2246}
2247
2248status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2249{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 // keep strong reference on the record thread so that
2251 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002252 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 {
2254 Mutex::Autolock _l(mLock);
2255 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002256 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257 return BAD_VALUE;
2258 }
2259
Steve Block3856b092011-10-20 11:56:00 +01002260 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002261
2262 // If we still have effect chains, it means that a client still holds a handle
2263 // on at least one effect. We must either move the chain to an existing thread with the
2264 // same session ID or put it aside in case a new record thread is opened for a
2265 // new capture on the same session
2266 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002267 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002268 Mutex::Autolock _sl(thread->mLock);
2269 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002270 // Note: maximum one chain per record thread
2271 if (effectChains.size() != 0) {
2272 chain = effectChains[0];
2273 }
2274 }
2275 if (chain != 0) {
2276 // first check if a record thread is already opened with a client on the same session.
2277 // This should only happen in case of overlap between one thread tear down and the
2278 // creation of its replacement
2279 size_t i;
2280 for (i = 0; i < mRecordThreads.size(); i++) {
2281 sp<RecordThread> t = mRecordThreads.valueAt(i);
2282 if (t == thread) {
2283 continue;
2284 }
2285 if (t->hasAudioSession(chain->sessionId()) != 0) {
2286 Mutex::Autolock _l(t->mLock);
2287 ALOGV("closeInput() found thread %d for effect session %d",
2288 t->id(), chain->sessionId());
2289 t->addEffectChain_l(chain);
2290 break;
2291 }
2292 }
2293 // put the chain aside if we could not find a record thread with the same session id.
2294 if (i == mRecordThreads.size()) {
2295 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002296 }
2297 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002298 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2299 ioDesc->mIoHandle = input;
2300 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 mRecordThreads.removeItem(input);
2302 }
Eric Laurent83b88082014-06-20 18:31:16 -07002303 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2304 // we have a different lock for notification client
2305 closeInputFinish(thread);
2306 return NO_ERROR;
2307}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002309void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002310{
2311 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002312 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002313 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002314 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002315 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002316 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002317}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002319void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002320{
2321 mRecordThreads.removeItem(thread->mId);
2322 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323}
2324
Glenn Kastend2304db2014-02-03 07:40:31 -08002325status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326{
2327 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002328 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329
2330 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2331 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002332 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334
2335 return NO_ERROR;
2336}
2337
2338
Glenn Kasteneeecb982016-02-26 10:44:04 -08002339audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340{
Glenn Kasten9d003132016-04-06 14:38:09 -07002341 // This is a binder API, so a malicious client could pass in a bad parameter.
2342 // Check for that before calling the internal API nextUniqueId().
2343 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2344 ALOGE("newAudioUniqueId invalid use %d", use);
2345 return AUDIO_UNIQUE_ID_ALLOCATE;
2346 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002347 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348}
2349
Glenn Kastend848eb42016-03-08 13:42:11 -08002350void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002351{
2352 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002353 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002354 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2355 if (pid != -1 && (caller == getpid_cached)) {
2356 caller = pid;
2357 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002358
Eric Laurent021cf962014-05-13 10:18:14 -07002359 {
2360 Mutex::Autolock _cl(mClientLock);
2361 // Ignore requests received from processes not known as notification client. The request
2362 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2363 // called from a different pid leaving a stale session reference. Also we don't know how
2364 // to clear this reference if the client process dies.
2365 if (mNotificationClients.indexOfKey(caller) < 0) {
2366 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2367 return;
2368 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002369 }
2370
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002371 size_t num = mAudioSessionRefs.size();
2372 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002373 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002374 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2375 ref->mCnt++;
2376 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002377 return;
2378 }
2379 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002380 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2381 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002382}
2383
Glenn Kastend848eb42016-03-08 13:42:11 -08002384void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002385{
2386 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002387 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002388 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2389 if (pid != -1 && (caller == getpid_cached)) {
2390 caller = pid;
2391 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002392 size_t num = mAudioSessionRefs.size();
2393 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002394 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002395 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2396 ref->mCnt--;
2397 ALOGV(" decremented refcount to %d", ref->mCnt);
2398 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002399 mAudioSessionRefs.removeAt(i);
2400 delete ref;
2401 purgeStaleEffects_l();
2402 }
2403 return;
2404 }
2405 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002406 // If the caller is mediaserver it is likely that the session being released was acquired
2407 // on behalf of a process not in notification clients and we ignore the warning.
2408 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002409}
2410
2411void AudioFlinger::purgeStaleEffects_l() {
2412
Steve Block3856b092011-10-20 11:56:00 +01002413 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002414
2415 Vector< sp<EffectChain> > chains;
2416
2417 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2418 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2419 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2420 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002421 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2422 chains.push(ec);
2423 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002424 }
2425 }
2426 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2427 sp<RecordThread> t = mRecordThreads.valueAt(i);
2428 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2429 sp<EffectChain> ec = t->mEffectChains[j];
2430 chains.push(ec);
2431 }
2432 }
2433
2434 for (size_t i = 0; i < chains.size(); i++) {
2435 sp<EffectChain> ec = chains[i];
2436 int sessionid = ec->sessionId();
2437 sp<ThreadBase> t = ec->mThread.promote();
2438 if (t == 0) {
2439 continue;
2440 }
2441 size_t numsessionrefs = mAudioSessionRefs.size();
2442 bool found = false;
2443 for (size_t k = 0; k < numsessionrefs; k++) {
2444 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002445 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002446 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002447 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002448 found = true;
2449 break;
2450 }
2451 }
2452 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002453 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002454 // remove all effects from the chain
2455 while (ec->mEffects.size()) {
2456 sp<EffectModule> effect = ec->mEffects[0];
2457 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002458 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002459 if (effect->purgeHandles()) {
2460 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002461 }
2462 AudioSystem::unregisterEffect(effect->id());
2463 }
2464 }
2465 }
2466 return;
2467}
2468
Glenn Kasteneeecb982016-02-26 10:44:04 -08002469// checkThread_l() must be called with AudioFlinger::mLock held
2470AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2471{
2472 ThreadBase *thread = NULL;
2473 switch (audio_unique_id_get_use(ioHandle)) {
2474 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2475 thread = checkPlaybackThread_l(ioHandle);
2476 break;
2477 case AUDIO_UNIQUE_ID_USE_INPUT:
2478 thread = checkRecordThread_l(ioHandle);
2479 break;
2480 default:
2481 break;
2482 }
2483 return thread;
2484}
2485
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002487AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488{
Glenn Kastena1117922012-01-26 10:53:32 -08002489 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490}
2491
2492// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002493AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494{
2495 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002496 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497}
2498
2499// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002500AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501{
Glenn Kastena1117922012-01-26 10:53:32 -08002502 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
Glenn Kasteneeecb982016-02-26 10:44:04 -08002505audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506{
Glenn Kasten9d003132016-04-06 14:38:09 -07002507 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002508 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002509 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2510 for (int retry = 0; retry < maxRetries; retry++) {
2511 // The cast allows wraparound from max positive to min negative instead of abort
2512 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2513 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2514 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2515 // allow wrap by skipping 0 and -1 for session ids
2516 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2517 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2518 return (audio_unique_id_t) (base | use);
2519 }
2520 }
2521 // We have no way of recovering from wraparound
2522 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2523 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524}
2525
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002526AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002527{
2528 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2529 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002530 if(thread->isDuplicating()) {
2531 continue;
2532 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002533 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002534 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002535 return thread;
2536 }
2537 }
2538 return NULL;
2539}
2540
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002541audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002542{
2543 PlaybackThread *thread = primaryPlaybackThread_l();
2544
2545 if (thread == NULL) {
2546 return 0;
2547 }
2548
Eric Laurentf1c04f92012-08-28 14:26:53 -07002549 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002550}
2551
Glenn Kastena7335632016-06-09 17:09:53 -07002552AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2553{
2554 size_t minFrameCount = 0;
2555 PlaybackThread *minThread = NULL;
2556 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2557 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2558 if (!thread->isDuplicating()) {
2559 size_t frameCount = thread->frameCountHAL();
2560 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2561 (frameCount == minFrameCount && thread->hasFastMixer() &&
2562 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2563 minFrameCount = frameCount;
2564 minThread = thread;
2565 }
2566 }
2567 }
2568 return minThread;
2569}
2570
Eric Laurenta011e352012-03-29 15:51:43 -07002571sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002572 audio_session_t triggerSession,
2573 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002574 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002575 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002576{
2577 Mutex::Autolock _l(mLock);
2578
2579 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2580 status_t playStatus = NAME_NOT_FOUND;
2581 status_t recStatus = NAME_NOT_FOUND;
2582 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2583 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2584 if (playStatus == NO_ERROR) {
2585 return event;
2586 }
2587 }
2588 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2589 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2590 if (recStatus == NO_ERROR) {
2591 return event;
2592 }
2593 }
2594 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2595 mPendingSyncEvents.add(event);
2596 } else {
2597 ALOGV("createSyncEvent() invalid event %d", event->type());
2598 event.clear();
2599 }
2600 return event;
2601}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002602
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603// ----------------------------------------------------------------------------
2604// Effect management
2605// ----------------------------------------------------------------------------
2606
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002607sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2608 return mEffectsFactoryHal;
2609}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610
Glenn Kastenf587ba52012-01-26 16:25:10 -08002611status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612{
2613 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002614 if (mEffectsFactoryHal.get()) {
2615 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2616 } else {
2617 return -ENODEV;
2618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619}
2620
Glenn Kastenf587ba52012-01-26 16:25:10 -08002621status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622{
2623 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002624 if (mEffectsFactoryHal.get()) {
2625 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2626 } else {
2627 return -ENODEV;
2628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629}
2630
Glenn Kasten5e92a782012-01-30 07:40:52 -08002631status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002632 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633{
2634 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002635 if (mEffectsFactoryHal.get()) {
2636 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2637 } else {
2638 return -ENODEV;
2639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640}
2641
2642
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002643sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 effect_descriptor_t *pDesc,
2645 const sp<IEffectClient>& effectClient,
2646 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002647 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002648 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002649 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 status_t *status,
2651 int *id,
2652 int *enabled)
2653{
2654 status_t lStatus = NO_ERROR;
2655 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002658 pid_t pid = IPCThreadState::self()->getCallingPid();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002659 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2660 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661
2662 if (pDesc == NULL) {
2663 lStatus = BAD_VALUE;
2664 goto Exit;
2665 }
2666
Eric Laurent84e9a102010-09-23 16:10:16 -07002667 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002668 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002669 lStatus = PERMISSION_DENIED;
2670 goto Exit;
2671 }
2672
Dima Zavinfce7a472011-04-19 22:30:36 -07002673 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002674 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002675 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002676 lStatus = PERMISSION_DENIED;
2677 goto Exit;
2678 }
2679
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002680 if (mEffectsFactoryHal.get() == NULL) {
2681 lStatus = NO_INIT;
2682 goto Exit;
2683 }
2684
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002686 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002688 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002690 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691 goto Exit;
2692 }
2693 } else {
2694 // if uuid is not specified, look for an available implementation
2695 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002696 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002697 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 lStatus = BAD_VALUE;
2699 goto Exit;
2700 }
2701 uint32_t numEffects = 0;
2702 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002703 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 bool found = false;
2705
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002706 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002708 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 goto Exit;
2710 }
2711 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002712 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002714 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 continue;
2716 }
2717 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2718 // If matching type found save effect descriptor. If the session is
2719 // 0 and the effect is not auxiliary, continue enumeration in case
2720 // an auxiliary version of this effect type is available
2721 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002722 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002723 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2725 break;
2726 }
2727 }
2728 }
2729 if (!found) {
2730 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002731 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732 goto Exit;
2733 }
2734 // For same effect type, chose auxiliary version over insert version if
2735 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002736 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002738 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 }
2740 }
2741
2742 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002743 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2745 lStatus = INVALID_OPERATION;
2746 goto Exit;
2747 }
2748
Eric Laurent59255e42011-07-27 19:49:51 -07002749 // check recording permission for visualizer
2750 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002751 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002752 lStatus = PERMISSION_DENIED;
2753 goto Exit;
2754 }
2755
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002757 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002758 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002759 // if the output returned by getOutputForEffect() is removed before we lock the
2760 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2761 // and we will exit safely
2762 io = AudioSystem::getOutputForEffect(&desc);
2763 ALOGV("createEffect got output %d", io);
2764 }
2765
2766 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767
2768 // If output is not specified try to find a matching audio session ID in one of the
2769 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002770 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2771 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002772 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002773 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002774 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2775 // output must be specified by AudioPolicyManager when using session
2776 // AUDIO_SESSION_OUTPUT_STAGE
2777 lStatus = BAD_VALUE;
2778 goto Exit;
2779 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002780 // look for the thread where the specified audio session is present
2781 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2782 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2783 io = mPlaybackThreads.keyAt(i);
2784 break;
2785 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002787 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002788 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2789 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2790 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002791 break;
2792 }
2793 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002794 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002795 // If no output thread contains the requested session ID, default to
2796 // first output. The effect chain will be moved to the correct output
2797 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002798 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002799 io = mPlaybackThreads.keyAt(0);
2800 }
Steve Block3856b092011-10-20 11:56:00 +01002801 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002802 }
2803 ThreadBase *thread = checkRecordThread_l(io);
2804 if (thread == NULL) {
2805 thread = checkPlaybackThread_l(io);
2806 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002807 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002808 lStatus = BAD_VALUE;
2809 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002810 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002811 } else {
2812 // Check if one effect chain was awaiting for an effect to be created on this
2813 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002814 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002815 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002816 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002817 thread->addEffectChain_l(chain);
2818 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002820
Eric Laurent021cf962014-05-13 10:18:14 -07002821 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002823 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002824 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2825 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 if (handle != 0 && id != NULL) {
2827 *id = handle->id();
2828 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002829 if (handle == 0) {
2830 // remove local strong reference to Client with mClientLock held
2831 Mutex::Autolock _cl(mClientLock);
2832 client.clear();
2833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835
2836Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002837 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 return handle;
2839}
2840
Glenn Kastend848eb42016-03-08 13:42:11 -08002841status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002842 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002843{
Steve Block3856b092011-10-20 11:56:00 +01002844 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002845 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002846 Mutex::Autolock _l(mLock);
2847 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002848 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002849 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 }
Eric Laurentde070132010-07-13 04:45:46 -07002851 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2852 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002853 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002854 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 }
Eric Laurentde070132010-07-13 04:45:46 -07002856 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2857 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002858 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002859 return BAD_VALUE;
2860 }
2861
2862 Mutex::Autolock _dl(dstThread->mLock);
2863 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002864 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865}
2866
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002867// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002868status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002869 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002870 AudioFlinger::PlaybackThread *dstThread,
2871 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002872{
Steve Block3856b092011-10-20 11:56:00 +01002873 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002874 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002875
Eric Laurent59255e42011-07-27 19:49:51 -07002876 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002877 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002878 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002879 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002880 return INVALID_OPERATION;
2881 }
2882
Eric Laurent4c415062016-06-17 16:14:16 -07002883 // Check whether the destination thread and all effects in the chain are compatible
2884 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002885 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002886 " destination thread %p is not compatible with effects in the chain",
2887 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002888 return INVALID_OPERATION;
2889 }
2890
Eric Laurent39e94f82010-07-28 01:32:47 -07002891 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002892 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002893 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002894 // removed.
2895 srcThread->removeEffectChain_l(chain);
2896
2897 // transfer all effects one by one so that new effect chain is created on new thread with
2898 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002899 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002900 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002901 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002902 Vector< sp<EffectModule> > removed;
2903 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002904 while (effect != 0) {
2905 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002906 removed.add(effect);
2907 status = dstThread->addEffect_l(effect);
2908 if (status != NO_ERROR) {
2909 break;
2910 }
Eric Laurentec35a142011-10-05 17:42:25 -07002911 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2912 if (effect->state() == EffectModule::ACTIVE ||
2913 effect->state() == EffectModule::STOPPING) {
2914 effect->start();
2915 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002916 // if the move request is not received from audio policy manager, the effect must be
2917 // re-registered with the new strategy and output
2918 if (dstChain == 0) {
2919 dstChain = effect->chain().promote();
2920 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002921 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002922 status = NO_INIT;
2923 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002924 }
2925 strategy = dstChain->strategy();
2926 }
2927 if (reRegister) {
2928 AudioSystem::unregisterEffect(effect->id());
2929 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002930 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002931 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002932 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002933 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002934 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002935 }
Eric Laurentde070132010-07-13 04:45:46 -07002936 effect = chain->getEffectFromId_l(0);
2937 }
2938
Eric Laurent5baf2af2013-09-12 17:37:00 -07002939 if (status != NO_ERROR) {
2940 for (size_t i = 0; i < removed.size(); i++) {
2941 srcThread->addEffect_l(removed[i]);
2942 if (dstChain != 0 && reRegister) {
2943 AudioSystem::unregisterEffect(removed[i]->id());
2944 AudioSystem::registerEffect(&removed[i]->desc(),
2945 srcThread->id(),
2946 strategy,
2947 sessionId,
2948 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002949 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002950 }
2951 }
2952 }
2953
2954 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002955}
2956
Eric Laurent5baf2af2013-09-12 17:37:00 -07002957bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002958{
2959 if (mGlobalEffectEnableTime != 0 &&
2960 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2961 return true;
2962 }
2963
2964 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2965 sp<EffectChain> ec =
2966 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002967 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002968 return true;
2969 }
2970 }
2971 return false;
2972}
2973
Eric Laurent5baf2af2013-09-12 17:37:00 -07002974void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002975{
2976 Mutex::Autolock _l(mLock);
2977
2978 mGlobalEffectEnableTime = systemTime();
2979
2980 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2981 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2982 if (t->mType == ThreadBase::OFFLOAD) {
2983 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2984 }
2985 }
2986
2987}
2988
Eric Laurentaaa44472014-09-12 17:41:50 -07002989status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2990{
Glenn Kastend848eb42016-03-08 13:42:11 -08002991 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002992 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002993 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002994 if (index >= 0) {
2995 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2996 return ALREADY_EXISTS;
2997 }
2998 mOrphanEffectChains.add(session, chain);
2999 return NO_ERROR;
3000}
3001
3002sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3003{
3004 sp<EffectChain> chain;
3005 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003006 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003007 if (index >= 0) {
3008 chain = mOrphanEffectChains.valueAt(index);
3009 mOrphanEffectChains.removeItemsAt(index);
3010 }
3011 return chain;
3012}
3013
3014bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3015{
3016 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003017 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003018 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003019 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003020 if (index >= 0) {
3021 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
3022 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003023 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003024 mOrphanEffectChains.removeItemsAt(index);
3025 }
3026 return true;
3027 }
3028 return false;
3029}
3030
3031
Glenn Kastenda6ef132013-01-10 12:31:01 -08003032struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003033#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3034 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003035};
3036
3037int comparEntry(const void *p1, const void *p2)
3038{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003039 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003040}
3041
Glenn Kasten46909e72013-02-26 09:20:22 -08003042#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003043void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044{
Eric Laurent81784c32012-11-19 14:55:58 -08003045 NBAIO_Source *teeSource = source.get();
3046 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003047 // .wav rotation
3048 // There is a benign race condition if 2 threads call this simultaneously.
3049 // They would both traverse the directory, but the result would simply be
3050 // failures at unlink() which are ignored. It's also unlikely since
3051 // normally dumpsys is only done by bugreport or from the command line.
3052 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003053 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003054 size_t teePathLen = strlen(teePath);
3055 DIR *dir = opendir(teePath);
3056 teePath[teePathLen++] = '/';
3057 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003058#define TEE_MAX_SORT 20 // number of entries to sort
3059#define TEE_MAX_KEEP 10 // number of entries to keep
3060 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003061 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003062 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 struct dirent de;
3064 struct dirent *result = NULL;
3065 int rc = readdir_r(dir, &de, &result);
3066 if (rc != 0) {
3067 ALOGW("readdir_r failed %d", rc);
3068 break;
3069 }
3070 if (result == NULL) {
3071 break;
3072 }
3073 if (result != &de) {
3074 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3075 break;
3076 }
3077 // ignore non .wav file entries
3078 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003079 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003080 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3081 continue;
3082 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003083 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003084 }
3085 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003086 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003087 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003088 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3089 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003090 (void) unlink(teePath);
3091 }
3092 }
3093 } else {
3094 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003095 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003096 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003097 }
3098 }
Eric Laurent81784c32012-11-19 14:55:58 -08003099 char teeTime[16];
3100 struct timeval tv;
3101 gettimeofday(&tv, NULL);
3102 struct tm tm;
3103 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003104 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3105 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3106 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3107 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003108 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003109 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003110 char wavHeader[44];
3111 memcpy(wavHeader,
3112 "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",
3113 sizeof(wavHeader));
3114 NBAIO_Format format = teeSource->format();
3115 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003116 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003117 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003118 wavHeader[22] = channelCount; // number of channels
3119 wavHeader[24] = sampleRate; // sample rate
3120 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003121 wavHeader[32] = frameSize; // block alignment
3122 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003123 write(teeFd, wavHeader, sizeof(wavHeader));
3124 size_t total = 0;
3125 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003126#define TEE_SINK_READ 1024 // frames per I/O operation
3127 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003128 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003129 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003130 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003131 bool wasFirstRead = firstRead;
3132 firstRead = false;
3133 if (actual <= 0) {
3134 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3135 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003136 }
Eric Laurent81784c32012-11-19 14:55:58 -08003137 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003138 }
Eric Laurent81784c32012-11-19 14:55:58 -08003139 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003140 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003141 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003142 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003143 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003144 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003145 uint32_t temp = 44 + total * frameSize - 8;
3146 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003147 write(teeFd, &temp, sizeof(temp));
3148 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003149 temp = total * frameSize;
3150 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003151 write(teeFd, &temp, sizeof(temp));
3152 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003153 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003154 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003155 }
Eric Laurent59255e42011-07-27 19:49:51 -07003156 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003157 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003158 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003159 }
Eric Laurent59255e42011-07-27 19:49:51 -07003160 }
3161 }
3162}
Glenn Kasten46909e72013-02-26 09:20:22 -08003163#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003164
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165// ----------------------------------------------------------------------------
3166
3167status_t AudioFlinger::onTransact(
3168 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3169{
3170 return BnAudioFlinger::onTransact(code, data, reply, flags);
3171}
3172
Glenn Kasten63238ef2015-03-02 15:50:29 -08003173} // namespace android