blob: 7e10e48a1e9429eaa199ac071bbd636e46d3799b [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070038#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <utils/String16.h>
40#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070041#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
Dima Zavinfce7a472011-04-19 22:30:36 -070043#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <cutils/properties.h>
45
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include "AudioMixer.h"
49#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080050#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
Andy Hung6770c6f2015-04-07 13:43:36 -070052#include <media/AudioResamplerPublic.h>
53
Mikhail Naganov9fe94012016-10-14 14:57:40 -070054#include <system/audio_effects/effect_visualizer.h>
55#include <system/audio_effects/effect_ns.h>
56#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080061
Glenn Kasten9e58b552013-01-18 15:09:48 -080062#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070063#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080064#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070066#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070068#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069
rago3bd1c872016-09-26 12:58:14 -070070//#define BUFLOG_NDEBUG 0
71#include <BufLog.h>
72
Mathias Agopian65ab4712010-07-14 17:59:35 -070073// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
John Grossman1c345192012-03-27 14:00:17 -070075// Note: the following macro is used for extremely verbose logging message. In
76// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
77// 0; but one side effect of this is to turn all LOGV's as well. Some messages
78// are so verbose that we want to suppress them even when we have ALOG_ASSERT
79// turned on. Do not uncomment the #def below unless you really know what you
80// are doing and want to see all of the extremely verbose messages.
81//#define VERY_VERY_VERBOSE_LOGGING
82#ifdef VERY_VERY_VERBOSE_LOGGING
83#define ALOGVV ALOGV
84#else
85#define ALOGVV(a...) do { } while(0)
86#endif
Eric Laurentde070132010-07-13 04:45:46 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088namespace android {
89
Glenn Kastenec1d6b52011-12-12 09:04:45 -080090static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
91static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070092static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070093static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Glenn Kasten58912562012-04-03 10:45:00 -070095
John Grossman4ff14ba2012-02-08 16:37:41 -080096nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080097
Eric Laurent81784c32012-11-19 14:55:58 -080098uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070099
Glenn Kasten46909e72013-02-26 09:20:22 -0800100#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800101bool AudioFlinger::mTeeSinkInputEnabled = false;
102bool AudioFlinger::mTeeSinkOutputEnabled = false;
103bool AudioFlinger::mTeeSinkTrackEnabled = false;
104
105size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
106size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
107size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800108#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800109
Eric Laurent813e2a72013-08-31 12:59:48 -0700110// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
111// we define a minimum time during which a global effect is considered enabled.
112static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115
Marco Nelissenb2208842014-02-07 14:00:50 -0800116const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800117 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530118 case AUDIO_FORMAT_PCM:
119 switch (format) {
120 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
121 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
122 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
123 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
124 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
125 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
126 default:
127 break;
128 }
129 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800130 case AUDIO_FORMAT_MP3: return "mp3";
131 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
132 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
133 case AUDIO_FORMAT_AAC: return "aac";
134 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
135 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
136 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530137 case AUDIO_FORMAT_OPUS: return "opus";
138 case AUDIO_FORMAT_AC3: return "ac-3";
139 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800140 case AUDIO_FORMAT_IEC61937: return "iec61937";
Eric Laurente30f2092016-07-07 18:56:57 -0700141 case AUDIO_FORMAT_DTS: return "dts";
142 case AUDIO_FORMAT_DTS_HD: return "dts-hd";
143 case AUDIO_FORMAT_DOLBY_TRUEHD: return "dolby-truehd";
Marco Nelissenb2208842014-02-07 14:00:50 -0800144 default:
145 break;
146 }
147 return "unknown";
148}
149
Mathias Agopian65ab4712010-07-14 17:59:35 -0700150// ----------------------------------------------------------------------------
151
152AudioFlinger::AudioFlinger()
153 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800155 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700156 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700159 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700161 mBtNrecIsOff(false),
162 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700163 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700164 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700165 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700166{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700167 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
168 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
169 // zero ID has a special meaning, so unavailable
170 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
171 }
172
Glenn Kasten949a9262013-04-16 12:35:20 -0700173 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800174 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800175 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800176 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
177 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800178 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700179
Wei Jia3f273d12015-11-24 09:06:49 -0800180 // reset battery stats.
181 // if the audio service has crashed, battery stats could be left
182 // in bad state, reset the state upon service start.
183 BatteryNotifier::getInstance().noteResetAudio();
184
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700185 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700186 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
187
Glenn Kasten46909e72013-02-26 09:20:22 -0800188#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800189 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800190 (void) property_get("ro.debuggable", value, "0");
191 int debuggable = atoi(value);
192 int teeEnabled = 0;
193 if (debuggable) {
194 (void) property_get("af.tee", value, "0");
195 teeEnabled = atoi(value);
196 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800197 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700198 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800199 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700200 }
201 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800202 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700203 }
204 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800205 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700206 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800207#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700208}
209
210void AudioFlinger::onFirstRef()
211{
Eric Laurent93575202011-01-18 18:39:02 -0800212 Mutex::Autolock _l(mLock);
213
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800215 char val_str[PROPERTY_VALUE_MAX] = { 0 };
216 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
217 uint32_t int_val;
218 if (1 == sscanf(val_str, "%u", &int_val)) {
219 mStandbyTimeInNsecs = milliseconds(int_val);
220 ALOGI("Using %u mSec as standby time.", int_val);
221 } else {
222 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
223 ALOGI("Using default %u mSec as standby time.",
224 (uint32_t)(mStandbyTimeInNsecs / 1000000));
225 }
226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227
Eric Laurent1c333e22014-05-20 10:48:17 -0700228 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700229
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231}
232
233AudioFlinger::~AudioFlinger()
234{
235 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700236 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700237 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700238 }
239 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700240 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700241 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700248
249 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800250 if (mLogMemoryDealer != 0) {
251 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
252 if (binder != 0) {
253 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
254 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
255 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
256 mUnregisteredWriters.pop();
257 mediaLogService->unregisterWriter(iMemory);
258 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700259 }
260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261}
262
Eric Laurenta4c5a552012-03-29 10:12:40 -0700263static const char * const audio_interfaces[] = {
264 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
265 AUDIO_HARDWARE_MODULE_ID_A2DP,
266 AUDIO_HARDWARE_MODULE_ID_USB,
267};
268#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
269
Phil Burk062e67a2015-02-11 13:40:50 -0800270AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700271 audio_module_handle_t module,
272 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700273{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274 // if module is 0, the request comes from an old policy manager and we should load
275 // well known modules
276 if (module == 0) {
277 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
278 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
279 loadHwModule_l(audio_interfaces[i]);
280 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700281 // then try to find a module supporting the requested device.
282 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
283 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700284 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
285 uint32_t supportedDevices;
286 if (dev->getSupportedDevices(&supportedDevices) == OK &&
287 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700288 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700289 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700290 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700291 } else {
292 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700293 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
294 if (audioHwDevice != NULL) {
295 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 }
297 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298
Dima Zavin799a70e2011-04-18 16:57:27 -0700299 return NULL;
300}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301
Glenn Kasten0f11b512014-01-31 16:18:54 -0800302void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append("Clients:\n");
309 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800310 sp<Client> client = mClients.valueAt(i).promote();
311 if (client != 0) {
312 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314 }
315 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316
Eric Laurentd1b28d42013-09-18 18:47:13 -0700317 result.append("Notification Clients:\n");
318 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
319 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
320 result.append(buffer);
321 }
322
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700323 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800324 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700325 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
326 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800327 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700328 result.append(buffer);
329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331}
332
333
Glenn Kasten0f11b512014-01-31 16:18:54 -0800334void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335{
336 const size_t SIZE = 256;
337 char buffer[SIZE];
338 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800339 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340
John Grossman4ff14ba2012-02-08 16:37:41 -0800341 snprintf(buffer, SIZE, "Hardware status: %d\n"
342 "Standby Time mSec: %u\n",
343 hardwareStatus,
344 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 result.append(buffer);
346 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350{
351 const size_t SIZE = 256;
352 char buffer[SIZE];
353 String8 result;
354 snprintf(buffer, SIZE, "Permission Denial: "
355 "can't dump AudioFlinger from pid=%d, uid=%d\n",
356 IPCThreadState::self()->getCallingPid(),
357 IPCThreadState::self()->getCallingUid());
358 result.append(buffer);
359 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700360}
361
Eric Laurent81784c32012-11-19 14:55:58 -0800362bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363{
364 bool locked = false;
365 for (int i = 0; i < kDumpLockRetries; ++i) {
366 if (mutex.tryLock() == NO_ERROR) {
367 locked = true;
368 break;
369 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800370 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 return locked;
373}
374
375status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
376{
Glenn Kasten44deb052012-02-05 18:09:08 -0800377 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378 dumpPermissionDenial(fd, args);
379 } else {
380 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800381 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 if (!hardwareLocked) {
383 String8 result(kHardwareLockedString);
384 write(fd, result.string(), result.size());
385 } else {
386 mHardwareLock.unlock();
387 }
388
Eric Laurent81784c32012-11-19 14:55:58 -0800389 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390
391 // failed to lock - AudioFlinger is probably deadlocked
392 if (!locked) {
393 String8 result(kDeadlockedString);
394 write(fd, result.string(), result.size());
395 }
396
Eric Laurent021cf962014-05-13 10:18:14 -0700397 bool clientLocked = dumpTryLock(mClientLock);
398 if (!clientLocked) {
399 String8 result(kClientLockedString);
400 write(fd, result.string(), result.size());
401 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700402
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700403 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700404 mEffectsFactoryHal->dumpEffects(fd);
405 } else {
406 String8 result(kNoEffectsFactory);
407 write(fd, result.string(), result.size());
408 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700409
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700411 if (clientLocked) {
412 mClientLock.unlock();
413 }
414
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415 dumpInternals(fd, args);
416
417 // dump playback threads
418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
419 mPlaybackThreads.valueAt(i)->dump(fd, args);
420 }
421
422 // dump record threads
423 for (size_t i = 0; i < mRecordThreads.size(); i++) {
424 mRecordThreads.valueAt(i)->dump(fd, args);
425 }
426
Eric Laurentaaa44472014-09-12 17:41:50 -0700427 // dump orphan effect chains
428 if (mOrphanEffectChains.size() != 0) {
429 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
430 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
431 mOrphanEffectChains.valueAt(i)->dump(fd, args);
432 }
433 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700434 // dump all hardware devs
435 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700436 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
437 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700439
Glenn Kasten46909e72013-02-26 09:20:22 -0800440#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700441 // dump the serially shared record tee sink
442 if (mRecordTeeSource != 0) {
443 dumpTee(fd, mRecordTeeSource);
444 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800445#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700446
rago3bd1c872016-09-26 12:58:14 -0700447 BUFLOG_RESET;
448
Glenn Kastend65d73c2012-06-22 17:21:07 -0700449 if (locked) {
450 mLock.unlock();
451 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800452
453 // append a copy of media.log here by forwarding fd to it, but don't attempt
454 // to lookup the service if it's not running, as it will block for a second
455 if (mLogMemoryDealer != 0) {
456 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
457 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700458 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800459 Vector<String16> args;
460 binder->dump(fd, args);
461 }
462 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700463
464 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700465 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700466 bool unreachableMemory = false;
467 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700468 if (arg == String16("-m")) {
469 dumpMem = true;
470 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700471 unreachableMemory = true;
472 }
473 }
474
Andy Hung07b745e2016-05-23 16:21:07 -0700475 if (dumpMem) {
476 dprintf(fd, "\nDumping memory:\n");
477 std::string s = dumpMemoryAddresses(100 /* limit */);
478 write(fd, s.c_str(), s.size());
479 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700480 if (unreachableMemory) {
481 dprintf(fd, "\nDumping unreachable memory:\n");
482 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700483 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700484 write(fd, s.c_str(), s.size());
485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 }
487 return NO_ERROR;
488}
489
Eric Laurent021cf962014-05-13 10:18:14 -0700490sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800491{
Eric Laurent021cf962014-05-13 10:18:14 -0700492 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800493 // If pid is already in the mClients wp<> map, then use that entry
494 // (for which promote() is always != 0), otherwise create a new entry and Client.
495 sp<Client> client = mClients.valueFor(pid).promote();
496 if (client == 0) {
497 client = new Client(this, pid);
498 mClients.add(pid, client);
499 }
500
501 return client;
502}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503
Glenn Kasten9e58b552013-01-18 15:09:48 -0800504sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
505{
Glenn Kasten481fb672013-09-30 14:39:28 -0700506 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800507 if (mLogMemoryDealer == 0) {
508 return new NBLog::Writer();
509 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800510 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700511 // Similarly if we can't contact the media.log service, also return a dummy writer
512 if (binder == 0) {
513 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800514 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700515 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
516 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
517 // If allocation fails, consult the vector of previously unregistered writers
518 // and garbage-collect one or more them until an allocation succeeds
519 if (shared == 0) {
520 Mutex::Autolock _l(mUnregisteredWritersLock);
521 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
522 {
523 // Pick the oldest stale writer to garbage-collect
524 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
525 mUnregisteredWriters.removeAt(0);
526 mediaLogService->unregisterWriter(iMemory);
527 // Now the media.log remote reference to IMemory is gone. When our last local
528 // reference to IMemory also drops to zero at end of this block,
529 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
530 }
531 // Re-attempt the allocation
532 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
533 if (shared != 0) {
534 goto success;
535 }
536 }
537 // Even after garbage-collecting all old writers, there is still not enough memory,
538 // so return a dummy writer
539 return new NBLog::Writer();
540 }
541success:
542 mediaLogService->registerWriter(shared, size, name);
543 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800544}
545
546void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
547{
Glenn Kasten685ef092013-02-04 08:15:34 -0800548 if (writer == 0) {
549 return;
550 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800551 sp<IMemory> iMemory(writer->getIMemory());
552 if (iMemory == 0) {
553 return;
554 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700555 // Rather than removing the writer immediately, append it to a queue of old writers to
556 // be garbage-collected later. This allows us to continue to view old logs for a while.
557 Mutex::Autolock _l(mUnregisteredWritersLock);
558 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800559}
560
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561// IAudioFlinger interface
562
563
564sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800565 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800567 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700568 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800569 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700570 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700573 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800574 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800575 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800576 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 status_t *status)
578{
579 sp<PlaybackThread::Track> track;
580 sp<TrackHandle> trackHandle;
581 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800583 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700585 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
586 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
587 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
588 ALOGW_IF(pid != -1 && pid != callingPid,
589 "%s uid %d pid %d tried to pass itself off as pid %d",
590 __func__, callingUid, callingPid, pid);
591 pid = callingPid;
592 }
593
Glenn Kasten263709e2012-01-06 08:40:01 -0800594 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
595 // but if someone uses binder directly they could bypass that and cause us to crash
596 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000597 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 lStatus = BAD_VALUE;
599 goto Exit;
600 }
601
Glenn Kasten53b5d092014-02-05 10:00:23 -0800602 // further sample rate checks are performed by createTrack_l() depending on the thread type
603 if (sampleRate == 0) {
604 ALOGE("createTrack() invalid sample rate %u", sampleRate);
605 lStatus = BAD_VALUE;
606 goto Exit;
607 }
608
609 // further channel mask checks are performed by createTrack_l() depending on the thread type
610 if (!audio_is_output_channel(channelMask)) {
611 ALOGE("createTrack() invalid channel mask %#x", channelMask);
612 lStatus = BAD_VALUE;
613 goto Exit;
614 }
615
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700616 // further format checks are performed by createTrack_l() depending on the thread type
617 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800618 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700619 lStatus = BAD_VALUE;
620 goto Exit;
621 }
622
Glenn Kasten663c2242013-09-24 11:52:37 -0700623 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
624 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
625 lStatus = BAD_VALUE;
626 goto Exit;
627 }
628
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 {
630 Mutex::Autolock _l(mLock);
631 PlaybackThread *thread = checkPlaybackThread_l(output);
632 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800633 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634 lStatus = BAD_VALUE;
635 goto Exit;
636 }
637
Eric Laurent021cf962014-05-13 10:18:14 -0700638 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
Glenn Kastene848bd92014-03-13 15:00:32 -0700640 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700641 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800642 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
643 ALOGE("createTrack() invalid session ID %d", *sessionId);
644 lStatus = BAD_VALUE;
645 goto Exit;
646 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700647 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700648 // check if an effect chain with the same session ID is present on another
649 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700650 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700651 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
652 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700653 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700654 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700655 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700656 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700657 }
Eric Laurentde070132010-07-13 04:45:46 -0700658 }
659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700661 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800662 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663 if (sessionId != NULL) {
664 *sessionId = lSessionId;
665 }
666 }
Steve Block3856b092011-10-20 11:56:00 +0100667 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668
669 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800670 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800671 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700672 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700673
674 // move effect chain to this output thread if an effect on same session was waiting
675 // for a track to be created
676 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700677 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700678 Mutex::Autolock _dl(thread->mLock);
679 Mutex::Autolock _sl(effectThread->mLock);
680 moveEffectChain_l(lSessionId, effectThread, thread, true);
681 }
Eric Laurenta011e352012-03-29 15:51:43 -0700682
683 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700684 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700685 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
686 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700687 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700688 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700689 } else {
690 mPendingSyncEvents[i]->cancel();
691 }
Eric Laurenta011e352012-03-29 15:51:43 -0700692 mPendingSyncEvents.removeAt(i);
693 i--;
694 }
695 }
696 }
Glenn Kastene198c362013-08-13 09:13:36 -0700697
Glenn Kastend848eb42016-03-08 13:42:11 -0800698 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 }
Glenn Kastene198c362013-08-13 09:13:36 -0700700
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700701 if (lStatus != NO_ERROR) {
702 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700703 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700704 // Don't hold mClientLock when releasing the reference on the track as the
705 // destructor will acquire it.
706 {
707 Mutex::Autolock _cl(mClientLock);
708 client.clear();
709 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700711 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712 }
713
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700714 // return handle to client
715 trackHandle = new TrackHandle(track);
716
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700718 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 return trackHandle;
720}
721
Glenn Kasten2c073da2016-02-26 09:14:08 -0800722uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723{
724 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800725 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800727 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 return 0;
729 }
730 return thread->sampleRate();
731}
732
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800733audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734{
735 Mutex::Autolock _l(mLock);
736 PlaybackThread *thread = checkPlaybackThread_l(output);
737 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000738 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800739 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 }
741 return thread->format();
742}
743
Glenn Kasten2c073da2016-02-26 09:14:08 -0800744size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745{
746 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800747 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800749 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 return 0;
751 }
Glenn Kasten58912562012-04-03 10:45:00 -0700752 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
753 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 return thread->frameCount();
755}
756
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700757size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
758{
759 Mutex::Autolock _l(mLock);
760 ThreadBase *thread = checkThread_l(ioHandle);
761 if (thread == NULL) {
762 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
763 return 0;
764 }
765 return thread->frameCountHAL();
766}
767
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800768uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769{
770 Mutex::Autolock _l(mLock);
771 PlaybackThread *thread = checkPlaybackThread_l(output);
772 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800773 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774 return 0;
775 }
776 return thread->latency();
777}
778
779status_t AudioFlinger::setMasterVolume(float value)
780{
Eric Laurenta1884f92011-08-23 08:25:03 -0700781 status_t ret = initCheck();
782 if (ret != NO_ERROR) {
783 return ret;
784 }
785
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 // check calling permissions
787 if (!settingsAllowed()) {
788 return PERMISSION_DENIED;
789 }
790
Eric Laurenta4c5a552012-03-29 10:12:40 -0700791 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700792 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700793
John Grossmanee578c02012-07-23 17:05:46 -0700794 // Set master volume in the HALs which support it.
795 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
796 AutoMutex lock(mHardwareLock);
797 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800798
John Grossmanee578c02012-07-23 17:05:46 -0700799 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
800 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700801 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800802 }
John Grossmanee578c02012-07-23 17:05:46 -0700803 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805
John Grossmanee578c02012-07-23 17:05:46 -0700806 // Now set the master volume in each playback thread. Playback threads
807 // assigned to HALs which do not have master volume support will apply
808 // master volume during the mix operation. Threads with HALs which do
809 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700810 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
811 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
812 continue;
813 }
John Grossmanee578c02012-07-23 17:05:46 -0700814 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700815 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816
817 return NO_ERROR;
818}
819
Glenn Kastenf78aee72012-01-04 11:00:47 -0800820status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821{
Eric Laurenta1884f92011-08-23 08:25:03 -0700822 status_t ret = initCheck();
823 if (ret != NO_ERROR) {
824 return ret;
825 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826
827 // check calling permissions
828 if (!settingsAllowed()) {
829 return PERMISSION_DENIED;
830 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800831 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000832 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return BAD_VALUE;
834 }
835
836 { // scope for the lock
837 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700838 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700840 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 mHardwareStatus = AUDIO_HW_IDLE;
842 }
843
844 if (NO_ERROR == ret) {
845 Mutex::Autolock _l(mLock);
846 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800847 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700848 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 }
850
851 return ret;
852}
853
854status_t AudioFlinger::setMicMute(bool state)
855{
Eric Laurenta1884f92011-08-23 08:25:03 -0700856 status_t ret = initCheck();
857 if (ret != NO_ERROR) {
858 return ret;
859 }
860
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861 // check calling permissions
862 if (!settingsAllowed()) {
863 return PERMISSION_DENIED;
864 }
865
866 AutoMutex lock(mHardwareLock);
867 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700868 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700869 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
870 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700871 if (result != NO_ERROR) {
872 ret = result;
873 }
874 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 mHardwareStatus = AUDIO_HW_IDLE;
876 return ret;
877}
878
879bool AudioFlinger::getMicMute() const
880{
Eric Laurenta1884f92011-08-23 08:25:03 -0700881 status_t ret = initCheck();
882 if (ret != NO_ERROR) {
883 return false;
884 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800885 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700886 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800887 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800889 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700890 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
891 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800892 if (result == NO_ERROR) {
893 mute = mute && state;
894 }
895 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800897
898 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899}
900
901status_t AudioFlinger::setMasterMute(bool muted)
902{
John Grossmand8f178d2012-07-20 14:51:35 -0700903 status_t ret = initCheck();
904 if (ret != NO_ERROR) {
905 return ret;
906 }
907
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908 // check calling permissions
909 if (!settingsAllowed()) {
910 return PERMISSION_DENIED;
911 }
912
John Grossmanee578c02012-07-23 17:05:46 -0700913 Mutex::Autolock _l(mLock);
914 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700915
John Grossmanee578c02012-07-23 17:05:46 -0700916 // Set master mute in the HALs which support it.
917 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
918 AutoMutex lock(mHardwareLock);
919 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700920
John Grossmanee578c02012-07-23 17:05:46 -0700921 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
922 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700923 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700924 }
John Grossmanee578c02012-07-23 17:05:46 -0700925 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700926 }
927
John Grossmanee578c02012-07-23 17:05:46 -0700928 // Now set the master mute in each playback thread. Playback threads
929 // assigned to HALs which do not have master mute support will apply master
930 // mute during the mix operation. Threads with HALs which do support master
931 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700932 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
933 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
934 continue;
935 }
John Grossmanee578c02012-07-23 17:05:46 -0700936 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938
939 return NO_ERROR;
940}
941
942float AudioFlinger::masterVolume() const
943{
Glenn Kasten98067102011-12-13 11:47:54 -0800944 Mutex::Autolock _l(mLock);
945 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946}
947
948bool AudioFlinger::masterMute() const
949{
Glenn Kasten98067102011-12-13 11:47:54 -0800950 Mutex::Autolock _l(mLock);
951 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
John Grossman4ff14ba2012-02-08 16:37:41 -0800954float AudioFlinger::masterVolume_l() const
955{
John Grossman4ff14ba2012-02-08 16:37:41 -0800956 return mMasterVolume;
957}
958
John Grossmand8f178d2012-07-20 14:51:35 -0700959bool AudioFlinger::masterMute_l() const
960{
John Grossmanee578c02012-07-23 17:05:46 -0700961 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700962}
963
Eric Laurent223fd5c2014-11-11 13:43:36 -0800964status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
965{
966 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
967 ALOGW("setStreamVolume() invalid stream %d", stream);
968 return BAD_VALUE;
969 }
970 pid_t caller = IPCThreadState::self()->getCallingPid();
971 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
972 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
973 return PERMISSION_DENIED;
974 }
975
976 return NO_ERROR;
977}
978
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800979status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
980 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981{
982 // check calling permissions
983 if (!settingsAllowed()) {
984 return PERMISSION_DENIED;
985 }
986
Eric Laurent223fd5c2014-11-11 13:43:36 -0800987 status_t status = checkStreamType(stream);
988 if (status != NO_ERROR) {
989 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800991 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992
993 AutoMutex lock(mLock);
994 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700995 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 thread = checkPlaybackThread_l(output);
997 if (thread == NULL) {
998 return BAD_VALUE;
999 }
1000 }
1001
1002 mStreamTypes[stream].volume = value;
1003
1004 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001006 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 }
1008 } else {
1009 thread->setStreamVolume(stream, value);
1010 }
1011
1012 return NO_ERROR;
1013}
1014
Glenn Kastenfff6d712012-01-12 16:38:12 -08001015status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
1017 // check calling permissions
1018 if (!settingsAllowed()) {
1019 return PERMISSION_DENIED;
1020 }
1021
Eric Laurent223fd5c2014-11-11 13:43:36 -08001022 status_t status = checkStreamType(stream);
1023 if (status != NO_ERROR) {
1024 return status;
1025 }
1026 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1027
1028 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001029 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 return BAD_VALUE;
1031 }
1032
Eric Laurent93575202011-01-18 18:39:02 -08001033 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001035 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001036 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037
1038 return NO_ERROR;
1039}
1040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001041float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001043 status_t status = checkStreamType(stream);
1044 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 return 0.0f;
1046 }
1047
1048 AutoMutex lock(mLock);
1049 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001050 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 PlaybackThread *thread = checkPlaybackThread_l(output);
1052 if (thread == NULL) {
1053 return 0.0f;
1054 }
1055 volume = thread->streamVolume(stream);
1056 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001057 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 }
1059
1060 return volume;
1061}
1062
Glenn Kastenfff6d712012-01-12 16:38:12 -08001063bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001065 status_t status = checkStreamType(stream);
1066 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 return true;
1068 }
1069
Glenn Kasten6637baa2012-01-09 09:40:36 -08001070 AutoMutex lock(mLock);
1071 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072}
1073
Eric Laurent054d9d32015-04-24 08:48:48 -07001074
1075void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1076{
1077 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1078 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1079 }
1080}
1081
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001082status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001084 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1085 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001086
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 // check calling permissions
1088 if (!settingsAllowed()) {
1089 return PERMISSION_DENIED;
1090 }
1091
Glenn Kasten142f5192014-03-25 17:44:59 -07001092 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1093 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001094 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001095 // result will remain NO_INIT if no audio device is present
1096 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001097 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001098 AutoMutex lock(mHardwareLock);
1099 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1100 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001101 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1102 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001103 // return success if at least one audio device accepts the parameters as not all
1104 // HALs are requested to support all parameters. If no audio device supports the
1105 // requested parameters, the last error is reported.
1106 if (final_result != NO_ERROR) {
1107 final_result = result;
1108 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001109 }
1110 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001111 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001112 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1113 AudioParameter param = AudioParameter(keyValuePairs);
1114 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001115 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1116 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001117 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001118 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1119 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001120 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001121 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1122 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001123 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001124 // suspend effects associated with those session IDs
1125 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001126 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001127 thread->setEffectSuspended(FX_IID_AEC,
1128 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001129 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001130 thread->setEffectSuspended(FX_IID_NS,
1131 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001132 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001133 }
1134 }
Eric Laurentbee53372011-08-29 12:42:48 -07001135 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001136 }
1137 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001138 String8 screenState;
1139 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001140 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001141 if (isOff != (AudioFlinger::mScreenState & 1)) {
1142 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001143 }
1144 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001145 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 }
1147
1148 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1149 // and the thread is exited once the lock is released
1150 sp<ThreadBase> thread;
1151 {
1152 Mutex::Autolock _l(mLock);
1153 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001154 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001156 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001157 // indicate output device change to all input threads for pre processing
1158 AudioParameter param = AudioParameter(keyValuePairs);
1159 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001160 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1161 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001162 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 }
1165 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001166 if (thread != 0) {
1167 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 }
1169 return BAD_VALUE;
1170}
1171
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001172String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001174 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1175 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176
Eric Laurenta4c5a552012-03-29 10:12:40 -07001177 Mutex::Autolock _l(mLock);
1178
Glenn Kasten142f5192014-03-25 17:44:59 -07001179 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001180 String8 out_s8;
1181
Dima Zavin799a70e2011-04-18 16:57:27 -07001182 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001183 String8 s;
1184 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001185 {
1186 AutoMutex lock(mHardwareLock);
1187 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001188 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1189 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001190 mHardwareStatus = AUDIO_HW_IDLE;
1191 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001192 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001193 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001194 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 }
1196
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1198 if (playbackThread != NULL) {
1199 return playbackThread->getParameters(keys);
1200 }
1201 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1202 if (recordThread != NULL) {
1203 return recordThread->getParameters(keys);
1204 }
1205 return String8("");
1206}
1207
Glenn Kastendd8104c2012-07-02 12:42:44 -07001208size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1209 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210{
Eric Laurenta1884f92011-08-23 08:25:03 -07001211 status_t ret = initCheck();
1212 if (ret != NO_ERROR) {
1213 return 0;
1214 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001215 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001216 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001217 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001218 return 0;
1219 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001220
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001221 AutoMutex lock(mHardwareLock);
1222 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001223 audio_config_t config, proposed;
1224 memset(&proposed, 0, sizeof(proposed));
1225 proposed.sample_rate = sampleRate;
1226 proposed.channel_mask = channelMask;
1227 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001228
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001229 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001230 size_t frames;
1231 for (;;) {
1232 // Note: config is currently a const parameter for get_input_buffer_size()
1233 // but we use a copy from proposed in case config changes from the call.
1234 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001235 status_t result = dev->getInputBufferSize(&config, &frames);
1236 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001237 break; // hal success, config is the result
1238 }
1239 // change one parameter of the configuration each iteration to a more "common" value
1240 // to see if the device will support it.
1241 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1242 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1243 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1244 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1245 } else {
1246 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1247 "format %#x, channelMask 0x%X",
1248 sampleRate, format, channelMask);
1249 break; // retries failed, break out of loop with frames == 0.
1250 }
1251 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001252 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001253 if (frames > 0 && config.sample_rate != sampleRate) {
1254 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1255 }
1256 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257}
1258
Glenn Kasten5f972c02014-01-13 09:59:31 -08001259uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261 Mutex::Autolock _l(mLock);
1262
1263 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1264 if (recordThread != NULL) {
1265 return recordThread->getInputFramesLost();
1266 }
1267 return 0;
1268}
1269
1270status_t AudioFlinger::setVoiceVolume(float value)
1271{
Eric Laurenta1884f92011-08-23 08:25:03 -07001272 status_t ret = initCheck();
1273 if (ret != NO_ERROR) {
1274 return ret;
1275 }
1276
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277 // check calling permissions
1278 if (!settingsAllowed()) {
1279 return PERMISSION_DENIED;
1280 }
1281
1282 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001283 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001284 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001285 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286 mHardwareStatus = AUDIO_HW_IDLE;
1287
1288 return ret;
1289}
1290
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001291status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001292 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294 Mutex::Autolock _l(mLock);
1295
1296 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1297 if (playbackThread != NULL) {
1298 return playbackThread->getRenderPosition(halFrames, dspFrames);
1299 }
1300
1301 return BAD_VALUE;
1302}
1303
1304void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1305{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001307 if (client == 0) {
1308 return;
1309 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001310 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001311 {
1312 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001313 if (mNotificationClients.indexOfKey(pid) < 0) {
1314 sp<NotificationClient> notificationClient = new NotificationClient(this,
1315 client,
1316 pid);
1317 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318
Eric Laurent021cf962014-05-13 10:18:14 -07001319 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320
Marco Nelissen06b46062014-11-14 07:58:25 -08001321 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001322 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001323 }
1324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325
Eric Laurent021cf962014-05-13 10:18:14 -07001326 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001327 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001328 // the config change is always sent from playback or record threads to avoid deadlock
1329 // with AudioSystem::gLock
1330 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1331 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001334 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1335 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336 }
1337}
1338
1339void AudioFlinger::removeNotificationClient(pid_t pid)
1340{
1341 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001342 {
1343 Mutex::Autolock _cl(mClientLock);
1344 mNotificationClients.removeItem(pid);
1345 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001346
Steve Block3856b092011-10-20 11:56:00 +01001347 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001348 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001349 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001350 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001351 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001352 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001353 if (ref->mPid == pid) {
1354 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001355 mAudioSessionRefs.removeAt(i);
1356 delete ref;
1357 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001358 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001359 } else {
1360 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001361 }
1362 }
1363 if (removed) {
1364 purgeStaleEffects_l();
1365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366}
1367
Eric Laurent73e26b62015-04-27 16:55:58 -07001368void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369 const sp<AudioIoDescriptor>& ioDesc,
1370 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371{
Eric Laurent021cf962014-05-13 10:18:14 -07001372 Mutex::Autolock _l(mClientLock);
1373 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001375 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1376 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1377 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 }
1379}
1380
Eric Laurent021cf962014-05-13 10:18:14 -07001381// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382void AudioFlinger::removeClient_l(pid_t pid)
1383{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001384 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001385 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 mClients.removeItem(pid);
1387}
1388
Eric Laurent717e1282012-06-29 16:36:52 -07001389// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001390sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1391 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001392{
1393 sp<PlaybackThread> thread;
1394
1395 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1396 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1397 ALOG_ASSERT(thread == 0);
1398 thread = mPlaybackThreads.valueAt(i);
1399 }
1400 }
1401
1402 return thread;
1403}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406
1407// ----------------------------------------------------------------------------
1408
1409AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1410 : RefBase(),
1411 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001412 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001413{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301414 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1415 heapSize *= 1024;
1416 if (!heapSize) {
1417 heapSize = kClientSharedHeapSizeBytes;
1418 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1419 // invalidated tracks
1420 if (!audioFlinger->isLowRamDevice()) {
1421 heapSize *= kClientSharedHeapSizeMultiplier;
1422 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001423 }
1424 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425}
1426
Eric Laurent021cf962014-05-13 10:18:14 -07001427// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428AudioFlinger::Client::~Client()
1429{
1430 mAudioFlinger->removeClient_l(mPid);
1431}
1432
Glenn Kasten435dbe62012-01-30 10:15:48 -08001433sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434{
1435 return mMemoryDealer;
1436}
1437
1438// ----------------------------------------------------------------------------
1439
1440AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1441 const sp<IAudioFlingerClient>& client,
1442 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001443 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444{
1445}
1446
1447AudioFlinger::NotificationClient::~NotificationClient()
1448{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449}
1450
Glenn Kasten0f11b512014-01-31 16:18:54 -08001451void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452{
1453 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001454 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455}
1456
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457
1458// ----------------------------------------------------------------------------
1459
1460sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001461 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001463 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001464 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001465 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001466 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001467 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001468 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001469 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001470 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001471 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001472 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001473 sp<IMemory>& cblk,
1474 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 status_t *status)
1476{
1477 sp<RecordThread::RecordTrack> recordTrack;
1478 sp<RecordHandle> recordHandle;
1479 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001481 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482
Glenn Kastend776ac62014-05-07 09:16:09 -07001483 cblk.clear();
1484 buffers.clear();
1485
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001486 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001487 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1488 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001489 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001490 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1491 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001492 updatePid = true;
1493 }
1494
1495 if (updatePid) {
1496 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1497 ALOGW_IF(pid != -1 && pid != callingPid,
1498 "%s uid %d pid %d tried to pass itself off as pid %d",
1499 __func__, callingUid, callingPid, pid);
1500 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001501 }
1502
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001504 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001505 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001506 lStatus = PERMISSION_DENIED;
1507 goto Exit;
1508 }
1509
Glenn Kasten53b5d092014-02-05 10:00:23 -08001510 // further sample rate checks are performed by createRecordTrack_l()
1511 if (sampleRate == 0) {
1512 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
1516
Andy Hung6770c6f2015-04-07 13:43:36 -07001517 // we don't yet support anything other than linear PCM
1518 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001519 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001520 lStatus = BAD_VALUE;
1521 goto Exit;
1522 }
1523
Glenn Kasten53b5d092014-02-05 10:00:23 -08001524 // further channel mask checks are performed by createRecordTrack_l()
1525 if (!audio_is_input_channel(channelMask)) {
1526 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1527 lStatus = BAD_VALUE;
1528 goto Exit;
1529 }
1530
Glenn Kasten05997e22014-03-13 15:08:33 -07001531 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001533 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001535 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 lStatus = BAD_VALUE;
1537 goto Exit;
1538 }
1539
Eric Laurent021cf962014-05-13 10:18:14 -07001540 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001542 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001543 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1544 lStatus = BAD_VALUE;
1545 goto Exit;
1546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 lSessionId = *sessionId;
1548 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001549 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001550 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 if (sessionId != NULL) {
1552 *sessionId = lSessionId;
1553 }
1554 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001555 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001556
Glenn Kasten1879fff2012-07-11 15:36:59 -07001557 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001558 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001559 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001560 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001561
1562 if (lStatus == NO_ERROR) {
1563 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1564 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001565 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001566 if (chain != 0) {
1567 Mutex::Autolock _l(thread->mLock);
1568 thread->addEffectChain_l(chain);
1569 }
1570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 }
Glenn Kastene198c362013-08-13 09:13:36 -07001572
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001573 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001574 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001575 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001576 // Don't hold mClientLock when releasing the reference on the track as the
1577 // destructor will acquire it.
1578 {
1579 Mutex::Autolock _cl(mClientLock);
1580 client.clear();
1581 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 goto Exit;
1584 }
1585
Glenn Kastend776ac62014-05-07 09:16:09 -07001586 cblk = recordTrack->getCblk();
1587 buffers = recordTrack->getBuffers();
1588
Glenn Kasten2fc14732013-08-05 14:58:14 -07001589 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591
1592Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001593 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 return recordHandle;
1595}
1596
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001597
1598
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599// ----------------------------------------------------------------------------
1600
Eric Laurenta4c5a552012-03-29 10:12:40 -07001601audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1602{
Eric Laurent44622db2014-08-01 19:00:33 -07001603 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001604 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001605 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001606 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001607 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001608 }
1609 Mutex::Autolock _l(mLock);
1610 return loadHwModule_l(name);
1611}
1612
1613// loadHwModule_l() must be called with AudioFlinger::mLock held
1614audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1615{
1616 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1617 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1618 ALOGW("loadHwModule() module %s already loaded", name);
1619 return mAudioHwDevs.keyAt(i);
1620 }
1621 }
1622
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001623 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001624
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001625 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001626 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001627 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001628 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001629 }
1630
1631 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001632 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001633 mHardwareStatus = AUDIO_HW_IDLE;
1634 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001635 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001636 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001637 }
1638
John Grossmanee578c02012-07-23 17:05:46 -07001639 // Check and cache this HAL's level of support for master mute and master
1640 // volume. If this is the first HAL opened, and it supports the get
1641 // methods, use the initial values provided by the HAL as the current
1642 // master mute and volume settings.
1643
1644 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1645 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001646 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001647
1648 if (0 == mAudioHwDevs.size()) {
1649 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001650 float mv;
1651 if (OK == dev->getMasterVolume(&mv)) {
1652 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001653 }
1654
1655 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001656 bool mm;
1657 if (OK == dev->getMasterMute(&mm)) {
1658 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001659 }
1660 }
1661
Eric Laurenta4c5a552012-03-29 10:12:40 -07001662 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001663 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001664 flags = static_cast<AudioHwDevice::Flags>(flags |
1665 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1666 }
1667
1668 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001669 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001670 flags = static_cast<AudioHwDevice::Flags>(flags |
1671 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1672 }
1673
Eric Laurenta4c5a552012-03-29 10:12:40 -07001674 mHardwareStatus = AUDIO_HW_IDLE;
1675 }
1676
Glenn Kastena13cde92016-03-28 15:26:02 -07001677 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001678 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001679
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001680 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001681
1682 return handle;
1683
1684}
1685
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001686// ----------------------------------------------------------------------------
1687
Glenn Kasten3b16c762012-11-14 08:44:39 -08001688uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001689{
1690 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001691 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001692 return thread != NULL ? thread->sampleRate() : 0;
1693}
1694
Glenn Kastene33054e2012-11-14 12:54:39 -08001695size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001696{
1697 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001698 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001699 return thread != NULL ? thread->frameCountHAL() : 0;
1700}
1701
1702// ----------------------------------------------------------------------------
1703
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001704status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1705{
1706 uid_t uid = IPCThreadState::self()->getCallingUid();
1707 if (uid != AID_SYSTEM) {
1708 return PERMISSION_DENIED;
1709 }
1710 Mutex::Autolock _l(mLock);
1711 if (mIsDeviceTypeKnown) {
1712 return INVALID_OPERATION;
1713 }
1714 mIsLowRamDevice = isLowRamDevice;
1715 mIsDeviceTypeKnown = true;
1716 return NO_ERROR;
1717}
1718
Eric Laurent93c3d412014-08-01 14:48:35 -07001719audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1720{
1721 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001722
1723 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1724 if (index >= 0) {
1725 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1726 mHwAvSyncIds.valueAt(index), sessionId);
1727 return mHwAvSyncIds.valueAt(index);
1728 }
1729
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001730 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001731 if (dev == NULL) {
1732 return AUDIO_HW_SYNC_INVALID;
1733 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001734 String8 reply;
1735 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001736 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001737 param = AudioParameter(reply);
1738 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001739
1740 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001741 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001742 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1743 return AUDIO_HW_SYNC_INVALID;
1744 }
1745
1746 // allow only one session for a given HW A/V sync ID.
1747 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1748 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1749 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1750 value, mHwAvSyncIds.keyAt(i));
1751 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001752 break;
1753 }
1754 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001755
1756 mHwAvSyncIds.add(sessionId, value);
1757
1758 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1759 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1760 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001761 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001762 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001763 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001764 thread->setParameters(param.toString());
1765 break;
1766 }
1767 }
1768
1769 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1770 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001771}
1772
Eric Laurent72e3f392015-05-20 14:43:50 -07001773status_t AudioFlinger::systemReady()
1774{
1775 Mutex::Autolock _l(mLock);
1776 ALOGI("%s", __FUNCTION__);
1777 if (mSystemReady) {
1778 ALOGW("%s called twice", __FUNCTION__);
1779 return NO_ERROR;
1780 }
1781 mSystemReady = true;
1782 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1783 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1784 thread->systemReady();
1785 }
1786 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1787 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1788 thread->systemReady();
1789 }
1790 return NO_ERROR;
1791}
1792
Eric Laurentfa90e842014-10-17 18:12:31 -07001793// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1794void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1795{
1796 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1797 if (index >= 0) {
1798 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1799 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1800 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001801 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001802 thread->setParameters(param.toString());
1803 }
1804}
1805
1806
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001807// ----------------------------------------------------------------------------
1808
Eric Laurent83b88082014-06-20 18:31:16 -07001809
1810sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001811 audio_io_handle_t *output,
1812 audio_config_t *config,
1813 audio_devices_t devices,
1814 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001815 audio_output_flags_t flags)
1816{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001817 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001818 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001819 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001820 }
1821
Eric Laurentcf2c0212014-07-25 16:20:43 -07001822 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001823 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1824 } else {
1825 // Audio Policy does not currently request a specific output handle.
1826 // If this is ever needed, see openInput_l() for example code.
1827 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1828 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001829 }
Eric Laurent83b88082014-06-20 18:31:16 -07001830
1831 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1832
Eric Laurent83b88082014-06-20 18:31:16 -07001833 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001834 // This if statement allows overriding the audio policy settings
1835 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1836 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1837 // Check only for Normal Mixing mode
1838 if (kEnableExtendedPrecision) {
1839 // Specify format (uncomment one below to choose)
1840 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1841 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1842 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1843 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001844 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001845 }
1846 if (kEnableExtendedChannels) {
1847 // Specify channel mask (uncomment one below to choose)
1848 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1849 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1850 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1851 }
Eric Laurent83b88082014-06-20 18:31:16 -07001852 }
1853
Phil Burk062e67a2015-02-11 13:40:50 -08001854 AudioStreamOut *outputStream = NULL;
1855 status_t status = outHwDev->openOutputStream(
1856 &outputStream,
1857 *output,
1858 devices,
1859 flags,
1860 config,
1861 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001862
1863 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001864
Phil Burk062e67a2015-02-11 13:40:50 -08001865 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001866
1867 PlaybackThread *thread;
1868 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001869 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001870 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001871 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1872 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001873 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001874 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001875 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001876 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001877 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001878 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001879 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001880 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001881 return thread;
1882 }
1883
1884 return 0;
1885}
1886
Eric Laurentcf2c0212014-07-25 16:20:43 -07001887status_t AudioFlinger::openOutput(audio_module_handle_t module,
1888 audio_io_handle_t *output,
1889 audio_config_t *config,
1890 audio_devices_t *devices,
1891 const String8& address,
1892 uint32_t *latencyMs,
1893 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894{
Phil Burk062e67a2015-02-11 13:40:50 -08001895 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001896 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001897 (devices != NULL) ? *devices : 0,
1898 config->sample_rate,
1899 config->format,
1900 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001901 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902
Eric Laurentcf2c0212014-07-25 16:20:43 -07001903 if (*devices == AUDIO_DEVICE_NONE) {
1904 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001906
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 Mutex::Autolock _l(mLock);
1908
Eric Laurentcf2c0212014-07-25 16:20:43 -07001909 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001910 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001911 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912
1913 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001914 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001915
1916 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001917 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001918 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001919 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001920
1921 AutoMutex lock(mHardwareLock);
1922 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001923 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001924 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001925 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001926 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 }
1928
Eric Laurentcf2c0212014-07-25 16:20:43 -07001929 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930}
1931
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001932audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1933 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934{
1935 Mutex::Autolock _l(mLock);
1936 MixerThread *thread1 = checkMixerThread_l(output1);
1937 MixerThread *thread2 = checkMixerThread_l(output2);
1938
1939 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001940 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1941 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001942 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 }
1944
Glenn Kasteneeecb982016-02-26 10:44:04 -08001945 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001946 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 thread->addOutputTrack(thread2);
1948 mPlaybackThreads.add(id, thread);
1949 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001950 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 return id;
1952}
1953
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001954status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955{
Glenn Kastend96c5722012-04-25 13:44:49 -07001956 return closeOutput_nonvirtual(output);
1957}
1958
1959status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1960{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 // keep strong reference on the playback thread so that
1962 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001963 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 {
1965 Mutex::Autolock _l(mLock);
1966 thread = checkPlaybackThread_l(output);
1967 if (thread == NULL) {
1968 return BAD_VALUE;
1969 }
1970
Steve Block3856b092011-10-20 11:56:00 +01001971 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001973 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001975 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001976 DuplicatingThread *dupThread =
1977 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001979 }
1980 }
1981 }
1982
1983
1984 mPlaybackThreads.removeItem(output);
1985 // save all effects to the default thread
1986 if (mPlaybackThreads.size()) {
1987 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1988 if (dstThread != NULL) {
1989 // audioflinger lock is held here so the acquisition order of thread locks does not
1990 // matter
1991 Mutex::Autolock _dl(dstThread->mLock);
1992 Mutex::Autolock _sl(thread->mLock);
1993 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1994 for (size_t i = 0; i < effectChains.size(); i ++) {
1995 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 }
1997 }
1998 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001999 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2000 ioDesc->mIoHandle = output;
2001 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 }
2003 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002004 // The thread entity (active unit of execution) is no longer running here,
2005 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006
Eric Laurentf6870ae2015-05-08 10:50:03 -07002007 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002008 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 }
Eric Laurent83b88082014-06-20 18:31:16 -07002010
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 return NO_ERROR;
2012}
2013
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002014void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002015{
2016 AudioStreamOut *out = thread->clearOutput();
2017 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2018 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002019 delete out;
2020}
2021
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002022void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002023{
2024 mPlaybackThreads.removeItem(thread->mId);
2025 thread->exit();
2026 closeOutputFinish(thread);
2027}
2028
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002029status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030{
2031 Mutex::Autolock _l(mLock);
2032 PlaybackThread *thread = checkPlaybackThread_l(output);
2033
2034 if (thread == NULL) {
2035 return BAD_VALUE;
2036 }
2037
Steve Block3856b092011-10-20 11:56:00 +01002038 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 thread->suspend();
2040
2041 return NO_ERROR;
2042}
2043
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002044status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045{
2046 Mutex::Autolock _l(mLock);
2047 PlaybackThread *thread = checkPlaybackThread_l(output);
2048
2049 if (thread == NULL) {
2050 return BAD_VALUE;
2051 }
2052
Steve Block3856b092011-10-20 11:56:00 +01002053 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054
2055 thread->restore();
2056
2057 return NO_ERROR;
2058}
2059
Eric Laurentcf2c0212014-07-25 16:20:43 -07002060status_t AudioFlinger::openInput(audio_module_handle_t module,
2061 audio_io_handle_t *input,
2062 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002063 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002064 const String8& address,
2065 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002066 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067{
Eric Laurent83b88082014-06-20 18:31:16 -07002068 Mutex::Autolock _l(mLock);
2069
Glenn Kastene7d66712015-03-05 13:46:52 -08002070 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002071 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002072 }
2073
Glenn Kastene7d66712015-03-05 13:46:52 -08002074 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002075
2076 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002077 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002078 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002079 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002081 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002082}
Dima Zavin799a70e2011-04-18 16:57:27 -07002083
Eric Laurent83b88082014-06-20 18:31:16 -07002084sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002085 audio_io_handle_t *input,
2086 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002087 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002088 const String8& address,
2089 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002090 audio_input_flags_t flags)
2091{
Glenn Kastene7d66712015-03-05 13:46:52 -08002092 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002093 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002094 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002095 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002096 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002097
Glenn Kasteneeecb982016-02-26 10:44:04 -08002098 // Audio Policy can request a specific handle for hardware hotword.
2099 // The goal here is not to re-open an already opened input.
2100 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002101 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002102 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2103 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2104 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2105 return 0;
2106 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2107 // This should not happen in a transient state with current design.
2108 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2109 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002110 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002111
Eric Laurentcf2c0212014-07-25 16:20:43 -07002112 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002113 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002114 sp<StreamInHalInterface> inStream;
2115 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002116 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002118 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002119 inStream.get(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002120 halconfig.sample_rate,
2121 halconfig.format,
2122 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002123 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002124 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002126 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002127 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002128 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002129 audio_is_linear_pcm(config->format) &&
2130 audio_is_linear_pcm(halconfig.format) &&
2131 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002132 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2133 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002134 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002135 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002136 inStream.clear();
2137 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002138 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002139 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 }
2141
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002142 if (status == NO_ERROR && inStream != 0) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002143
Glenn Kasten46909e72013-02-26 09:20:22 -08002144#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002145 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2146 // or (re-)create if current Pipe is idle and does not match the new format
2147 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002148 enum {
2149 TEE_SINK_NO, // don't copy input
2150 TEE_SINK_NEW, // copy input using a new pipe
2151 TEE_SINK_OLD, // copy input using an existing pipe
2152 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002153 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2154 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002155 if (!mTeeSinkInputEnabled) {
2156 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002157 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002158 kind = TEE_SINK_NO;
2159 } else if (mRecordTeeSink == 0) {
2160 kind = TEE_SINK_NEW;
2161 } else if (mRecordTeeSink->getStrongCount() != 1) {
2162 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002163 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002164 kind = TEE_SINK_OLD;
2165 } else {
2166 kind = TEE_SINK_NEW;
2167 }
2168 switch (kind) {
2169 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002170 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002171 size_t numCounterOffers = 0;
2172 const NBAIO_Format offers[1] = {format};
2173 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2174 ALOG_ASSERT(index == 0);
2175 PipeReader *pipeReader = new PipeReader(*pipe);
2176 numCounterOffers = 0;
2177 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2178 ALOG_ASSERT(index == 0);
2179 mRecordTeeSink = pipe;
2180 mRecordTeeSource = pipeReader;
2181 teeSink = pipe;
2182 }
2183 break;
2184 case TEE_SINK_OLD:
2185 teeSink = mRecordTeeSink;
2186 break;
2187 case TEE_SINK_NO:
2188 default:
2189 break;
2190 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002191#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002192
Eric Laurent05067782016-06-01 18:27:28 -07002193 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002194
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002195 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002196 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002197 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002198 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002199 inputStream,
2200 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002201 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002202 devices,
2203 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002204#ifdef TEE_SINK
2205 , teeSink
2206#endif
2207 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002208 mRecordThreads.add(*input, thread);
2209 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002210 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 }
2212
Eric Laurentcf2c0212014-07-25 16:20:43 -07002213 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 return 0;
2215}
2216
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002217status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218{
Glenn Kastend96c5722012-04-25 13:44:49 -07002219 return closeInput_nonvirtual(input);
2220}
2221
2222status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2223{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 // keep strong reference on the record thread so that
2225 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002226 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 {
2228 Mutex::Autolock _l(mLock);
2229 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002230 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231 return BAD_VALUE;
2232 }
2233
Steve Block3856b092011-10-20 11:56:00 +01002234 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002235
2236 // If we still have effect chains, it means that a client still holds a handle
2237 // on at least one effect. We must either move the chain to an existing thread with the
2238 // same session ID or put it aside in case a new record thread is opened for a
2239 // new capture on the same session
2240 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002241 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002242 Mutex::Autolock _sl(thread->mLock);
2243 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002244 // Note: maximum one chain per record thread
2245 if (effectChains.size() != 0) {
2246 chain = effectChains[0];
2247 }
2248 }
2249 if (chain != 0) {
2250 // first check if a record thread is already opened with a client on the same session.
2251 // This should only happen in case of overlap between one thread tear down and the
2252 // creation of its replacement
2253 size_t i;
2254 for (i = 0; i < mRecordThreads.size(); i++) {
2255 sp<RecordThread> t = mRecordThreads.valueAt(i);
2256 if (t == thread) {
2257 continue;
2258 }
2259 if (t->hasAudioSession(chain->sessionId()) != 0) {
2260 Mutex::Autolock _l(t->mLock);
2261 ALOGV("closeInput() found thread %d for effect session %d",
2262 t->id(), chain->sessionId());
2263 t->addEffectChain_l(chain);
2264 break;
2265 }
2266 }
2267 // put the chain aside if we could not find a record thread with the same session id.
2268 if (i == mRecordThreads.size()) {
2269 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002270 }
2271 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002272 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2273 ioDesc->mIoHandle = input;
2274 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 mRecordThreads.removeItem(input);
2276 }
Eric Laurent83b88082014-06-20 18:31:16 -07002277 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2278 // we have a different lock for notification client
2279 closeInputFinish(thread);
2280 return NO_ERROR;
2281}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002283void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002284{
2285 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002286 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002287 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002288 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002289 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002290}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002292void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002293{
2294 mRecordThreads.removeItem(thread->mId);
2295 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296}
2297
Glenn Kastend2304db2014-02-03 07:40:31 -08002298status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299{
2300 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002301 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302
2303 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2304 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002305 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307
2308 return NO_ERROR;
2309}
2310
2311
Glenn Kasteneeecb982016-02-26 10:44:04 -08002312audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313{
Glenn Kasten9d003132016-04-06 14:38:09 -07002314 // This is a binder API, so a malicious client could pass in a bad parameter.
2315 // Check for that before calling the internal API nextUniqueId().
2316 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2317 ALOGE("newAudioUniqueId invalid use %d", use);
2318 return AUDIO_UNIQUE_ID_ALLOCATE;
2319 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002320 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321}
2322
Glenn Kastend848eb42016-03-08 13:42:11 -08002323void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002324{
2325 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002326 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002327 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2328 if (pid != -1 && (caller == getpid_cached)) {
2329 caller = pid;
2330 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002331
Eric Laurent021cf962014-05-13 10:18:14 -07002332 {
2333 Mutex::Autolock _cl(mClientLock);
2334 // Ignore requests received from processes not known as notification client. The request
2335 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2336 // called from a different pid leaving a stale session reference. Also we don't know how
2337 // to clear this reference if the client process dies.
2338 if (mNotificationClients.indexOfKey(caller) < 0) {
2339 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2340 return;
2341 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002342 }
2343
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002344 size_t num = mAudioSessionRefs.size();
2345 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002346 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002347 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2348 ref->mCnt++;
2349 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002350 return;
2351 }
2352 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002353 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2354 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002355}
2356
Glenn Kastend848eb42016-03-08 13:42:11 -08002357void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002358{
2359 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002360 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002361 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2362 if (pid != -1 && (caller == getpid_cached)) {
2363 caller = pid;
2364 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002365 size_t num = mAudioSessionRefs.size();
2366 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002367 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002368 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2369 ref->mCnt--;
2370 ALOGV(" decremented refcount to %d", ref->mCnt);
2371 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002372 mAudioSessionRefs.removeAt(i);
2373 delete ref;
2374 purgeStaleEffects_l();
2375 }
2376 return;
2377 }
2378 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002379 // If the caller is mediaserver it is likely that the session being released was acquired
2380 // on behalf of a process not in notification clients and we ignore the warning.
2381 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002382}
2383
2384void AudioFlinger::purgeStaleEffects_l() {
2385
Steve Block3856b092011-10-20 11:56:00 +01002386 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002387
2388 Vector< sp<EffectChain> > chains;
2389
2390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2391 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2392 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2393 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002394 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2395 chains.push(ec);
2396 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002397 }
2398 }
2399 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2400 sp<RecordThread> t = mRecordThreads.valueAt(i);
2401 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2402 sp<EffectChain> ec = t->mEffectChains[j];
2403 chains.push(ec);
2404 }
2405 }
2406
2407 for (size_t i = 0; i < chains.size(); i++) {
2408 sp<EffectChain> ec = chains[i];
2409 int sessionid = ec->sessionId();
2410 sp<ThreadBase> t = ec->mThread.promote();
2411 if (t == 0) {
2412 continue;
2413 }
2414 size_t numsessionrefs = mAudioSessionRefs.size();
2415 bool found = false;
2416 for (size_t k = 0; k < numsessionrefs; k++) {
2417 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002418 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002419 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002420 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002421 found = true;
2422 break;
2423 }
2424 }
2425 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002426 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002427 // remove all effects from the chain
2428 while (ec->mEffects.size()) {
2429 sp<EffectModule> effect = ec->mEffects[0];
2430 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002431 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002432 if (effect->purgeHandles()) {
2433 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002434 }
2435 AudioSystem::unregisterEffect(effect->id());
2436 }
2437 }
2438 }
2439 return;
2440}
2441
Glenn Kasteneeecb982016-02-26 10:44:04 -08002442// checkThread_l() must be called with AudioFlinger::mLock held
2443AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2444{
2445 ThreadBase *thread = NULL;
2446 switch (audio_unique_id_get_use(ioHandle)) {
2447 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2448 thread = checkPlaybackThread_l(ioHandle);
2449 break;
2450 case AUDIO_UNIQUE_ID_USE_INPUT:
2451 thread = checkRecordThread_l(ioHandle);
2452 break;
2453 default:
2454 break;
2455 }
2456 return thread;
2457}
2458
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002460AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461{
Glenn Kastena1117922012-01-26 10:53:32 -08002462 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463}
2464
2465// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002466AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467{
2468 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002469 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470}
2471
2472// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002473AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474{
Glenn Kastena1117922012-01-26 10:53:32 -08002475 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476}
2477
Glenn Kasteneeecb982016-02-26 10:44:04 -08002478audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479{
Glenn Kasten9d003132016-04-06 14:38:09 -07002480 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002481 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002482 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2483 for (int retry = 0; retry < maxRetries; retry++) {
2484 // The cast allows wraparound from max positive to min negative instead of abort
2485 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2486 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2487 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2488 // allow wrap by skipping 0 and -1 for session ids
2489 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2490 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2491 return (audio_unique_id_t) (base | use);
2492 }
2493 }
2494 // We have no way of recovering from wraparound
2495 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2496 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497}
2498
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002499AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002500{
2501 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2502 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002503 if(thread->isDuplicating()) {
2504 continue;
2505 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002506 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002507 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002508 return thread;
2509 }
2510 }
2511 return NULL;
2512}
2513
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002514audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002515{
2516 PlaybackThread *thread = primaryPlaybackThread_l();
2517
2518 if (thread == NULL) {
2519 return 0;
2520 }
2521
Eric Laurentf1c04f92012-08-28 14:26:53 -07002522 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002523}
2524
Glenn Kastena7335632016-06-09 17:09:53 -07002525AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2526{
2527 size_t minFrameCount = 0;
2528 PlaybackThread *minThread = NULL;
2529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2530 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2531 if (!thread->isDuplicating()) {
2532 size_t frameCount = thread->frameCountHAL();
2533 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2534 (frameCount == minFrameCount && thread->hasFastMixer() &&
2535 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2536 minFrameCount = frameCount;
2537 minThread = thread;
2538 }
2539 }
2540 }
2541 return minThread;
2542}
2543
Eric Laurenta011e352012-03-29 15:51:43 -07002544sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002545 audio_session_t triggerSession,
2546 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002547 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002548 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002549{
2550 Mutex::Autolock _l(mLock);
2551
2552 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2553 status_t playStatus = NAME_NOT_FOUND;
2554 status_t recStatus = NAME_NOT_FOUND;
2555 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2556 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2557 if (playStatus == NO_ERROR) {
2558 return event;
2559 }
2560 }
2561 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2562 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2563 if (recStatus == NO_ERROR) {
2564 return event;
2565 }
2566 }
2567 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2568 mPendingSyncEvents.add(event);
2569 } else {
2570 ALOGV("createSyncEvent() invalid event %d", event->type());
2571 event.clear();
2572 }
2573 return event;
2574}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002575
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576// ----------------------------------------------------------------------------
2577// Effect management
2578// ----------------------------------------------------------------------------
2579
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002580sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2581 return mEffectsFactoryHal;
2582}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583
Glenn Kastenf587ba52012-01-26 16:25:10 -08002584status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585{
2586 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002587 if (mEffectsFactoryHal.get()) {
2588 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2589 } else {
2590 return -ENODEV;
2591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592}
2593
Glenn Kastenf587ba52012-01-26 16:25:10 -08002594status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595{
2596 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002597 if (mEffectsFactoryHal.get()) {
2598 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2599 } else {
2600 return -ENODEV;
2601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602}
2603
Glenn Kasten5e92a782012-01-30 07:40:52 -08002604status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002605 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606{
2607 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002608 if (mEffectsFactoryHal.get()) {
2609 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2610 } else {
2611 return -ENODEV;
2612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613}
2614
2615
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002616sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 effect_descriptor_t *pDesc,
2618 const sp<IEffectClient>& effectClient,
2619 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002620 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002621 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002622 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 status_t *status,
2624 int *id,
2625 int *enabled)
2626{
2627 status_t lStatus = NO_ERROR;
2628 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002631 pid_t pid = IPCThreadState::self()->getCallingPid();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002632 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2633 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634
2635 if (pDesc == NULL) {
2636 lStatus = BAD_VALUE;
2637 goto Exit;
2638 }
2639
Eric Laurent84e9a102010-09-23 16:10:16 -07002640 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002641 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002642 lStatus = PERMISSION_DENIED;
2643 goto Exit;
2644 }
2645
Dima Zavinfce7a472011-04-19 22:30:36 -07002646 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002647 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002648 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002649 lStatus = PERMISSION_DENIED;
2650 goto Exit;
2651 }
2652
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002654 lStatus = NO_INIT;
2655 goto Exit;
2656 }
2657
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002659 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002661 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002663 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 goto Exit;
2665 }
2666 } else {
2667 // if uuid is not specified, look for an available implementation
2668 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002669 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002670 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 lStatus = BAD_VALUE;
2672 goto Exit;
2673 }
2674 uint32_t numEffects = 0;
2675 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002676 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 bool found = false;
2678
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002679 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002681 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 goto Exit;
2683 }
2684 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002685 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002687 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 continue;
2689 }
2690 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2691 // If matching type found save effect descriptor. If the session is
2692 // 0 and the effect is not auxiliary, continue enumeration in case
2693 // an auxiliary version of this effect type is available
2694 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002695 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002696 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002697 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2698 break;
2699 }
2700 }
2701 }
2702 if (!found) {
2703 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002704 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 goto Exit;
2706 }
2707 // For same effect type, chose auxiliary version over insert version if
2708 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002709 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002711 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 }
2713 }
2714
2715 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002716 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2718 lStatus = INVALID_OPERATION;
2719 goto Exit;
2720 }
2721
Eric Laurent59255e42011-07-27 19:49:51 -07002722 // check recording permission for visualizer
2723 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002724 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002725 lStatus = PERMISSION_DENIED;
2726 goto Exit;
2727 }
2728
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002730 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002731 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002732 // if the output returned by getOutputForEffect() is removed before we lock the
2733 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2734 // and we will exit safely
2735 io = AudioSystem::getOutputForEffect(&desc);
2736 ALOGV("createEffect got output %d", io);
2737 }
2738
2739 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740
2741 // If output is not specified try to find a matching audio session ID in one of the
2742 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002743 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2744 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002745 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002746 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002747 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2748 // output must be specified by AudioPolicyManager when using session
2749 // AUDIO_SESSION_OUTPUT_STAGE
2750 lStatus = BAD_VALUE;
2751 goto Exit;
2752 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002753 // look for the thread where the specified audio session is present
2754 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2755 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2756 io = mPlaybackThreads.keyAt(i);
2757 break;
2758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002760 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002761 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2762 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2763 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002764 break;
2765 }
2766 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002767 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002768 // If no output thread contains the requested session ID, default to
2769 // first output. The effect chain will be moved to the correct output
2770 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002771 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002772 io = mPlaybackThreads.keyAt(0);
2773 }
Steve Block3856b092011-10-20 11:56:00 +01002774 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002775 }
2776 ThreadBase *thread = checkRecordThread_l(io);
2777 if (thread == NULL) {
2778 thread = checkPlaybackThread_l(io);
2779 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002780 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002781 lStatus = BAD_VALUE;
2782 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002783 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002784 } else {
2785 // Check if one effect chain was awaiting for an effect to be created on this
2786 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002787 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002788 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002789 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002790 thread->addEffectChain_l(chain);
2791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002793
Eric Laurent021cf962014-05-13 10:18:14 -07002794 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002796 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002797 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2798 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 if (handle != 0 && id != NULL) {
2800 *id = handle->id();
2801 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002802 if (handle == 0) {
2803 // remove local strong reference to Client with mClientLock held
2804 Mutex::Autolock _cl(mClientLock);
2805 client.clear();
2806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 }
2808
2809Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002810 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 return handle;
2812}
2813
Glenn Kastend848eb42016-03-08 13:42:11 -08002814status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002815 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002816{
Steve Block3856b092011-10-20 11:56:00 +01002817 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002818 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002819 Mutex::Autolock _l(mLock);
2820 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002821 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002822 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 }
Eric Laurentde070132010-07-13 04:45:46 -07002824 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2825 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002826 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002827 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 }
Eric Laurentde070132010-07-13 04:45:46 -07002829 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2830 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002831 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002832 return BAD_VALUE;
2833 }
2834
2835 Mutex::Autolock _dl(dstThread->mLock);
2836 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002837 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838}
2839
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002840// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002841status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002842 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002843 AudioFlinger::PlaybackThread *dstThread,
2844 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002845{
Steve Block3856b092011-10-20 11:56:00 +01002846 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002847 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002848
Eric Laurent59255e42011-07-27 19:49:51 -07002849 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002850 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002851 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002852 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002853 return INVALID_OPERATION;
2854 }
2855
Eric Laurent4c415062016-06-17 16:14:16 -07002856 // Check whether the destination thread and all effects in the chain are compatible
2857 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002858 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002859 " destination thread %p is not compatible with effects in the chain",
2860 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002861 return INVALID_OPERATION;
2862 }
2863
Eric Laurent39e94f82010-07-28 01:32:47 -07002864 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002865 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002866 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002867 // removed.
2868 srcThread->removeEffectChain_l(chain);
2869
2870 // transfer all effects one by one so that new effect chain is created on new thread with
2871 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002872 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002873 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002874 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002875 Vector< sp<EffectModule> > removed;
2876 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002877 while (effect != 0) {
2878 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002879 removed.add(effect);
2880 status = dstThread->addEffect_l(effect);
2881 if (status != NO_ERROR) {
2882 break;
2883 }
Eric Laurentec35a142011-10-05 17:42:25 -07002884 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2885 if (effect->state() == EffectModule::ACTIVE ||
2886 effect->state() == EffectModule::STOPPING) {
2887 effect->start();
2888 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002889 // if the move request is not received from audio policy manager, the effect must be
2890 // re-registered with the new strategy and output
2891 if (dstChain == 0) {
2892 dstChain = effect->chain().promote();
2893 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002894 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002895 status = NO_INIT;
2896 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002897 }
2898 strategy = dstChain->strategy();
2899 }
2900 if (reRegister) {
2901 AudioSystem::unregisterEffect(effect->id());
2902 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002903 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002904 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002905 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002906 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002907 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002908 }
Eric Laurentde070132010-07-13 04:45:46 -07002909 effect = chain->getEffectFromId_l(0);
2910 }
2911
Eric Laurent5baf2af2013-09-12 17:37:00 -07002912 if (status != NO_ERROR) {
2913 for (size_t i = 0; i < removed.size(); i++) {
2914 srcThread->addEffect_l(removed[i]);
2915 if (dstChain != 0 && reRegister) {
2916 AudioSystem::unregisterEffect(removed[i]->id());
2917 AudioSystem::registerEffect(&removed[i]->desc(),
2918 srcThread->id(),
2919 strategy,
2920 sessionId,
2921 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002922 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002923 }
2924 }
2925 }
2926
2927 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928}
2929
Eric Laurent5baf2af2013-09-12 17:37:00 -07002930bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002931{
2932 if (mGlobalEffectEnableTime != 0 &&
2933 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2934 return true;
2935 }
2936
2937 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2938 sp<EffectChain> ec =
2939 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002940 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002941 return true;
2942 }
2943 }
2944 return false;
2945}
2946
Eric Laurent5baf2af2013-09-12 17:37:00 -07002947void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002948{
2949 Mutex::Autolock _l(mLock);
2950
2951 mGlobalEffectEnableTime = systemTime();
2952
2953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2954 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2955 if (t->mType == ThreadBase::OFFLOAD) {
2956 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2957 }
2958 }
2959
2960}
2961
Eric Laurentaaa44472014-09-12 17:41:50 -07002962status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2963{
Glenn Kastend848eb42016-03-08 13:42:11 -08002964 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002965 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002966 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002967 if (index >= 0) {
2968 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2969 return ALREADY_EXISTS;
2970 }
2971 mOrphanEffectChains.add(session, chain);
2972 return NO_ERROR;
2973}
2974
2975sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2976{
2977 sp<EffectChain> chain;
2978 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002979 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002980 if (index >= 0) {
2981 chain = mOrphanEffectChains.valueAt(index);
2982 mOrphanEffectChains.removeItemsAt(index);
2983 }
2984 return chain;
2985}
2986
2987bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2988{
2989 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002990 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002991 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002992 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002993 if (index >= 0) {
2994 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2995 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002996 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002997 mOrphanEffectChains.removeItemsAt(index);
2998 }
2999 return true;
3000 }
3001 return false;
3002}
3003
3004
Glenn Kastenda6ef132013-01-10 12:31:01 -08003005struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003006#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3007 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003008};
3009
3010int comparEntry(const void *p1, const void *p2)
3011{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003012 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003013}
3014
Glenn Kasten46909e72013-02-26 09:20:22 -08003015#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003016void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017{
Eric Laurent81784c32012-11-19 14:55:58 -08003018 NBAIO_Source *teeSource = source.get();
3019 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003020 // .wav rotation
3021 // There is a benign race condition if 2 threads call this simultaneously.
3022 // They would both traverse the directory, but the result would simply be
3023 // failures at unlink() which are ignored. It's also unlikely since
3024 // normally dumpsys is only done by bugreport or from the command line.
3025 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003026 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003027 size_t teePathLen = strlen(teePath);
3028 DIR *dir = opendir(teePath);
3029 teePath[teePathLen++] = '/';
3030 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003031#define TEE_MAX_SORT 20 // number of entries to sort
3032#define TEE_MAX_KEEP 10 // number of entries to keep
3033 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003034 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003035 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003036 struct dirent de;
3037 struct dirent *result = NULL;
3038 int rc = readdir_r(dir, &de, &result);
3039 if (rc != 0) {
3040 ALOGW("readdir_r failed %d", rc);
3041 break;
3042 }
3043 if (result == NULL) {
3044 break;
3045 }
3046 if (result != &de) {
3047 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3048 break;
3049 }
3050 // ignore non .wav file entries
3051 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003052 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003053 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3054 continue;
3055 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003056 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003057 }
3058 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003059 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003060 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003061 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3062 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003063 (void) unlink(teePath);
3064 }
3065 }
3066 } else {
3067 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003068 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003069 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003070 }
3071 }
Eric Laurent81784c32012-11-19 14:55:58 -08003072 char teeTime[16];
3073 struct timeval tv;
3074 gettimeofday(&tv, NULL);
3075 struct tm tm;
3076 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003077 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3078 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3079 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3080 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003081 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003082 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003083 char wavHeader[44];
3084 memcpy(wavHeader,
3085 "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",
3086 sizeof(wavHeader));
3087 NBAIO_Format format = teeSource->format();
3088 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003089 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003090 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003091 wavHeader[22] = channelCount; // number of channels
3092 wavHeader[24] = sampleRate; // sample rate
3093 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003094 wavHeader[32] = frameSize; // block alignment
3095 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003096 write(teeFd, wavHeader, sizeof(wavHeader));
3097 size_t total = 0;
3098 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003099#define TEE_SINK_READ 1024 // frames per I/O operation
3100 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003101 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003102 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003103 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003104 bool wasFirstRead = firstRead;
3105 firstRead = false;
3106 if (actual <= 0) {
3107 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3108 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003109 }
Eric Laurent81784c32012-11-19 14:55:58 -08003110 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003111 }
Eric Laurent81784c32012-11-19 14:55:58 -08003112 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003113 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003114 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003115 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003116 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003117 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003118 uint32_t temp = 44 + total * frameSize - 8;
3119 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003120 write(teeFd, &temp, sizeof(temp));
3121 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003122 temp = total * frameSize;
3123 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003124 write(teeFd, &temp, sizeof(temp));
3125 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003126 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003127 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003128 }
Eric Laurent59255e42011-07-27 19:49:51 -07003129 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003130 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003131 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003132 }
Eric Laurent59255e42011-07-27 19:49:51 -07003133 }
3134 }
3135}
Glenn Kasten46909e72013-02-26 09:20:22 -08003136#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003137
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138// ----------------------------------------------------------------------------
3139
3140status_t AudioFlinger::onTransact(
3141 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3142{
3143 return BnAudioFlinger::onTransact(code, data, reply, flags);
3144}
3145
Glenn Kasten63238ef2015-03-02 15:50:29 -08003146} // namespace android