blob: 0e61e76f895bfb7cd04e813f191110206e9c00e9 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070034#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080047#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Andy Hung6770c6f2015-04-07 13:43:36 -070049#include <media/AudioResamplerPublic.h>
50
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070052#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070053#include <audio_effects/effect_ns.h>
54#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Glenn Kasten3b21c502011-12-15 09:52:39 -080056#include <audio_utils/primitives.h>
57
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080059
Glenn Kasten9e58b552013-01-18 15:09:48 -080060#include <media/IMediaLogService.h>
61
Glenn Kastenda6ef132013-01-10 12:31:01 -080062#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070064#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070066#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080067
Mathias Agopian65ab4712010-07-14 17:59:35 -070068// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
John Grossman1c345192012-03-27 14:00:17 -070070// Note: the following macro is used for extremely verbose logging message. In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well. Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on. Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
Eric Laurentde070132010-07-13 04:45:46 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Glenn Kastenec1d6b52011-12-12 09:04:45 -080085static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
86static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070087static const char kClientLockedString[] = "Client lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Glenn Kasten58912562012-04-03 10:45:00 -070089
John Grossman4ff14ba2012-02-08 16:37:41 -080090nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080091
Eric Laurent81784c32012-11-19 14:55:58 -080092uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070093
Glenn Kasten46909e72013-02-26 09:20:22 -080094#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080095bool AudioFlinger::mTeeSinkInputEnabled = false;
96bool AudioFlinger::mTeeSinkOutputEnabled = false;
97bool AudioFlinger::mTeeSinkTrackEnabled = false;
98
99size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
100size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
101size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109
Marco Nelissenb2208842014-02-07 14:00:50 -0800110const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800111 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530112 case AUDIO_FORMAT_PCM:
113 switch (format) {
114 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
115 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
116 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
117 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
118 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
119 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
120 default:
121 break;
122 }
123 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800124 case AUDIO_FORMAT_MP3: return "mp3";
125 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
126 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
127 case AUDIO_FORMAT_AAC: return "aac";
128 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
129 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
130 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530131 case AUDIO_FORMAT_OPUS: return "opus";
132 case AUDIO_FORMAT_AC3: return "ac-3";
133 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800134 case AUDIO_FORMAT_IEC61937: return "iec61937";
Marco Nelissenb2208842014-02-07 14:00:50 -0800135 default:
136 break;
137 }
138 return "unknown";
139}
140
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700141static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700142{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700143 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700144 int rc;
145
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700146 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
147 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
148 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
149 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700150 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700151 }
152 rc = audio_hw_device_open(mod, dev);
153 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
154 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
155 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700157 }
Eric Laurent5806b352014-05-22 12:23:26 -0700158 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700159 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
160 rc = BAD_VALUE;
161 goto out;
162 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 return 0;
164
165out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 *dev = NULL;
167 return rc;
168}
169
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170// ----------------------------------------------------------------------------
171
172AudioFlinger::AudioFlinger()
173 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800175 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700176 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700179 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800180 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700181 mBtNrecIsOff(false),
182 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700183 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700184 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700185 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700187 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
188 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
189 // zero ID has a special meaning, so unavailable
190 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
191 }
192
Glenn Kasten949a9262013-04-16 12:35:20 -0700193 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800194 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800195 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800196 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
197 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800198 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700199
Wei Jia3f273d12015-11-24 09:06:49 -0800200 // reset battery stats.
201 // if the audio service has crashed, battery stats could be left
202 // in bad state, reset the state upon service start.
203 BatteryNotifier::getInstance().noteResetAudio();
204
Glenn Kasten46909e72013-02-26 09:20:22 -0800205#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800206 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800207 (void) property_get("ro.debuggable", value, "0");
208 int debuggable = atoi(value);
209 int teeEnabled = 0;
210 if (debuggable) {
211 (void) property_get("af.tee", value, "0");
212 teeEnabled = atoi(value);
213 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800214 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700215 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800216 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700217 }
218 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800219 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700220 }
221 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800222 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700223 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800224#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700225}
226
227void AudioFlinger::onFirstRef()
228{
Eric Laurent93575202011-01-18 18:39:02 -0800229 Mutex::Autolock _l(mLock);
230
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800232 char val_str[PROPERTY_VALUE_MAX] = { 0 };
233 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
234 uint32_t int_val;
235 if (1 == sscanf(val_str, "%u", &int_val)) {
236 mStandbyTimeInNsecs = milliseconds(int_val);
237 ALOGI("Using %u mSec as standby time.", int_val);
238 } else {
239 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
240 ALOGI("Using default %u mSec as standby time.",
241 (uint32_t)(mStandbyTimeInNsecs / 1000000));
242 }
243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244
Eric Laurent1c333e22014-05-20 10:48:17 -0700245 mPatchPanel = new PatchPanel(this);
246
Eric Laurenta4c5a552012-03-29 10:12:40 -0700247 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248}
249
250AudioFlinger::~AudioFlinger()
251{
252 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700253 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700254 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 }
256 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700257 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700258 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700260
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800261 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
262 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700263 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
264 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700266
267 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800268 if (mLogMemoryDealer != 0) {
269 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
270 if (binder != 0) {
271 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
272 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
273 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
274 mUnregisteredWriters.pop();
275 mediaLogService->unregisterWriter(iMemory);
276 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700277 }
278 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279}
280
Eric Laurenta4c5a552012-03-29 10:12:40 -0700281static const char * const audio_interfaces[] = {
282 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
283 AUDIO_HARDWARE_MODULE_ID_A2DP,
284 AUDIO_HARDWARE_MODULE_ID_USB,
285};
286#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
287
Phil Burk062e67a2015-02-11 13:40:50 -0800288AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700289 audio_module_handle_t module,
290 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700291{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700292 // if module is 0, the request comes from an old policy manager and we should load
293 // well known modules
294 if (module == 0) {
295 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
296 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
297 loadHwModule_l(audio_interfaces[i]);
298 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700299 // then try to find a module supporting the requested device.
300 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
301 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
302 audio_hw_device_t *dev = audioHwDevice->hwDevice();
303 if ((dev->get_supported_devices != NULL) &&
304 (dev->get_supported_devices(dev) & devices) == devices)
305 return audioHwDevice;
306 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 } else {
308 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700309 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
310 if (audioHwDevice != NULL) {
311 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700312 }
313 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700314
Dima Zavin799a70e2011-04-18 16:57:27 -0700315 return NULL;
316}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700317
Glenn Kasten0f11b512014-01-31 16:18:54 -0800318void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319{
320 const size_t SIZE = 256;
321 char buffer[SIZE];
322 String8 result;
323
324 result.append("Clients:\n");
325 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800326 sp<Client> client = mClients.valueAt(i).promote();
327 if (client != 0) {
328 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
329 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330 }
331 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700332
Eric Laurentd1b28d42013-09-18 18:47:13 -0700333 result.append("Notification Clients:\n");
334 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
335 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
336 result.append(buffer);
337 }
338
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700339 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800340 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700341 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
342 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800343 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700344 result.append(buffer);
345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347}
348
349
Glenn Kasten0f11b512014-01-31 16:18:54 -0800350void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351{
352 const size_t SIZE = 256;
353 char buffer[SIZE];
354 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800355 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700356
John Grossman4ff14ba2012-02-08 16:37:41 -0800357 snprintf(buffer, SIZE, "Hardware status: %d\n"
358 "Standby Time mSec: %u\n",
359 hardwareStatus,
360 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 result.append(buffer);
362 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363}
364
Glenn Kasten0f11b512014-01-31 16:18:54 -0800365void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366{
367 const size_t SIZE = 256;
368 char buffer[SIZE];
369 String8 result;
370 snprintf(buffer, SIZE, "Permission Denial: "
371 "can't dump AudioFlinger from pid=%d, uid=%d\n",
372 IPCThreadState::self()->getCallingPid(),
373 IPCThreadState::self()->getCallingUid());
374 result.append(buffer);
375 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376}
377
Eric Laurent81784c32012-11-19 14:55:58 -0800378bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379{
380 bool locked = false;
381 for (int i = 0; i < kDumpLockRetries; ++i) {
382 if (mutex.tryLock() == NO_ERROR) {
383 locked = true;
384 break;
385 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800386 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 }
388 return locked;
389}
390
391status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
392{
Glenn Kasten44deb052012-02-05 18:09:08 -0800393 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394 dumpPermissionDenial(fd, args);
395 } else {
396 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800397 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700398 if (!hardwareLocked) {
399 String8 result(kHardwareLockedString);
400 write(fd, result.string(), result.size());
401 } else {
402 mHardwareLock.unlock();
403 }
404
Eric Laurent81784c32012-11-19 14:55:58 -0800405 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700406
407 // failed to lock - AudioFlinger is probably deadlocked
408 if (!locked) {
409 String8 result(kDeadlockedString);
410 write(fd, result.string(), result.size());
411 }
412
Eric Laurent021cf962014-05-13 10:18:14 -0700413 bool clientLocked = dumpTryLock(mClientLock);
414 if (!clientLocked) {
415 String8 result(kClientLockedString);
416 write(fd, result.string(), result.size());
417 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700418
419 EffectDumpEffects(fd);
420
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700422 if (clientLocked) {
423 mClientLock.unlock();
424 }
425
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 dumpInternals(fd, args);
427
428 // dump playback threads
429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
430 mPlaybackThreads.valueAt(i)->dump(fd, args);
431 }
432
433 // dump record threads
434 for (size_t i = 0; i < mRecordThreads.size(); i++) {
435 mRecordThreads.valueAt(i)->dump(fd, args);
436 }
437
Eric Laurentaaa44472014-09-12 17:41:50 -0700438 // dump orphan effect chains
439 if (mOrphanEffectChains.size() != 0) {
440 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
441 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
442 mOrphanEffectChains.valueAt(i)->dump(fd, args);
443 }
444 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700445 // dump all hardware devs
446 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700447 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700448 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700450
Glenn Kasten46909e72013-02-26 09:20:22 -0800451#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700452 // dump the serially shared record tee sink
453 if (mRecordTeeSource != 0) {
454 dumpTee(fd, mRecordTeeSource);
455 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800456#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700457
Glenn Kastend65d73c2012-06-22 17:21:07 -0700458 if (locked) {
459 mLock.unlock();
460 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800461
462 // append a copy of media.log here by forwarding fd to it, but don't attempt
463 // to lookup the service if it's not running, as it will block for a second
464 if (mLogMemoryDealer != 0) {
465 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
466 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700467 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800468 Vector<String16> args;
469 binder->dump(fd, args);
470 }
471 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700472
473 // check for optional arguments
474 bool unreachableMemory = false;
475 for (const auto &arg : args) {
476 if (arg == String16("--unreachable")) {
477 unreachableMemory = true;
478 }
479 }
480
481 if (unreachableMemory) {
482 dprintf(fd, "\nDumping unreachable memory:\n");
483 // TODO - should limit be an argument parameter?
484 std::string s = GetUnreachableMemoryString(true /* contents */, 10000 /* limit */);
485 write(fd, s.c_str(), s.size());
486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 }
488 return NO_ERROR;
489}
490
Eric Laurent021cf962014-05-13 10:18:14 -0700491sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800492{
Eric Laurent021cf962014-05-13 10:18:14 -0700493 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800494 // If pid is already in the mClients wp<> map, then use that entry
495 // (for which promote() is always != 0), otherwise create a new entry and Client.
496 sp<Client> client = mClients.valueFor(pid).promote();
497 if (client == 0) {
498 client = new Client(this, pid);
499 mClients.add(pid, client);
500 }
501
502 return client;
503}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504
Glenn Kasten9e58b552013-01-18 15:09:48 -0800505sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
506{
Glenn Kasten481fb672013-09-30 14:39:28 -0700507 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800508 if (mLogMemoryDealer == 0) {
509 return new NBLog::Writer();
510 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800511 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700512 // Similarly if we can't contact the media.log service, also return a dummy writer
513 if (binder == 0) {
514 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800515 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700516 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
517 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
518 // If allocation fails, consult the vector of previously unregistered writers
519 // and garbage-collect one or more them until an allocation succeeds
520 if (shared == 0) {
521 Mutex::Autolock _l(mUnregisteredWritersLock);
522 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
523 {
524 // Pick the oldest stale writer to garbage-collect
525 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
526 mUnregisteredWriters.removeAt(0);
527 mediaLogService->unregisterWriter(iMemory);
528 // Now the media.log remote reference to IMemory is gone. When our last local
529 // reference to IMemory also drops to zero at end of this block,
530 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
531 }
532 // Re-attempt the allocation
533 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
534 if (shared != 0) {
535 goto success;
536 }
537 }
538 // Even after garbage-collecting all old writers, there is still not enough memory,
539 // so return a dummy writer
540 return new NBLog::Writer();
541 }
542success:
543 mediaLogService->registerWriter(shared, size, name);
544 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800545}
546
547void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
548{
Glenn Kasten685ef092013-02-04 08:15:34 -0800549 if (writer == 0) {
550 return;
551 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800552 sp<IMemory> iMemory(writer->getIMemory());
553 if (iMemory == 0) {
554 return;
555 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700556 // Rather than removing the writer immediately, append it to a queue of old writers to
557 // be garbage-collected later. This allows us to continue to view old logs for a while.
558 Mutex::Autolock _l(mUnregisteredWritersLock);
559 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800560}
561
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562// IAudioFlinger interface
563
564
565sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800566 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800568 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700569 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800570 size_t *frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800571 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800573 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700574 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800575 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800576 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800577 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 status_t *status)
579{
580 sp<PlaybackThread::Track> track;
581 sp<TrackHandle> trackHandle;
582 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800584 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700586 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
587 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
588 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
589 ALOGW_IF(pid != -1 && pid != callingPid,
590 "%s uid %d pid %d tried to pass itself off as pid %d",
591 __func__, callingUid, callingPid, pid);
592 pid = callingPid;
593 }
594
Glenn Kasten263709e2012-01-06 08:40:01 -0800595 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
596 // but if someone uses binder directly they could bypass that and cause us to crash
597 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000598 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 lStatus = BAD_VALUE;
600 goto Exit;
601 }
602
Glenn Kasten53b5d092014-02-05 10:00:23 -0800603 // further sample rate checks are performed by createTrack_l() depending on the thread type
604 if (sampleRate == 0) {
605 ALOGE("createTrack() invalid sample rate %u", sampleRate);
606 lStatus = BAD_VALUE;
607 goto Exit;
608 }
609
610 // further channel mask checks are performed by createTrack_l() depending on the thread type
611 if (!audio_is_output_channel(channelMask)) {
612 ALOGE("createTrack() invalid channel mask %#x", channelMask);
613 lStatus = BAD_VALUE;
614 goto Exit;
615 }
616
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700617 // further format checks are performed by createTrack_l() depending on the thread type
618 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800619 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700620 lStatus = BAD_VALUE;
621 goto Exit;
622 }
623
Glenn Kasten663c2242013-09-24 11:52:37 -0700624 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
625 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
626 lStatus = BAD_VALUE;
627 goto Exit;
628 }
629
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 {
631 Mutex::Autolock _l(mLock);
632 PlaybackThread *thread = checkPlaybackThread_l(output);
633 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800634 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 lStatus = BAD_VALUE;
636 goto Exit;
637 }
638
Eric Laurent021cf962014-05-13 10:18:14 -0700639 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640
Glenn Kastene848bd92014-03-13 15:00:32 -0700641 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700642 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800643 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
644 ALOGE("createTrack() invalid session ID %d", *sessionId);
645 lStatus = BAD_VALUE;
646 goto Exit;
647 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700648 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700649 // check if an effect chain with the same session ID is present on another
650 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700651 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700652 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
653 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700654 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700655 if (sessions & PlaybackThread::EFFECT_SESSION) {
656 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700657 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700658 }
Eric Laurentde070132010-07-13 04:45:46 -0700659 }
660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700662 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800663 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 if (sessionId != NULL) {
665 *sessionId = lSessionId;
666 }
667 }
Steve Block3856b092011-10-20 11:56:00 +0100668 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669
670 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800671 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800672 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700673 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700674
675 // move effect chain to this output thread if an effect on same session was waiting
676 // for a track to be created
677 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700678 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700679 Mutex::Autolock _dl(thread->mLock);
680 Mutex::Autolock _sl(effectThread->mLock);
681 moveEffectChain_l(lSessionId, effectThread, thread, true);
682 }
Eric Laurenta011e352012-03-29 15:51:43 -0700683
684 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700685 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700686 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
687 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700688 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700689 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700690 } else {
691 mPendingSyncEvents[i]->cancel();
692 }
Eric Laurenta011e352012-03-29 15:51:43 -0700693 mPendingSyncEvents.removeAt(i);
694 i--;
695 }
696 }
697 }
Glenn Kastene198c362013-08-13 09:13:36 -0700698
Glenn Kastend848eb42016-03-08 13:42:11 -0800699 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700 }
Glenn Kastene198c362013-08-13 09:13:36 -0700701
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700702 if (lStatus != NO_ERROR) {
703 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700704 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700705 // Don't hold mClientLock when releasing the reference on the track as the
706 // destructor will acquire it.
707 {
708 Mutex::Autolock _cl(mClientLock);
709 client.clear();
710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700712 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713 }
714
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700715 // return handle to client
716 trackHandle = new TrackHandle(track);
717
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700719 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 return trackHandle;
721}
722
Glenn Kasten2c073da2016-02-26 09:14:08 -0800723uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724{
725 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800726 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700727 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800728 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 return 0;
730 }
731 return thread->sampleRate();
732}
733
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800734audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
736 Mutex::Autolock _l(mLock);
737 PlaybackThread *thread = checkPlaybackThread_l(output);
738 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000739 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800740 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741 }
742 return thread->format();
743}
744
Glenn Kasten2c073da2016-02-26 09:14:08 -0800745size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746{
747 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800748 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800750 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 return 0;
752 }
Glenn Kasten58912562012-04-03 10:45:00 -0700753 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
754 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 return thread->frameCount();
756}
757
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700758size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
759{
760 Mutex::Autolock _l(mLock);
761 ThreadBase *thread = checkThread_l(ioHandle);
762 if (thread == NULL) {
763 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
764 return 0;
765 }
766 return thread->frameCountHAL();
767}
768
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800769uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770{
771 Mutex::Autolock _l(mLock);
772 PlaybackThread *thread = checkPlaybackThread_l(output);
773 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800774 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700775 return 0;
776 }
777 return thread->latency();
778}
779
780status_t AudioFlinger::setMasterVolume(float value)
781{
Eric Laurenta1884f92011-08-23 08:25:03 -0700782 status_t ret = initCheck();
783 if (ret != NO_ERROR) {
784 return ret;
785 }
786
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 // check calling permissions
788 if (!settingsAllowed()) {
789 return PERMISSION_DENIED;
790 }
791
Eric Laurenta4c5a552012-03-29 10:12:40 -0700792 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700793 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700794
John Grossmanee578c02012-07-23 17:05:46 -0700795 // Set master volume in the HALs which support it.
796 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
797 AutoMutex lock(mHardwareLock);
798 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800799
John Grossmanee578c02012-07-23 17:05:46 -0700800 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
801 if (dev->canSetMasterVolume()) {
802 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800803 }
John Grossmanee578c02012-07-23 17:05:46 -0700804 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806
John Grossmanee578c02012-07-23 17:05:46 -0700807 // Now set the master volume in each playback thread. Playback threads
808 // assigned to HALs which do not have master volume support will apply
809 // master volume during the mix operation. Threads with HALs which do
810 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700811 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
812 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
813 continue;
814 }
John Grossmanee578c02012-07-23 17:05:46 -0700815 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817
818 return NO_ERROR;
819}
820
Glenn Kastenf78aee72012-01-04 11:00:47 -0800821status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822{
Eric Laurenta1884f92011-08-23 08:25:03 -0700823 status_t ret = initCheck();
824 if (ret != NO_ERROR) {
825 return ret;
826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827
828 // check calling permissions
829 if (!settingsAllowed()) {
830 return PERMISSION_DENIED;
831 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800832 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000833 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 return BAD_VALUE;
835 }
836
837 { // scope for the lock
838 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700839 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700841 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 mHardwareStatus = AUDIO_HW_IDLE;
843 }
844
845 if (NO_ERROR == ret) {
846 Mutex::Autolock _l(mLock);
847 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800848 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700849 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 }
851
852 return ret;
853}
854
855status_t AudioFlinger::setMicMute(bool state)
856{
Eric Laurenta1884f92011-08-23 08:25:03 -0700857 status_t ret = initCheck();
858 if (ret != NO_ERROR) {
859 return ret;
860 }
861
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862 // check calling permissions
863 if (!settingsAllowed()) {
864 return PERMISSION_DENIED;
865 }
866
867 AutoMutex lock(mHardwareLock);
868 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700869 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
870 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
871 status_t result = dev->set_mic_mute(dev, state);
872 if (result != NO_ERROR) {
873 ret = result;
874 }
875 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876 mHardwareStatus = AUDIO_HW_IDLE;
877 return ret;
878}
879
880bool AudioFlinger::getMicMute() const
881{
Eric Laurenta1884f92011-08-23 08:25:03 -0700882 status_t ret = initCheck();
883 if (ret != NO_ERROR) {
884 return false;
885 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800886 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700887 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800888 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800890 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
891 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
892 status_t result = dev->get_mic_mute(dev, &state);
893 if (result == NO_ERROR) {
894 mute = mute && state;
895 }
896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800898
899 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900}
901
902status_t AudioFlinger::setMasterMute(bool muted)
903{
John Grossmand8f178d2012-07-20 14:51:35 -0700904 status_t ret = initCheck();
905 if (ret != NO_ERROR) {
906 return ret;
907 }
908
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909 // check calling permissions
910 if (!settingsAllowed()) {
911 return PERMISSION_DENIED;
912 }
913
John Grossmanee578c02012-07-23 17:05:46 -0700914 Mutex::Autolock _l(mLock);
915 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700916
John Grossmanee578c02012-07-23 17:05:46 -0700917 // Set master mute in the HALs which support it.
918 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
919 AutoMutex lock(mHardwareLock);
920 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700921
John Grossmanee578c02012-07-23 17:05:46 -0700922 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
923 if (dev->canSetMasterMute()) {
924 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700925 }
John Grossmanee578c02012-07-23 17:05:46 -0700926 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700927 }
928
John Grossmanee578c02012-07-23 17:05:46 -0700929 // Now set the master mute in each playback thread. Playback threads
930 // assigned to HALs which do not have master mute support will apply master
931 // mute during the mix operation. Threads with HALs which do support master
932 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700933 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
934 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
935 continue;
936 }
John Grossmanee578c02012-07-23 17:05:46 -0700937 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939
940 return NO_ERROR;
941}
942
943float AudioFlinger::masterVolume() const
944{
Glenn Kasten98067102011-12-13 11:47:54 -0800945 Mutex::Autolock _l(mLock);
946 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947}
948
949bool AudioFlinger::masterMute() const
950{
Glenn Kasten98067102011-12-13 11:47:54 -0800951 Mutex::Autolock _l(mLock);
952 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953}
954
John Grossman4ff14ba2012-02-08 16:37:41 -0800955float AudioFlinger::masterVolume_l() const
956{
John Grossman4ff14ba2012-02-08 16:37:41 -0800957 return mMasterVolume;
958}
959
John Grossmand8f178d2012-07-20 14:51:35 -0700960bool AudioFlinger::masterMute_l() const
961{
John Grossmanee578c02012-07-23 17:05:46 -0700962 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700963}
964
Eric Laurent223fd5c2014-11-11 13:43:36 -0800965status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
966{
967 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
968 ALOGW("setStreamVolume() invalid stream %d", stream);
969 return BAD_VALUE;
970 }
971 pid_t caller = IPCThreadState::self()->getCallingPid();
972 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
973 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
974 return PERMISSION_DENIED;
975 }
976
977 return NO_ERROR;
978}
979
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800980status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
981 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982{
983 // check calling permissions
984 if (!settingsAllowed()) {
985 return PERMISSION_DENIED;
986 }
987
Eric Laurent223fd5c2014-11-11 13:43:36 -0800988 status_t status = checkStreamType(stream);
989 if (status != NO_ERROR) {
990 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800992 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993
994 AutoMutex lock(mLock);
995 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700996 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 thread = checkPlaybackThread_l(output);
998 if (thread == NULL) {
999 return BAD_VALUE;
1000 }
1001 }
1002
1003 mStreamTypes[stream].volume = value;
1004
1005 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001006 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001007 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 }
1009 } else {
1010 thread->setStreamVolume(stream, value);
1011 }
1012
1013 return NO_ERROR;
1014}
1015
Glenn Kastenfff6d712012-01-12 16:38:12 -08001016status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017{
1018 // check calling permissions
1019 if (!settingsAllowed()) {
1020 return PERMISSION_DENIED;
1021 }
1022
Eric Laurent223fd5c2014-11-11 13:43:36 -08001023 status_t status = checkStreamType(stream);
1024 if (status != NO_ERROR) {
1025 return status;
1026 }
1027 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1028
1029 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001030 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 return BAD_VALUE;
1032 }
1033
Eric Laurent93575202011-01-18 18:39:02 -08001034 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001036 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001037 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038
1039 return NO_ERROR;
1040}
1041
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001042float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001044 status_t status = checkStreamType(stream);
1045 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 return 0.0f;
1047 }
1048
1049 AutoMutex lock(mLock);
1050 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001051 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 PlaybackThread *thread = checkPlaybackThread_l(output);
1053 if (thread == NULL) {
1054 return 0.0f;
1055 }
1056 volume = thread->streamVolume(stream);
1057 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001058 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059 }
1060
1061 return volume;
1062}
1063
Glenn Kastenfff6d712012-01-12 16:38:12 -08001064bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001066 status_t status = checkStreamType(stream);
1067 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 return true;
1069 }
1070
Glenn Kasten6637baa2012-01-09 09:40:36 -08001071 AutoMutex lock(mLock);
1072 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073}
1074
Eric Laurent054d9d32015-04-24 08:48:48 -07001075
1076void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1077{
1078 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1079 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1080 }
1081}
1082
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001083status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001085 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1086 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001087
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088 // check calling permissions
1089 if (!settingsAllowed()) {
1090 return PERMISSION_DENIED;
1091 }
1092
Glenn Kasten142f5192014-03-25 17:44:59 -07001093 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1094 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001095 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001096 status_t final_result = NO_ERROR;
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++) {
1101 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1102 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1103 final_result = result ?: final_result;
1104 }
1105 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001106 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001107 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1108 AudioParameter param = AudioParameter(keyValuePairs);
1109 String8 value;
1110 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001111 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1112 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001113 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1114 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001115 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001116 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1117 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001118 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001119 // suspend effects associated with those session IDs
1120 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001121 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001122 thread->setEffectSuspended(FX_IID_AEC,
1123 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001124 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001125 thread->setEffectSuspended(FX_IID_NS,
1126 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001127 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001128 }
1129 }
Eric Laurentbee53372011-08-29 12:42:48 -07001130 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001131 }
1132 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001133 String8 screenState;
1134 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1135 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001136 if (isOff != (AudioFlinger::mScreenState & 1)) {
1137 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001138 }
1139 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001140 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 }
1142
1143 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1144 // and the thread is exited once the lock is released
1145 sp<ThreadBase> thread;
1146 {
1147 Mutex::Autolock _l(mLock);
1148 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001149 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001151 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001152 // indicate output device change to all input threads for pre processing
1153 AudioParameter param = AudioParameter(keyValuePairs);
1154 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001155 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1156 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001157 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001158 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001159 }
1160 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001161 if (thread != 0) {
1162 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 }
1164 return BAD_VALUE;
1165}
1166
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001167String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001169 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1170 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171
Eric Laurenta4c5a552012-03-29 10:12:40 -07001172 Mutex::Autolock _l(mLock);
1173
Glenn Kasten142f5192014-03-25 17:44:59 -07001174 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001175 String8 out_s8;
1176
Dima Zavin799a70e2011-04-18 16:57:27 -07001177 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001178 char *s;
1179 {
1180 AutoMutex lock(mHardwareLock);
1181 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001182 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001183 s = dev->get_parameters(dev, keys.string());
1184 mHardwareStatus = AUDIO_HW_IDLE;
1185 }
John Grossmanef7740b2012-02-09 11:28:36 -08001186 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001187 free(s);
1188 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001189 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 }
1191
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1193 if (playbackThread != NULL) {
1194 return playbackThread->getParameters(keys);
1195 }
1196 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1197 if (recordThread != NULL) {
1198 return recordThread->getParameters(keys);
1199 }
1200 return String8("");
1201}
1202
Glenn Kastendd8104c2012-07-02 12:42:44 -07001203size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1204 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205{
Eric Laurenta1884f92011-08-23 08:25:03 -07001206 status_t ret = initCheck();
1207 if (ret != NO_ERROR) {
1208 return 0;
1209 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001210 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001211 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001212 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001213 return 0;
1214 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001215
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001216 AutoMutex lock(mHardwareLock);
1217 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001218 audio_config_t config, proposed;
1219 memset(&proposed, 0, sizeof(proposed));
1220 proposed.sample_rate = sampleRate;
1221 proposed.channel_mask = channelMask;
1222 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001223
John Grossmanee578c02012-07-23 17:05:46 -07001224 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001225 size_t frames;
1226 for (;;) {
1227 // Note: config is currently a const parameter for get_input_buffer_size()
1228 // but we use a copy from proposed in case config changes from the call.
1229 config = proposed;
1230 frames = dev->get_input_buffer_size(dev, &config);
1231 if (frames != 0) {
1232 break; // hal success, config is the result
1233 }
1234 // change one parameter of the configuration each iteration to a more "common" value
1235 // to see if the device will support it.
1236 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1237 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1238 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1239 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1240 } else {
1241 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1242 "format %#x, channelMask 0x%X",
1243 sampleRate, format, channelMask);
1244 break; // retries failed, break out of loop with frames == 0.
1245 }
1246 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001247 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001248 if (frames > 0 && config.sample_rate != sampleRate) {
1249 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1250 }
1251 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252}
1253
Glenn Kasten5f972c02014-01-13 09:59:31 -08001254uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 Mutex::Autolock _l(mLock);
1257
1258 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1259 if (recordThread != NULL) {
1260 return recordThread->getInputFramesLost();
1261 }
1262 return 0;
1263}
1264
1265status_t AudioFlinger::setVoiceVolume(float value)
1266{
Eric Laurenta1884f92011-08-23 08:25:03 -07001267 status_t ret = initCheck();
1268 if (ret != NO_ERROR) {
1269 return ret;
1270 }
1271
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 // check calling permissions
1273 if (!settingsAllowed()) {
1274 return PERMISSION_DENIED;
1275 }
1276
1277 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001278 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001279 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001280 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 mHardwareStatus = AUDIO_HW_IDLE;
1282
1283 return ret;
1284}
1285
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001286status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001287 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 Mutex::Autolock _l(mLock);
1290
1291 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1292 if (playbackThread != NULL) {
1293 return playbackThread->getRenderPosition(halFrames, dspFrames);
1294 }
1295
1296 return BAD_VALUE;
1297}
1298
1299void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1300{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001302 if (client == 0) {
1303 return;
1304 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001305 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001306 {
1307 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001308 if (mNotificationClients.indexOfKey(pid) < 0) {
1309 sp<NotificationClient> notificationClient = new NotificationClient(this,
1310 client,
1311 pid);
1312 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313
Eric Laurent021cf962014-05-13 10:18:14 -07001314 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315
Marco Nelissen06b46062014-11-14 07:58:25 -08001316 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001317 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001318 }
1319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320
Eric Laurent021cf962014-05-13 10:18:14 -07001321 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001322 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001323 // the config change is always sent from playback or record threads to avoid deadlock
1324 // with AudioSystem::gLock
1325 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1326 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001329 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1330 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331 }
1332}
1333
1334void AudioFlinger::removeNotificationClient(pid_t pid)
1335{
1336 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001337 {
1338 Mutex::Autolock _cl(mClientLock);
1339 mNotificationClients.removeItem(pid);
1340 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001341
Steve Block3856b092011-10-20 11:56:00 +01001342 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001343 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001344 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001345 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001346 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001347 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001348 if (ref->mPid == pid) {
1349 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001350 mAudioSessionRefs.removeAt(i);
1351 delete ref;
1352 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001353 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001354 } else {
1355 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001356 }
1357 }
1358 if (removed) {
1359 purgeStaleEffects_l();
1360 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001361}
1362
Eric Laurent73e26b62015-04-27 16:55:58 -07001363void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001364 const sp<AudioIoDescriptor>& ioDesc,
1365 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366{
Eric Laurent021cf962014-05-13 10:18:14 -07001367 Mutex::Autolock _l(mClientLock);
1368 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001370 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1371 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373 }
1374}
1375
Eric Laurent021cf962014-05-13 10:18:14 -07001376// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377void AudioFlinger::removeClient_l(pid_t pid)
1378{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001379 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001380 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 mClients.removeItem(pid);
1382}
1383
Eric Laurent717e1282012-06-29 16:36:52 -07001384// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001385sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1386 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001387{
1388 sp<PlaybackThread> thread;
1389
1390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1391 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1392 ALOG_ASSERT(thread == 0);
1393 thread = mPlaybackThreads.valueAt(i);
1394 }
1395 }
1396
1397 return thread;
1398}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401
1402// ----------------------------------------------------------------------------
1403
1404AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1405 : RefBase(),
1406 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001407 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408{
Eric Laurentda73b6c2015-08-20 16:18:53 -07001409 size_t heapSize = kClientSharedHeapSizeBytes;
1410 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1411 // invalidated tracks
1412 if (!audioFlinger->isLowRamDevice()) {
1413 heapSize *= kClientSharedHeapSizeMultiplier;
1414 }
1415 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416}
1417
Eric Laurent021cf962014-05-13 10:18:14 -07001418// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419AudioFlinger::Client::~Client()
1420{
1421 mAudioFlinger->removeClient_l(mPid);
1422}
1423
Glenn Kasten435dbe62012-01-30 10:15:48 -08001424sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425{
1426 return mMemoryDealer;
1427}
1428
1429// ----------------------------------------------------------------------------
1430
1431AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1432 const sp<IAudioFlingerClient>& client,
1433 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001434 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435{
1436}
1437
1438AudioFlinger::NotificationClient::~NotificationClient()
1439{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440}
1441
Glenn Kasten0f11b512014-01-31 16:18:54 -08001442void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443{
1444 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001445 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446}
1447
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
1449// ----------------------------------------------------------------------------
1450
1451sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001452 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001454 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001455 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001456 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001457 size_t *frameCount,
Glenn Kasteneeca3262013-07-31 16:12:48 -07001458 IAudioFlinger::track_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001459 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001460 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001461 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001462 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001463 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001464 sp<IMemory>& cblk,
1465 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 status_t *status)
1467{
1468 sp<RecordThread::RecordTrack> recordTrack;
1469 sp<RecordHandle> recordHandle;
1470 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001472 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473
Glenn Kastend776ac62014-05-07 09:16:09 -07001474 cblk.clear();
1475 buffers.clear();
1476
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001477 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001478 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1479 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001480 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001481 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1482 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001483 updatePid = true;
1484 }
1485
1486 if (updatePid) {
1487 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1488 ALOGW_IF(pid != -1 && pid != callingPid,
1489 "%s uid %d pid %d tried to pass itself off as pid %d",
1490 __func__, callingUid, callingPid, pid);
1491 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001492 }
1493
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001495 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001496 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 lStatus = PERMISSION_DENIED;
1498 goto Exit;
1499 }
1500
Glenn Kasten53b5d092014-02-05 10:00:23 -08001501 // further sample rate checks are performed by createRecordTrack_l()
1502 if (sampleRate == 0) {
1503 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
1507
Andy Hung6770c6f2015-04-07 13:43:36 -07001508 // we don't yet support anything other than linear PCM
1509 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001510 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001511 lStatus = BAD_VALUE;
1512 goto Exit;
1513 }
1514
Glenn Kasten53b5d092014-02-05 10:00:23 -08001515 // further channel mask checks are performed by createRecordTrack_l()
1516 if (!audio_is_input_channel(channelMask)) {
1517 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1518 lStatus = BAD_VALUE;
1519 goto Exit;
1520 }
1521
Glenn Kasten05997e22014-03-13 15:08:33 -07001522 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001524 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001526 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 lStatus = BAD_VALUE;
1528 goto Exit;
1529 }
1530
Eric Laurent021cf962014-05-13 10:18:14 -07001531 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001532
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001533 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001534 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1535 lStatus = BAD_VALUE;
1536 goto Exit;
1537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 lSessionId = *sessionId;
1539 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001540 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001541 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 if (sessionId != NULL) {
1543 *sessionId = lSessionId;
1544 }
1545 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001546 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001547
Glenn Kasten1879fff2012-07-11 15:36:59 -07001548 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001549 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001550 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001551 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001552
1553 if (lStatus == NO_ERROR) {
1554 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1555 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001556 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001557 if (chain != 0) {
1558 Mutex::Autolock _l(thread->mLock);
1559 thread->addEffectChain_l(chain);
1560 }
1561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 }
Glenn Kastene198c362013-08-13 09:13:36 -07001563
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001564 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001565 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001566 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001567 // Don't hold mClientLock when releasing the reference on the track as the
1568 // destructor will acquire it.
1569 {
1570 Mutex::Autolock _cl(mClientLock);
1571 client.clear();
1572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 goto Exit;
1575 }
1576
Glenn Kastend776ac62014-05-07 09:16:09 -07001577 cblk = recordTrack->getCblk();
1578 buffers = recordTrack->getBuffers();
1579
Glenn Kasten2fc14732013-08-05 14:58:14 -07001580 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582
1583Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001584 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585 return recordHandle;
1586}
1587
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001588
1589
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590// ----------------------------------------------------------------------------
1591
Eric Laurenta4c5a552012-03-29 10:12:40 -07001592audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1593{
Eric Laurent44622db2014-08-01 19:00:33 -07001594 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001595 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001596 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001597 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001598 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001599 }
1600 Mutex::Autolock _l(mLock);
1601 return loadHwModule_l(name);
1602}
1603
1604// loadHwModule_l() must be called with AudioFlinger::mLock held
1605audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1606{
1607 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1608 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1609 ALOGW("loadHwModule() module %s already loaded", name);
1610 return mAudioHwDevs.keyAt(i);
1611 }
1612 }
1613
Eric Laurenta4c5a552012-03-29 10:12:40 -07001614 audio_hw_device_t *dev;
1615
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001616 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001617 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001618 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001619 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001620 }
1621
1622 mHardwareStatus = AUDIO_HW_INIT;
1623 rc = dev->init_check(dev);
1624 mHardwareStatus = AUDIO_HW_IDLE;
1625 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001626 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001627 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001628 }
1629
John Grossmanee578c02012-07-23 17:05:46 -07001630 // Check and cache this HAL's level of support for master mute and master
1631 // volume. If this is the first HAL opened, and it supports the get
1632 // methods, use the initial values provided by the HAL as the current
1633 // master mute and volume settings.
1634
1635 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1636 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001637 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001638
1639 if (0 == mAudioHwDevs.size()) {
1640 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1641 if (NULL != dev->get_master_volume) {
1642 float mv;
1643 if (OK == dev->get_master_volume(dev, &mv)) {
1644 mMasterVolume = mv;
1645 }
1646 }
1647
1648 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1649 if (NULL != dev->get_master_mute) {
1650 bool mm;
1651 if (OK == dev->get_master_mute(dev, &mm)) {
1652 mMasterMute = mm;
1653 }
1654 }
1655 }
1656
Eric Laurenta4c5a552012-03-29 10:12:40 -07001657 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001658 if ((NULL != dev->set_master_volume) &&
1659 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1660 flags = static_cast<AudioHwDevice::Flags>(flags |
1661 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1662 }
1663
1664 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1665 if ((NULL != dev->set_master_mute) &&
1666 (OK == dev->set_master_mute(dev, mMasterMute))) {
1667 flags = static_cast<AudioHwDevice::Flags>(flags |
1668 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1669 }
1670
Eric Laurenta4c5a552012-03-29 10:12:40 -07001671 mHardwareStatus = AUDIO_HW_IDLE;
1672 }
1673
Glenn Kastena13cde92016-03-28 15:26:02 -07001674 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001675 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001676
1677 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001678 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001679
1680 return handle;
1681
1682}
1683
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001684// ----------------------------------------------------------------------------
1685
Glenn Kasten3b16c762012-11-14 08:44:39 -08001686uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001687{
1688 Mutex::Autolock _l(mLock);
1689 PlaybackThread *thread = primaryPlaybackThread_l();
1690 return thread != NULL ? thread->sampleRate() : 0;
1691}
1692
Glenn Kastene33054e2012-11-14 12:54:39 -08001693size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001694{
1695 Mutex::Autolock _l(mLock);
1696 PlaybackThread *thread = primaryPlaybackThread_l();
1697 return thread != NULL ? thread->frameCountHAL() : 0;
1698}
1699
1700// ----------------------------------------------------------------------------
1701
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001702status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1703{
1704 uid_t uid = IPCThreadState::self()->getCallingUid();
1705 if (uid != AID_SYSTEM) {
1706 return PERMISSION_DENIED;
1707 }
1708 Mutex::Autolock _l(mLock);
1709 if (mIsDeviceTypeKnown) {
1710 return INVALID_OPERATION;
1711 }
1712 mIsLowRamDevice = isLowRamDevice;
1713 mIsDeviceTypeKnown = true;
1714 return NO_ERROR;
1715}
1716
Eric Laurent93c3d412014-08-01 14:48:35 -07001717audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1718{
1719 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001720
1721 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1722 if (index >= 0) {
1723 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1724 mHwAvSyncIds.valueAt(index), sessionId);
1725 return mHwAvSyncIds.valueAt(index);
1726 }
1727
1728 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1729 if (dev == NULL) {
1730 return AUDIO_HW_SYNC_INVALID;
1731 }
1732 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1733 AudioParameter param = AudioParameter(String8(reply));
1734 free(reply);
1735
1736 int value;
1737 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1738 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1739 return AUDIO_HW_SYNC_INVALID;
1740 }
1741
1742 // allow only one session for a given HW A/V sync ID.
1743 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1744 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1745 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1746 value, mHwAvSyncIds.keyAt(i));
1747 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001748 break;
1749 }
1750 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001751
1752 mHwAvSyncIds.add(sessionId, value);
1753
1754 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1755 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1756 uint32_t sessions = thread->hasAudioSession(sessionId);
1757 if (sessions & PlaybackThread::TRACK_SESSION) {
1758 AudioParameter param = AudioParameter();
1759 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1760 thread->setParameters(param.toString());
1761 break;
1762 }
1763 }
1764
1765 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1766 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001767}
1768
Eric Laurent72e3f392015-05-20 14:43:50 -07001769status_t AudioFlinger::systemReady()
1770{
1771 Mutex::Autolock _l(mLock);
1772 ALOGI("%s", __FUNCTION__);
1773 if (mSystemReady) {
1774 ALOGW("%s called twice", __FUNCTION__);
1775 return NO_ERROR;
1776 }
1777 mSystemReady = true;
1778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1779 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1780 thread->systemReady();
1781 }
1782 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1783 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1784 thread->systemReady();
1785 }
1786 return NO_ERROR;
1787}
1788
Eric Laurentfa90e842014-10-17 18:12:31 -07001789// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1790void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1791{
1792 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1793 if (index >= 0) {
1794 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1795 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1796 AudioParameter param = AudioParameter();
1797 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1798 thread->setParameters(param.toString());
1799 }
1800}
1801
1802
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001803// ----------------------------------------------------------------------------
1804
Eric Laurent83b88082014-06-20 18:31:16 -07001805
1806sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001807 audio_io_handle_t *output,
1808 audio_config_t *config,
1809 audio_devices_t devices,
1810 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001811 audio_output_flags_t flags)
1812{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001813 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001814 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001815 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001816 }
1817
Eric Laurentcf2c0212014-07-25 16:20:43 -07001818 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001819 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1820 } else {
1821 // Audio Policy does not currently request a specific output handle.
1822 // If this is ever needed, see openInput_l() for example code.
1823 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1824 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001825 }
Eric Laurent83b88082014-06-20 18:31:16 -07001826
1827 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1828
Eric Laurent83b88082014-06-20 18:31:16 -07001829 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001830 // This if statement allows overriding the audio policy settings
1831 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1832 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1833 // Check only for Normal Mixing mode
1834 if (kEnableExtendedPrecision) {
1835 // Specify format (uncomment one below to choose)
1836 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1837 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1838 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1839 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001840 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001841 }
1842 if (kEnableExtendedChannels) {
1843 // Specify channel mask (uncomment one below to choose)
1844 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1845 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1846 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1847 }
Eric Laurent83b88082014-06-20 18:31:16 -07001848 }
1849
Phil Burk062e67a2015-02-11 13:40:50 -08001850 AudioStreamOut *outputStream = NULL;
1851 status_t status = outHwDev->openOutputStream(
1852 &outputStream,
1853 *output,
1854 devices,
1855 flags,
1856 config,
1857 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001858
1859 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001860
Phil Burk062e67a2015-02-11 13:40:50 -08001861 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001862
1863 PlaybackThread *thread;
1864 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001865 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001866 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001867 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1868 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001869 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001870 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001871 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001872 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001873 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001874 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001875 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001876 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001877 return thread;
1878 }
1879
1880 return 0;
1881}
1882
Eric Laurentcf2c0212014-07-25 16:20:43 -07001883status_t AudioFlinger::openOutput(audio_module_handle_t module,
1884 audio_io_handle_t *output,
1885 audio_config_t *config,
1886 audio_devices_t *devices,
1887 const String8& address,
1888 uint32_t *latencyMs,
1889 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890{
Phil Burk062e67a2015-02-11 13:40:50 -08001891 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001892 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001893 (devices != NULL) ? *devices : 0,
1894 config->sample_rate,
1895 config->format,
1896 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001897 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898
Eric Laurentcf2c0212014-07-25 16:20:43 -07001899 if (*devices == AUDIO_DEVICE_NONE) {
1900 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001902
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 Mutex::Autolock _l(mLock);
1904
Eric Laurentcf2c0212014-07-25 16:20:43 -07001905 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001906 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001907 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908
1909 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001910 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001911
1912 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001913 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001914 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001915 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001916
1917 AutoMutex lock(mHardwareLock);
1918 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001919 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001920 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001921 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001922 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 }
1924
Eric Laurentcf2c0212014-07-25 16:20:43 -07001925 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926}
1927
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001928audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1929 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930{
1931 Mutex::Autolock _l(mLock);
1932 MixerThread *thread1 = checkMixerThread_l(output1);
1933 MixerThread *thread2 = checkMixerThread_l(output2);
1934
1935 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001936 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1937 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001938 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 }
1940
Glenn Kasteneeecb982016-02-26 10:44:04 -08001941 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001942 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 thread->addOutputTrack(thread2);
1944 mPlaybackThreads.add(id, thread);
1945 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001946 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 return id;
1948}
1949
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001950status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951{
Glenn Kastend96c5722012-04-25 13:44:49 -07001952 return closeOutput_nonvirtual(output);
1953}
1954
1955status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1956{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 // keep strong reference on the playback thread so that
1958 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001959 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 {
1961 Mutex::Autolock _l(mLock);
1962 thread = checkPlaybackThread_l(output);
1963 if (thread == NULL) {
1964 return BAD_VALUE;
1965 }
1966
Steve Block3856b092011-10-20 11:56:00 +01001967 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001969 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001971 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001972 DuplicatingThread *dupThread =
1973 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 }
1976 }
1977 }
1978
1979
1980 mPlaybackThreads.removeItem(output);
1981 // save all effects to the default thread
1982 if (mPlaybackThreads.size()) {
1983 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1984 if (dstThread != NULL) {
1985 // audioflinger lock is held here so the acquisition order of thread locks does not
1986 // matter
1987 Mutex::Autolock _dl(dstThread->mLock);
1988 Mutex::Autolock _sl(thread->mLock);
1989 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1990 for (size_t i = 0; i < effectChains.size(); i ++) {
1991 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 }
1993 }
1994 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001995 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1996 ioDesc->mIoHandle = output;
1997 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 }
1999 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002000 // The thread entity (active unit of execution) is no longer running here,
2001 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002
Eric Laurentf6870ae2015-05-08 10:50:03 -07002003 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002004 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }
Eric Laurent83b88082014-06-20 18:31:16 -07002006
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 return NO_ERROR;
2008}
2009
Eric Laurent83b88082014-06-20 18:31:16 -07002010void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
2011{
2012 AudioStreamOut *out = thread->clearOutput();
2013 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2014 // from now on thread->mOutput is NULL
2015 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
2016 delete out;
2017}
2018
2019void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
2020{
2021 mPlaybackThreads.removeItem(thread->mId);
2022 thread->exit();
2023 closeOutputFinish(thread);
2024}
2025
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002026status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027{
2028 Mutex::Autolock _l(mLock);
2029 PlaybackThread *thread = checkPlaybackThread_l(output);
2030
2031 if (thread == NULL) {
2032 return BAD_VALUE;
2033 }
2034
Steve Block3856b092011-10-20 11:56:00 +01002035 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 thread->suspend();
2037
2038 return NO_ERROR;
2039}
2040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002041status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042{
2043 Mutex::Autolock _l(mLock);
2044 PlaybackThread *thread = checkPlaybackThread_l(output);
2045
2046 if (thread == NULL) {
2047 return BAD_VALUE;
2048 }
2049
Steve Block3856b092011-10-20 11:56:00 +01002050 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051
2052 thread->restore();
2053
2054 return NO_ERROR;
2055}
2056
Eric Laurentcf2c0212014-07-25 16:20:43 -07002057status_t AudioFlinger::openInput(audio_module_handle_t module,
2058 audio_io_handle_t *input,
2059 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002060 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002061 const String8& address,
2062 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002063 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064{
Eric Laurent83b88082014-06-20 18:31:16 -07002065 Mutex::Autolock _l(mLock);
2066
Glenn Kastene7d66712015-03-05 13:46:52 -08002067 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002068 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002069 }
2070
Glenn Kastene7d66712015-03-05 13:46:52 -08002071 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002072
2073 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002074 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002075 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002076 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002078 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002079}
Dima Zavin799a70e2011-04-18 16:57:27 -07002080
Eric Laurent83b88082014-06-20 18:31:16 -07002081sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002082 audio_io_handle_t *input,
2083 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002084 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002085 const String8& address,
2086 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002087 audio_input_flags_t flags)
2088{
Glenn Kastene7d66712015-03-05 13:46:52 -08002089 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002090 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002091 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002092 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002093 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002094
Glenn Kasteneeecb982016-02-26 10:44:04 -08002095 // Audio Policy can request a specific handle for hardware hotword.
2096 // The goal here is not to re-open an already opened input.
2097 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002098 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002099 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2100 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2101 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2102 return 0;
2103 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2104 // This should not happen in a transient state with current design.
2105 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2106 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002107 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002108
Eric Laurentcf2c0212014-07-25 16:20:43 -07002109 audio_config_t halconfig = *config;
2110 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002111 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002112 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002113 &inStream, flags, address.string(), source);
2114 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002115 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002116 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 halconfig.sample_rate,
2118 halconfig.format,
2119 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002120 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002121 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002123 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002124 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002125 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002126 audio_is_linear_pcm(config->format) &&
2127 audio_is_linear_pcm(halconfig.format) &&
2128 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002129 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2130 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002131 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002132 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002133 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002134 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002135 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002136 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 }
2138
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002139 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002140
Glenn Kasten46909e72013-02-26 09:20:22 -08002141#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002142 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2143 // or (re-)create if current Pipe is idle and does not match the new format
2144 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002145 enum {
2146 TEE_SINK_NO, // don't copy input
2147 TEE_SINK_NEW, // copy input using a new pipe
2148 TEE_SINK_OLD, // copy input using an existing pipe
2149 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002150 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2151 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002152 if (!mTeeSinkInputEnabled) {
2153 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002154 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002155 kind = TEE_SINK_NO;
2156 } else if (mRecordTeeSink == 0) {
2157 kind = TEE_SINK_NEW;
2158 } else if (mRecordTeeSink->getStrongCount() != 1) {
2159 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002160 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002161 kind = TEE_SINK_OLD;
2162 } else {
2163 kind = TEE_SINK_NEW;
2164 }
2165 switch (kind) {
2166 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002167 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002168 size_t numCounterOffers = 0;
2169 const NBAIO_Format offers[1] = {format};
2170 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2171 ALOG_ASSERT(index == 0);
2172 PipeReader *pipeReader = new PipeReader(*pipe);
2173 numCounterOffers = 0;
2174 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2175 ALOG_ASSERT(index == 0);
2176 mRecordTeeSink = pipe;
2177 mRecordTeeSource = pipeReader;
2178 teeSink = pipe;
2179 }
2180 break;
2181 case TEE_SINK_OLD:
2182 teeSink = mRecordTeeSink;
2183 break;
2184 case TEE_SINK_NO:
2185 default:
2186 break;
2187 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002188#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002189
Eric Laurentcf2c0212014-07-25 16:20:43 -07002190 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002191
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002192 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002193 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002194 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002195 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002196 inputStream,
2197 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002198 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002199 devices,
2200 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002201#ifdef TEE_SINK
2202 , teeSink
2203#endif
2204 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002205 mRecordThreads.add(*input, thread);
2206 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002207 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002208 }
2209
Eric Laurentcf2c0212014-07-25 16:20:43 -07002210 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 return 0;
2212}
2213
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002214status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215{
Glenn Kastend96c5722012-04-25 13:44:49 -07002216 return closeInput_nonvirtual(input);
2217}
2218
2219status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2220{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 // keep strong reference on the record thread so that
2222 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002223 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 {
2225 Mutex::Autolock _l(mLock);
2226 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002227 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 return BAD_VALUE;
2229 }
2230
Steve Block3856b092011-10-20 11:56:00 +01002231 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002232
2233 // If we still have effect chains, it means that a client still holds a handle
2234 // on at least one effect. We must either move the chain to an existing thread with the
2235 // same session ID or put it aside in case a new record thread is opened for a
2236 // new capture on the same session
2237 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002238 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002239 Mutex::Autolock _sl(thread->mLock);
2240 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002241 // Note: maximum one chain per record thread
2242 if (effectChains.size() != 0) {
2243 chain = effectChains[0];
2244 }
2245 }
2246 if (chain != 0) {
2247 // first check if a record thread is already opened with a client on the same session.
2248 // This should only happen in case of overlap between one thread tear down and the
2249 // creation of its replacement
2250 size_t i;
2251 for (i = 0; i < mRecordThreads.size(); i++) {
2252 sp<RecordThread> t = mRecordThreads.valueAt(i);
2253 if (t == thread) {
2254 continue;
2255 }
2256 if (t->hasAudioSession(chain->sessionId()) != 0) {
2257 Mutex::Autolock _l(t->mLock);
2258 ALOGV("closeInput() found thread %d for effect session %d",
2259 t->id(), chain->sessionId());
2260 t->addEffectChain_l(chain);
2261 break;
2262 }
2263 }
2264 // put the chain aside if we could not find a record thread with the same session id.
2265 if (i == mRecordThreads.size()) {
2266 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002267 }
2268 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002269 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2270 ioDesc->mIoHandle = input;
2271 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 mRecordThreads.removeItem(input);
2273 }
Eric Laurent83b88082014-06-20 18:31:16 -07002274 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2275 // we have a different lock for notification client
2276 closeInputFinish(thread);
2277 return NO_ERROR;
2278}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279
Eric Laurent83b88082014-06-20 18:31:16 -07002280void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2281{
2282 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002283 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002284 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002285 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002286 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002287 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002288}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289
Eric Laurent83b88082014-06-20 18:31:16 -07002290void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2291{
2292 mRecordThreads.removeItem(thread->mId);
2293 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294}
2295
Glenn Kastend2304db2014-02-03 07:40:31 -08002296status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297{
2298 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002299 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300
2301 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2302 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002303 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002304 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305
2306 return NO_ERROR;
2307}
2308
2309
Glenn Kasteneeecb982016-02-26 10:44:04 -08002310audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311{
Glenn Kasten9d003132016-04-06 14:38:09 -07002312 // This is a binder API, so a malicious client could pass in a bad parameter.
2313 // Check for that before calling the internal API nextUniqueId().
2314 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2315 ALOGE("newAudioUniqueId invalid use %d", use);
2316 return AUDIO_UNIQUE_ID_ALLOCATE;
2317 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002318 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319}
2320
Glenn Kastend848eb42016-03-08 13:42:11 -08002321void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002322{
2323 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002324 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002325 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2326 if (pid != -1 && (caller == getpid_cached)) {
2327 caller = pid;
2328 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002329
Eric Laurent021cf962014-05-13 10:18:14 -07002330 {
2331 Mutex::Autolock _cl(mClientLock);
2332 // Ignore requests received from processes not known as notification client. The request
2333 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2334 // called from a different pid leaving a stale session reference. Also we don't know how
2335 // to clear this reference if the client process dies.
2336 if (mNotificationClients.indexOfKey(caller) < 0) {
2337 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2338 return;
2339 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002340 }
2341
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002342 size_t num = mAudioSessionRefs.size();
2343 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002344 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002345 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2346 ref->mCnt++;
2347 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002348 return;
2349 }
2350 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002351 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2352 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002353}
2354
Glenn Kastend848eb42016-03-08 13:42:11 -08002355void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002356{
2357 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002358 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002359 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2360 if (pid != -1 && (caller == getpid_cached)) {
2361 caller = pid;
2362 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002363 size_t num = mAudioSessionRefs.size();
2364 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002365 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002366 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2367 ref->mCnt--;
2368 ALOGV(" decremented refcount to %d", ref->mCnt);
2369 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002370 mAudioSessionRefs.removeAt(i);
2371 delete ref;
2372 purgeStaleEffects_l();
2373 }
2374 return;
2375 }
2376 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002377 // If the caller is mediaserver it is likely that the session being released was acquired
2378 // on behalf of a process not in notification clients and we ignore the warning.
2379 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002380}
2381
2382void AudioFlinger::purgeStaleEffects_l() {
2383
Steve Block3856b092011-10-20 11:56:00 +01002384 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002385
2386 Vector< sp<EffectChain> > chains;
2387
2388 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2389 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2390 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2391 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002392 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2393 chains.push(ec);
2394 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002395 }
2396 }
2397 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2398 sp<RecordThread> t = mRecordThreads.valueAt(i);
2399 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2400 sp<EffectChain> ec = t->mEffectChains[j];
2401 chains.push(ec);
2402 }
2403 }
2404
2405 for (size_t i = 0; i < chains.size(); i++) {
2406 sp<EffectChain> ec = chains[i];
2407 int sessionid = ec->sessionId();
2408 sp<ThreadBase> t = ec->mThread.promote();
2409 if (t == 0) {
2410 continue;
2411 }
2412 size_t numsessionrefs = mAudioSessionRefs.size();
2413 bool found = false;
2414 for (size_t k = 0; k < numsessionrefs; k++) {
2415 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002416 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002417 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002418 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002419 found = true;
2420 break;
2421 }
2422 }
2423 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002424 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002425 // remove all effects from the chain
2426 while (ec->mEffects.size()) {
2427 sp<EffectModule> effect = ec->mEffects[0];
2428 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002429 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002430 if (effect->purgeHandles()) {
2431 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002432 }
2433 AudioSystem::unregisterEffect(effect->id());
2434 }
2435 }
2436 }
2437 return;
2438}
2439
Glenn Kasteneeecb982016-02-26 10:44:04 -08002440// checkThread_l() must be called with AudioFlinger::mLock held
2441AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2442{
2443 ThreadBase *thread = NULL;
2444 switch (audio_unique_id_get_use(ioHandle)) {
2445 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2446 thread = checkPlaybackThread_l(ioHandle);
2447 break;
2448 case AUDIO_UNIQUE_ID_USE_INPUT:
2449 thread = checkRecordThread_l(ioHandle);
2450 break;
2451 default:
2452 break;
2453 }
2454 return thread;
2455}
2456
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002458AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459{
Glenn Kastena1117922012-01-26 10:53:32 -08002460 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461}
2462
2463// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002464AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465{
2466 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002467 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468}
2469
2470// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002471AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472{
Glenn Kastena1117922012-01-26 10:53:32 -08002473 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474}
2475
Glenn Kasteneeecb982016-02-26 10:44:04 -08002476audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477{
Glenn Kasten9d003132016-04-06 14:38:09 -07002478 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002479 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002480 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2481 for (int retry = 0; retry < maxRetries; retry++) {
2482 // The cast allows wraparound from max positive to min negative instead of abort
2483 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2484 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2485 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2486 // allow wrap by skipping 0 and -1 for session ids
2487 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2488 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2489 return (audio_unique_id_t) (base | use);
2490 }
2491 }
2492 // We have no way of recovering from wraparound
2493 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2494 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495}
2496
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002497AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002498{
2499 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2500 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002501 if(thread->isDuplicating()) {
2502 continue;
2503 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002504 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002505 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002506 return thread;
2507 }
2508 }
2509 return NULL;
2510}
2511
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002512audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002513{
2514 PlaybackThread *thread = primaryPlaybackThread_l();
2515
2516 if (thread == NULL) {
2517 return 0;
2518 }
2519
Eric Laurentf1c04f92012-08-28 14:26:53 -07002520 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002521}
2522
Eric Laurenta011e352012-03-29 15:51:43 -07002523sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002524 audio_session_t triggerSession,
2525 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002526 sync_event_callback_t callBack,
Eric Laurent8ea16e42014-02-20 16:26:11 -08002527 wp<RefBase> cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002528{
2529 Mutex::Autolock _l(mLock);
2530
2531 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2532 status_t playStatus = NAME_NOT_FOUND;
2533 status_t recStatus = NAME_NOT_FOUND;
2534 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2535 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2536 if (playStatus == NO_ERROR) {
2537 return event;
2538 }
2539 }
2540 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2541 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2542 if (recStatus == NO_ERROR) {
2543 return event;
2544 }
2545 }
2546 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2547 mPendingSyncEvents.add(event);
2548 } else {
2549 ALOGV("createSyncEvent() invalid event %d", event->type());
2550 event.clear();
2551 }
2552 return event;
2553}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002554
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555// ----------------------------------------------------------------------------
2556// Effect management
2557// ----------------------------------------------------------------------------
2558
2559
Glenn Kastenf587ba52012-01-26 16:25:10 -08002560status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561{
2562 Mutex::Autolock _l(mLock);
2563 return EffectQueryNumberEffects(numEffects);
2564}
2565
Glenn Kastenf587ba52012-01-26 16:25:10 -08002566status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567{
2568 Mutex::Autolock _l(mLock);
2569 return EffectQueryEffect(index, descriptor);
2570}
2571
Glenn Kasten5e92a782012-01-30 07:40:52 -08002572status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002573 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574{
2575 Mutex::Autolock _l(mLock);
2576 return EffectGetDescriptor(pUuid, descriptor);
2577}
2578
2579
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002580sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 effect_descriptor_t *pDesc,
2582 const sp<IEffectClient>& effectClient,
2583 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002584 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002585 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002586 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 status_t *status,
2588 int *id,
2589 int *enabled)
2590{
2591 status_t lStatus = NO_ERROR;
2592 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002595 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002596 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002597 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598
2599 if (pDesc == NULL) {
2600 lStatus = BAD_VALUE;
2601 goto Exit;
2602 }
2603
Eric Laurent84e9a102010-09-23 16:10:16 -07002604 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002605 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002606 lStatus = PERMISSION_DENIED;
2607 goto Exit;
2608 }
2609
Dima Zavinfce7a472011-04-19 22:30:36 -07002610 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002611 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002612 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002613 lStatus = PERMISSION_DENIED;
2614 goto Exit;
2615 }
2616
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 if (!EffectIsNullUuid(&pDesc->uuid)) {
2619 // if uuid is specified, request effect descriptor
2620 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2621 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002622 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 goto Exit;
2624 }
2625 } else {
2626 // if uuid is not specified, look for an available implementation
2627 // of the required type in effect factory
2628 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002629 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 lStatus = BAD_VALUE;
2631 goto Exit;
2632 }
2633 uint32_t numEffects = 0;
2634 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002635 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 bool found = false;
2637
2638 lStatus = EffectQueryNumberEffects(&numEffects);
2639 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002640 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 goto Exit;
2642 }
2643 for (uint32_t i = 0; i < numEffects; i++) {
2644 lStatus = EffectQueryEffect(i, &desc);
2645 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002646 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 continue;
2648 }
2649 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2650 // If matching type found save effect descriptor. If the session is
2651 // 0 and the effect is not auxiliary, continue enumeration in case
2652 // an auxiliary version of this effect type is available
2653 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002654 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002655 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2657 break;
2658 }
2659 }
2660 }
2661 if (!found) {
2662 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002663 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 goto Exit;
2665 }
2666 // For same effect type, chose auxiliary version over insert version if
2667 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002668 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002670 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002671 }
2672 }
2673
2674 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002675 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2677 lStatus = INVALID_OPERATION;
2678 goto Exit;
2679 }
2680
Eric Laurent59255e42011-07-27 19:49:51 -07002681 // check recording permission for visualizer
2682 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002683 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002684 lStatus = PERMISSION_DENIED;
2685 goto Exit;
2686 }
2687
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002689 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002690 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002691 // if the output returned by getOutputForEffect() is removed before we lock the
2692 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2693 // and we will exit safely
2694 io = AudioSystem::getOutputForEffect(&desc);
2695 ALOGV("createEffect got output %d", io);
2696 }
2697
2698 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699
2700 // If output is not specified try to find a matching audio session ID in one of the
2701 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002702 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2703 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002704 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002705 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002706 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2707 // output must be specified by AudioPolicyManager when using session
2708 // AUDIO_SESSION_OUTPUT_STAGE
2709 lStatus = BAD_VALUE;
2710 goto Exit;
2711 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002712 // look for the thread where the specified audio session is present
2713 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2714 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2715 io = mPlaybackThreads.keyAt(i);
2716 break;
2717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002719 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002720 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2721 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2722 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002723 break;
2724 }
2725 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002726 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002727 // If no output thread contains the requested session ID, default to
2728 // first output. The effect chain will be moved to the correct output
2729 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002730 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002731 io = mPlaybackThreads.keyAt(0);
2732 }
Steve Block3856b092011-10-20 11:56:00 +01002733 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002734 }
2735 ThreadBase *thread = checkRecordThread_l(io);
2736 if (thread == NULL) {
2737 thread = checkPlaybackThread_l(io);
2738 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002739 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002740 lStatus = BAD_VALUE;
2741 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002742 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002743 } else {
2744 // Check if one effect chain was awaiting for an effect to be created on this
2745 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002746 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002747 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002748 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002749 thread->addEffectChain_l(chain);
2750 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002752
Eric Laurent021cf962014-05-13 10:18:14 -07002753 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002755 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002756 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2757 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758 if (handle != 0 && id != NULL) {
2759 *id = handle->id();
2760 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002761 if (handle == 0) {
2762 // remove local strong reference to Client with mClientLock held
2763 Mutex::Autolock _cl(mClientLock);
2764 client.clear();
2765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 }
2767
2768Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002769 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 return handle;
2771}
2772
Glenn Kastend848eb42016-03-08 13:42:11 -08002773status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002774 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002775{
Steve Block3856b092011-10-20 11:56:00 +01002776 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002777 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002778 Mutex::Autolock _l(mLock);
2779 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002780 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002781 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782 }
Eric Laurentde070132010-07-13 04:45:46 -07002783 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2784 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002785 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002786 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787 }
Eric Laurentde070132010-07-13 04:45:46 -07002788 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2789 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002790 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002791 return BAD_VALUE;
2792 }
2793
2794 Mutex::Autolock _dl(dstThread->mLock);
2795 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002796 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797}
2798
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002799// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002800status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002801 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002802 AudioFlinger::PlaybackThread *dstThread,
2803 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002804{
Steve Block3856b092011-10-20 11:56:00 +01002805 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002806 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002807
Eric Laurent59255e42011-07-27 19:49:51 -07002808 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002809 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002810 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002811 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002812 return INVALID_OPERATION;
2813 }
2814
Andy Hung9a592762014-07-21 21:56:01 -07002815 // Check whether the destination thread has a channel count of FCC_2, which is
2816 // currently required for (most) effects. Prevent moving the effect chain here rather
2817 // than disabling the addEffect_l() call in dstThread below.
Eric Laurentf6870ae2015-05-08 10:50:03 -07002818 if ((dstThread->type() == ThreadBase::MIXER || dstThread->isDuplicating()) &&
Eric Laurentb10352f2014-11-03 16:25:39 -08002819 dstThread->mChannelCount != FCC_2) {
Andy Hung9a592762014-07-21 21:56:01 -07002820 ALOGW("moveEffectChain_l() effect chain failed because"
2821 " destination thread %p channel count(%u) != %u",
2822 dstThread, dstThread->mChannelCount, FCC_2);
2823 return INVALID_OPERATION;
2824 }
2825
Eric Laurent39e94f82010-07-28 01:32:47 -07002826 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002827 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002828 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002829 // removed.
2830 srcThread->removeEffectChain_l(chain);
2831
2832 // transfer all effects one by one so that new effect chain is created on new thread with
2833 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002834 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002835 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002836 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002837 Vector< sp<EffectModule> > removed;
2838 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002839 while (effect != 0) {
2840 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002841 removed.add(effect);
2842 status = dstThread->addEffect_l(effect);
2843 if (status != NO_ERROR) {
2844 break;
2845 }
Eric Laurentec35a142011-10-05 17:42:25 -07002846 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2847 if (effect->state() == EffectModule::ACTIVE ||
2848 effect->state() == EffectModule::STOPPING) {
2849 effect->start();
2850 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002851 // if the move request is not received from audio policy manager, the effect must be
2852 // re-registered with the new strategy and output
2853 if (dstChain == 0) {
2854 dstChain = effect->chain().promote();
2855 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002856 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002857 status = NO_INIT;
2858 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002859 }
2860 strategy = dstChain->strategy();
2861 }
2862 if (reRegister) {
2863 AudioSystem::unregisterEffect(effect->id());
2864 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002865 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002866 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002867 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002868 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002869 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002870 }
Eric Laurentde070132010-07-13 04:45:46 -07002871 effect = chain->getEffectFromId_l(0);
2872 }
2873
Eric Laurent5baf2af2013-09-12 17:37:00 -07002874 if (status != NO_ERROR) {
2875 for (size_t i = 0; i < removed.size(); i++) {
2876 srcThread->addEffect_l(removed[i]);
2877 if (dstChain != 0 && reRegister) {
2878 AudioSystem::unregisterEffect(removed[i]->id());
2879 AudioSystem::registerEffect(&removed[i]->desc(),
2880 srcThread->id(),
2881 strategy,
2882 sessionId,
2883 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002884 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002885 }
2886 }
2887 }
2888
2889 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890}
2891
Eric Laurent5baf2af2013-09-12 17:37:00 -07002892bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002893{
2894 if (mGlobalEffectEnableTime != 0 &&
2895 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2896 return true;
2897 }
2898
2899 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2900 sp<EffectChain> ec =
2901 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002902 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002903 return true;
2904 }
2905 }
2906 return false;
2907}
2908
Eric Laurent5baf2af2013-09-12 17:37:00 -07002909void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002910{
2911 Mutex::Autolock _l(mLock);
2912
2913 mGlobalEffectEnableTime = systemTime();
2914
2915 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2916 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2917 if (t->mType == ThreadBase::OFFLOAD) {
2918 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2919 }
2920 }
2921
2922}
2923
Eric Laurentaaa44472014-09-12 17:41:50 -07002924status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2925{
Glenn Kastend848eb42016-03-08 13:42:11 -08002926 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002927 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002928 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002929 if (index >= 0) {
2930 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2931 return ALREADY_EXISTS;
2932 }
2933 mOrphanEffectChains.add(session, chain);
2934 return NO_ERROR;
2935}
2936
2937sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2938{
2939 sp<EffectChain> chain;
2940 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002941 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002942 if (index >= 0) {
2943 chain = mOrphanEffectChains.valueAt(index);
2944 mOrphanEffectChains.removeItemsAt(index);
2945 }
2946 return chain;
2947}
2948
2949bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2950{
2951 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002952 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002953 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002954 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002955 if (index >= 0) {
2956 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2957 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002958 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002959 mOrphanEffectChains.removeItemsAt(index);
2960 }
2961 return true;
2962 }
2963 return false;
2964}
2965
2966
Glenn Kastenda6ef132013-01-10 12:31:01 -08002967struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002968#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2969 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002970};
2971
2972int comparEntry(const void *p1, const void *p2)
2973{
Glenn Kasten2f55e762015-03-05 16:05:08 -08002974 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002975}
2976
Glenn Kasten46909e72013-02-26 09:20:22 -08002977#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002978void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979{
Eric Laurent81784c32012-11-19 14:55:58 -08002980 NBAIO_Source *teeSource = source.get();
2981 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002982 // .wav rotation
2983 // There is a benign race condition if 2 threads call this simultaneously.
2984 // They would both traverse the directory, but the result would simply be
2985 // failures at unlink() which are ignored. It's also unlikely since
2986 // normally dumpsys is only done by bugreport or from the command line.
2987 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08002988 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08002989 size_t teePathLen = strlen(teePath);
2990 DIR *dir = opendir(teePath);
2991 teePath[teePathLen++] = '/';
2992 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002993#define TEE_MAX_SORT 20 // number of entries to sort
2994#define TEE_MAX_KEEP 10 // number of entries to keep
2995 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002996 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08002997 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002998 struct dirent de;
2999 struct dirent *result = NULL;
3000 int rc = readdir_r(dir, &de, &result);
3001 if (rc != 0) {
3002 ALOGW("readdir_r failed %d", rc);
3003 break;
3004 }
3005 if (result == NULL) {
3006 break;
3007 }
3008 if (result != &de) {
3009 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3010 break;
3011 }
3012 // ignore non .wav file entries
3013 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003014 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003015 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3016 continue;
3017 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003018 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003019 }
3020 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003021 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003022 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003023 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3024 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003025 (void) unlink(teePath);
3026 }
3027 }
3028 } else {
3029 if (fd >= 0) {
Glenn Kasten9a003992016-02-23 15:24:34 -08003030 dprintf(fd, "unable to rotate tees in %.*s: %s\n", teePathLen, teePath,
3031 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003032 }
3033 }
Eric Laurent81784c32012-11-19 14:55:58 -08003034 char teeTime[16];
3035 struct timeval tv;
3036 gettimeofday(&tv, NULL);
3037 struct tm tm;
3038 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003039 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3040 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3041 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3042 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003043 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003044 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003045 char wavHeader[44];
3046 memcpy(wavHeader,
3047 "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",
3048 sizeof(wavHeader));
3049 NBAIO_Format format = teeSource->format();
3050 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003052 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003053 wavHeader[22] = channelCount; // number of channels
3054 wavHeader[24] = sampleRate; // sample rate
3055 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003056 wavHeader[32] = frameSize; // block alignment
3057 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003058 write(teeFd, wavHeader, sizeof(wavHeader));
3059 size_t total = 0;
3060 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003061#define TEE_SINK_READ 1024 // frames per I/O operation
3062 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003063 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003064 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003065 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003066 bool wasFirstRead = firstRead;
3067 firstRead = false;
3068 if (actual <= 0) {
3069 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3070 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003071 }
Eric Laurent81784c32012-11-19 14:55:58 -08003072 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003073 }
Eric Laurent81784c32012-11-19 14:55:58 -08003074 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003075 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003076 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003077 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003078 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003079 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003080 uint32_t temp = 44 + total * frameSize - 8;
3081 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003082 write(teeFd, &temp, sizeof(temp));
3083 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003084 temp = total * frameSize;
3085 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003086 write(teeFd, &temp, sizeof(temp));
3087 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003088 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003089 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003090 }
Eric Laurent59255e42011-07-27 19:49:51 -07003091 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003092 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003093 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003094 }
Eric Laurent59255e42011-07-27 19:49:51 -07003095 }
3096 }
3097}
Glenn Kasten46909e72013-02-26 09:20:22 -08003098#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003099
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100// ----------------------------------------------------------------------------
3101
3102status_t AudioFlinger::onTransact(
3103 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3104{
3105 return BnAudioFlinger::onTransact(code, data, reply, flags);
3106}
3107
Glenn Kasten63238ef2015-03-02 15:50:29 -08003108} // namespace android