blob: d2fee8187945a734458b6a8356cb5171894448a0 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070034#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
41
Dima Zavin64760242011-05-11 14:15:23 -070042#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070043#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080047#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
Andy Hung6770c6f2015-04-07 13:43:36 -070049#include <media/AudioResamplerPublic.h>
50
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070052#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070053#include <audio_effects/effect_ns.h>
54#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Glenn Kasten3b21c502011-12-15 09:52:39 -080056#include <audio_utils/primitives.h>
57
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080059
Glenn Kasten9e58b552013-01-18 15:09:48 -080060#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070061#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080062#include <media/nbaio/Pipe.h>
63#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070064#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080065#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070066#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080067
Mathias Agopian65ab4712010-07-14 17:59:35 -070068// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070069
John Grossman1c345192012-03-27 14:00:17 -070070// Note: the following macro is used for extremely verbose logging message. In
71// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
72// 0; but one side effect of this is to turn all LOGV's as well. Some messages
73// are so verbose that we want to suppress them even when we have ALOG_ASSERT
74// turned on. Do not uncomment the #def below unless you really know what you
75// are doing and want to see all of the extremely verbose messages.
76//#define VERY_VERY_VERBOSE_LOGGING
77#ifdef VERY_VERY_VERBOSE_LOGGING
78#define ALOGVV ALOGV
79#else
80#define ALOGVV(a...) do { } while(0)
81#endif
Eric Laurentde070132010-07-13 04:45:46 -070082
Mathias Agopian65ab4712010-07-14 17:59:35 -070083namespace android {
84
Glenn Kastenec1d6b52011-12-12 09:04:45 -080085static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
86static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070087static const char kClientLockedString[] = "Client lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Glenn Kasten58912562012-04-03 10:45:00 -070089
John Grossman4ff14ba2012-02-08 16:37:41 -080090nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080091
Eric Laurent81784c32012-11-19 14:55:58 -080092uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070093
Glenn Kasten46909e72013-02-26 09:20:22 -080094#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080095bool AudioFlinger::mTeeSinkInputEnabled = false;
96bool AudioFlinger::mTeeSinkOutputEnabled = false;
97bool AudioFlinger::mTeeSinkTrackEnabled = false;
98
99size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
100size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
101size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800102#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800103
Eric Laurent813e2a72013-08-31 12:59:48 -0700104// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
105// we define a minimum time during which a global effect is considered enabled.
106static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109
Marco Nelissenb2208842014-02-07 14:00:50 -0800110const char *formatToString(audio_format_t format) {
Phil Burkfdb3c072016-02-09 10:47:02 -0800111 switch (audio_get_main_format(format)) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530112 case AUDIO_FORMAT_PCM:
113 switch (format) {
114 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
115 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
116 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
117 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
118 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
119 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
120 default:
121 break;
122 }
123 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800124 case AUDIO_FORMAT_MP3: return "mp3";
125 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
126 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
127 case AUDIO_FORMAT_AAC: return "aac";
128 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
129 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
130 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530131 case AUDIO_FORMAT_OPUS: return "opus";
132 case AUDIO_FORMAT_AC3: return "ac-3";
133 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Phil Burkfdb3c072016-02-09 10:47:02 -0800134 case AUDIO_FORMAT_IEC61937: return "iec61937";
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
Andy Hung07b745e2016-05-23 16:21:07 -0700474 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700475 bool unreachableMemory = false;
476 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700477 if (arg == String16("-m")) {
478 dumpMem = true;
479 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700480 unreachableMemory = true;
481 }
482 }
483
Andy Hung07b745e2016-05-23 16:21:07 -0700484 if (dumpMem) {
485 dprintf(fd, "\nDumping memory:\n");
486 std::string s = dumpMemoryAddresses(100 /* limit */);
487 write(fd, s.c_str(), s.size());
488 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700489 if (unreachableMemory) {
490 dprintf(fd, "\nDumping unreachable memory:\n");
491 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700492 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700493 write(fd, s.c_str(), s.size());
494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 }
496 return NO_ERROR;
497}
498
Eric Laurent021cf962014-05-13 10:18:14 -0700499sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800500{
Eric Laurent021cf962014-05-13 10:18:14 -0700501 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800502 // If pid is already in the mClients wp<> map, then use that entry
503 // (for which promote() is always != 0), otherwise create a new entry and Client.
504 sp<Client> client = mClients.valueFor(pid).promote();
505 if (client == 0) {
506 client = new Client(this, pid);
507 mClients.add(pid, client);
508 }
509
510 return client;
511}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512
Glenn Kasten9e58b552013-01-18 15:09:48 -0800513sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
514{
Glenn Kasten481fb672013-09-30 14:39:28 -0700515 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800516 if (mLogMemoryDealer == 0) {
517 return new NBLog::Writer();
518 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800519 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700520 // Similarly if we can't contact the media.log service, also return a dummy writer
521 if (binder == 0) {
522 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800523 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700524 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
525 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
526 // If allocation fails, consult the vector of previously unregistered writers
527 // and garbage-collect one or more them until an allocation succeeds
528 if (shared == 0) {
529 Mutex::Autolock _l(mUnregisteredWritersLock);
530 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
531 {
532 // Pick the oldest stale writer to garbage-collect
533 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
534 mUnregisteredWriters.removeAt(0);
535 mediaLogService->unregisterWriter(iMemory);
536 // Now the media.log remote reference to IMemory is gone. When our last local
537 // reference to IMemory also drops to zero at end of this block,
538 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
539 }
540 // Re-attempt the allocation
541 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
542 if (shared != 0) {
543 goto success;
544 }
545 }
546 // Even after garbage-collecting all old writers, there is still not enough memory,
547 // so return a dummy writer
548 return new NBLog::Writer();
549 }
550success:
551 mediaLogService->registerWriter(shared, size, name);
552 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800553}
554
555void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
556{
Glenn Kasten685ef092013-02-04 08:15:34 -0800557 if (writer == 0) {
558 return;
559 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800560 sp<IMemory> iMemory(writer->getIMemory());
561 if (iMemory == 0) {
562 return;
563 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700564 // Rather than removing the writer immediately, append it to a queue of old writers to
565 // be garbage-collected later. This allows us to continue to view old logs for a while.
566 Mutex::Autolock _l(mUnregisteredWritersLock);
567 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800568}
569
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570// IAudioFlinger interface
571
572
573sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800574 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800576 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700577 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800578 size_t *frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800579 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800581 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700582 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800583 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800584 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800585 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 status_t *status)
587{
588 sp<PlaybackThread::Track> track;
589 sp<TrackHandle> trackHandle;
590 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800592 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700594 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
595 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
596 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
597 ALOGW_IF(pid != -1 && pid != callingPid,
598 "%s uid %d pid %d tried to pass itself off as pid %d",
599 __func__, callingUid, callingPid, pid);
600 pid = callingPid;
601 }
602
Glenn Kasten263709e2012-01-06 08:40:01 -0800603 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
604 // but if someone uses binder directly they could bypass that and cause us to crash
605 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000606 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 lStatus = BAD_VALUE;
608 goto Exit;
609 }
610
Glenn Kasten53b5d092014-02-05 10:00:23 -0800611 // further sample rate checks are performed by createTrack_l() depending on the thread type
612 if (sampleRate == 0) {
613 ALOGE("createTrack() invalid sample rate %u", sampleRate);
614 lStatus = BAD_VALUE;
615 goto Exit;
616 }
617
618 // further channel mask checks are performed by createTrack_l() depending on the thread type
619 if (!audio_is_output_channel(channelMask)) {
620 ALOGE("createTrack() invalid channel mask %#x", channelMask);
621 lStatus = BAD_VALUE;
622 goto Exit;
623 }
624
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700625 // further format checks are performed by createTrack_l() depending on the thread type
626 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800627 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700628 lStatus = BAD_VALUE;
629 goto Exit;
630 }
631
Glenn Kasten663c2242013-09-24 11:52:37 -0700632 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
633 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
634 lStatus = BAD_VALUE;
635 goto Exit;
636 }
637
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 {
639 Mutex::Autolock _l(mLock);
640 PlaybackThread *thread = checkPlaybackThread_l(output);
641 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800642 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643 lStatus = BAD_VALUE;
644 goto Exit;
645 }
646
Eric Laurent021cf962014-05-13 10:18:14 -0700647 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648
Glenn Kastene848bd92014-03-13 15:00:32 -0700649 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700650 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800651 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
652 ALOGE("createTrack() invalid session ID %d", *sessionId);
653 lStatus = BAD_VALUE;
654 goto Exit;
655 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700656 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700657 // check if an effect chain with the same session ID is present on another
658 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700659 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700660 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
661 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700662 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700663 if (sessions & PlaybackThread::EFFECT_SESSION) {
664 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700665 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700666 }
Eric Laurentde070132010-07-13 04:45:46 -0700667 }
668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700670 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800671 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 if (sessionId != NULL) {
673 *sessionId = lSessionId;
674 }
675 }
Steve Block3856b092011-10-20 11:56:00 +0100676 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677
678 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800679 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800680 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700681 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700682
683 // move effect chain to this output thread if an effect on same session was waiting
684 // for a track to be created
685 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700686 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700687 Mutex::Autolock _dl(thread->mLock);
688 Mutex::Autolock _sl(effectThread->mLock);
689 moveEffectChain_l(lSessionId, effectThread, thread, true);
690 }
Eric Laurenta011e352012-03-29 15:51:43 -0700691
692 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700693 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700694 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
695 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700696 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700697 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700698 } else {
699 mPendingSyncEvents[i]->cancel();
700 }
Eric Laurenta011e352012-03-29 15:51:43 -0700701 mPendingSyncEvents.removeAt(i);
702 i--;
703 }
704 }
705 }
Glenn Kastene198c362013-08-13 09:13:36 -0700706
Glenn Kastend848eb42016-03-08 13:42:11 -0800707 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 }
Glenn Kastene198c362013-08-13 09:13:36 -0700709
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700710 if (lStatus != NO_ERROR) {
711 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700712 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700713 // Don't hold mClientLock when releasing the reference on the track as the
714 // destructor will acquire it.
715 {
716 Mutex::Autolock _cl(mClientLock);
717 client.clear();
718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700720 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 }
722
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700723 // return handle to client
724 trackHandle = new TrackHandle(track);
725
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700727 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 return trackHandle;
729}
730
Glenn Kasten2c073da2016-02-26 09:14:08 -0800731uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732{
733 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800734 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800736 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 return 0;
738 }
739 return thread->sampleRate();
740}
741
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800742audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743{
744 Mutex::Autolock _l(mLock);
745 PlaybackThread *thread = checkPlaybackThread_l(output);
746 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000747 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800748 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 }
750 return thread->format();
751}
752
Glenn Kasten2c073da2016-02-26 09:14:08 -0800753size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754{
755 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800756 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800758 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 return 0;
760 }
Glenn Kasten58912562012-04-03 10:45:00 -0700761 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
762 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 return thread->frameCount();
764}
765
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700766size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
767{
768 Mutex::Autolock _l(mLock);
769 ThreadBase *thread = checkThread_l(ioHandle);
770 if (thread == NULL) {
771 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
772 return 0;
773 }
774 return thread->frameCountHAL();
775}
776
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800777uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778{
779 Mutex::Autolock _l(mLock);
780 PlaybackThread *thread = checkPlaybackThread_l(output);
781 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800782 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 return 0;
784 }
785 return thread->latency();
786}
787
788status_t AudioFlinger::setMasterVolume(float value)
789{
Eric Laurenta1884f92011-08-23 08:25:03 -0700790 status_t ret = initCheck();
791 if (ret != NO_ERROR) {
792 return ret;
793 }
794
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 // check calling permissions
796 if (!settingsAllowed()) {
797 return PERMISSION_DENIED;
798 }
799
Eric Laurenta4c5a552012-03-29 10:12:40 -0700800 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700801 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700802
John Grossmanee578c02012-07-23 17:05:46 -0700803 // Set master volume in the HALs which support it.
804 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
805 AutoMutex lock(mHardwareLock);
806 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800807
John Grossmanee578c02012-07-23 17:05:46 -0700808 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
809 if (dev->canSetMasterVolume()) {
810 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800811 }
John Grossmanee578c02012-07-23 17:05:46 -0700812 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814
John Grossmanee578c02012-07-23 17:05:46 -0700815 // Now set the master volume in each playback thread. Playback threads
816 // assigned to HALs which do not have master volume support will apply
817 // master volume during the mix operation. Threads with HALs which do
818 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700819 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
820 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
821 continue;
822 }
John Grossmanee578c02012-07-23 17:05:46 -0700823 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825
826 return NO_ERROR;
827}
828
Glenn Kastenf78aee72012-01-04 11:00:47 -0800829status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830{
Eric Laurenta1884f92011-08-23 08:25:03 -0700831 status_t ret = initCheck();
832 if (ret != NO_ERROR) {
833 return ret;
834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835
836 // check calling permissions
837 if (!settingsAllowed()) {
838 return PERMISSION_DENIED;
839 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800840 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000841 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 return BAD_VALUE;
843 }
844
845 { // scope for the lock
846 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700847 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700849 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 mHardwareStatus = AUDIO_HW_IDLE;
851 }
852
853 if (NO_ERROR == ret) {
854 Mutex::Autolock _l(mLock);
855 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800856 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700857 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 }
859
860 return ret;
861}
862
863status_t AudioFlinger::setMicMute(bool state)
864{
Eric Laurenta1884f92011-08-23 08:25:03 -0700865 status_t ret = initCheck();
866 if (ret != NO_ERROR) {
867 return ret;
868 }
869
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 // check calling permissions
871 if (!settingsAllowed()) {
872 return PERMISSION_DENIED;
873 }
874
875 AutoMutex lock(mHardwareLock);
876 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700877 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
878 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
879 status_t result = dev->set_mic_mute(dev, state);
880 if (result != NO_ERROR) {
881 ret = result;
882 }
883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 mHardwareStatus = AUDIO_HW_IDLE;
885 return ret;
886}
887
888bool AudioFlinger::getMicMute() const
889{
Eric Laurenta1884f92011-08-23 08:25:03 -0700890 status_t ret = initCheck();
891 if (ret != NO_ERROR) {
892 return false;
893 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800894 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700895 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800896 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800898 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
899 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
900 status_t result = dev->get_mic_mute(dev, &state);
901 if (result == NO_ERROR) {
902 mute = mute && state;
903 }
904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700905 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800906
907 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700908}
909
910status_t AudioFlinger::setMasterMute(bool muted)
911{
John Grossmand8f178d2012-07-20 14:51:35 -0700912 status_t ret = initCheck();
913 if (ret != NO_ERROR) {
914 return ret;
915 }
916
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917 // check calling permissions
918 if (!settingsAllowed()) {
919 return PERMISSION_DENIED;
920 }
921
John Grossmanee578c02012-07-23 17:05:46 -0700922 Mutex::Autolock _l(mLock);
923 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700924
John Grossmanee578c02012-07-23 17:05:46 -0700925 // Set master mute in the HALs which support it.
926 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
927 AutoMutex lock(mHardwareLock);
928 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700929
John Grossmanee578c02012-07-23 17:05:46 -0700930 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
931 if (dev->canSetMasterMute()) {
932 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700933 }
John Grossmanee578c02012-07-23 17:05:46 -0700934 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700935 }
936
John Grossmanee578c02012-07-23 17:05:46 -0700937 // Now set the master mute in each playback thread. Playback threads
938 // assigned to HALs which do not have master mute support will apply master
939 // mute during the mix operation. Threads with HALs which do support master
940 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700941 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
942 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
943 continue;
944 }
John Grossmanee578c02012-07-23 17:05:46 -0700945 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947
948 return NO_ERROR;
949}
950
951float AudioFlinger::masterVolume() const
952{
Glenn Kasten98067102011-12-13 11:47:54 -0800953 Mutex::Autolock _l(mLock);
954 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955}
956
957bool AudioFlinger::masterMute() const
958{
Glenn Kasten98067102011-12-13 11:47:54 -0800959 Mutex::Autolock _l(mLock);
960 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961}
962
John Grossman4ff14ba2012-02-08 16:37:41 -0800963float AudioFlinger::masterVolume_l() const
964{
John Grossman4ff14ba2012-02-08 16:37:41 -0800965 return mMasterVolume;
966}
967
John Grossmand8f178d2012-07-20 14:51:35 -0700968bool AudioFlinger::masterMute_l() const
969{
John Grossmanee578c02012-07-23 17:05:46 -0700970 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700971}
972
Eric Laurent223fd5c2014-11-11 13:43:36 -0800973status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
974{
975 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
976 ALOGW("setStreamVolume() invalid stream %d", stream);
977 return BAD_VALUE;
978 }
979 pid_t caller = IPCThreadState::self()->getCallingPid();
980 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
981 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
982 return PERMISSION_DENIED;
983 }
984
985 return NO_ERROR;
986}
987
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800988status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
989 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990{
991 // check calling permissions
992 if (!settingsAllowed()) {
993 return PERMISSION_DENIED;
994 }
995
Eric Laurent223fd5c2014-11-11 13:43:36 -0800996 status_t status = checkStreamType(stream);
997 if (status != NO_ERROR) {
998 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001000 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001
1002 AutoMutex lock(mLock);
1003 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -07001004 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005 thread = checkPlaybackThread_l(output);
1006 if (thread == NULL) {
1007 return BAD_VALUE;
1008 }
1009 }
1010
1011 mStreamTypes[stream].volume = value;
1012
1013 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001014 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001015 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 }
1017 } else {
1018 thread->setStreamVolume(stream, value);
1019 }
1020
1021 return NO_ERROR;
1022}
1023
Glenn Kastenfff6d712012-01-12 16:38:12 -08001024status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025{
1026 // check calling permissions
1027 if (!settingsAllowed()) {
1028 return PERMISSION_DENIED;
1029 }
1030
Eric Laurent223fd5c2014-11-11 13:43:36 -08001031 status_t status = checkStreamType(stream);
1032 if (status != NO_ERROR) {
1033 return status;
1034 }
1035 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1036
1037 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001038 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 return BAD_VALUE;
1040 }
1041
Eric Laurent93575202011-01-18 18:39:02 -08001042 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001044 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001045 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046
1047 return NO_ERROR;
1048}
1049
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001050float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001052 status_t status = checkStreamType(stream);
1053 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 return 0.0f;
1055 }
1056
1057 AutoMutex lock(mLock);
1058 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001059 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 PlaybackThread *thread = checkPlaybackThread_l(output);
1061 if (thread == NULL) {
1062 return 0.0f;
1063 }
1064 volume = thread->streamVolume(stream);
1065 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001066 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
1069 return volume;
1070}
1071
Glenn Kastenfff6d712012-01-12 16:38:12 -08001072bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001074 status_t status = checkStreamType(stream);
1075 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 return true;
1077 }
1078
Glenn Kasten6637baa2012-01-09 09:40:36 -08001079 AutoMutex lock(mLock);
1080 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081}
1082
Eric Laurent054d9d32015-04-24 08:48:48 -07001083
1084void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1085{
1086 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1087 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1088 }
1089}
1090
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001091status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001093 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1094 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001095
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 // check calling permissions
1097 if (!settingsAllowed()) {
1098 return PERMISSION_DENIED;
1099 }
1100
Glenn Kasten142f5192014-03-25 17:44:59 -07001101 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1102 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001103 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001104 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001105 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001106 AutoMutex lock(mHardwareLock);
1107 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1108 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1109 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1110 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1111 final_result = result ?: final_result;
1112 }
1113 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001114 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001115 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1116 AudioParameter param = AudioParameter(keyValuePairs);
1117 String8 value;
1118 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001119 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1120 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001121 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1122 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001123 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001124 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1125 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001126 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001127 // suspend effects associated with those session IDs
1128 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001129 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001130 thread->setEffectSuspended(FX_IID_AEC,
1131 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001132 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001133 thread->setEffectSuspended(FX_IID_NS,
1134 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001135 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001136 }
1137 }
Eric Laurentbee53372011-08-29 12:42:48 -07001138 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001139 }
1140 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001141 String8 screenState;
1142 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1143 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001144 if (isOff != (AudioFlinger::mScreenState & 1)) {
1145 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001146 }
1147 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001148 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149 }
1150
1151 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1152 // and the thread is exited once the lock is released
1153 sp<ThreadBase> thread;
1154 {
1155 Mutex::Autolock _l(mLock);
1156 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001157 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001159 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001160 // indicate output device change to all input threads for pre processing
1161 AudioParameter param = AudioParameter(keyValuePairs);
1162 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001163 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1164 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001165 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 }
1168 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001169 if (thread != 0) {
1170 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 }
1172 return BAD_VALUE;
1173}
1174
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001175String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001177 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1178 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179
Eric Laurenta4c5a552012-03-29 10:12:40 -07001180 Mutex::Autolock _l(mLock);
1181
Glenn Kasten142f5192014-03-25 17:44:59 -07001182 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001183 String8 out_s8;
1184
Dima Zavin799a70e2011-04-18 16:57:27 -07001185 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001186 char *s;
1187 {
1188 AutoMutex lock(mHardwareLock);
1189 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001190 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001191 s = dev->get_parameters(dev, keys.string());
1192 mHardwareStatus = AUDIO_HW_IDLE;
1193 }
John Grossmanef7740b2012-02-09 11:28:36 -08001194 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001195 free(s);
1196 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001197 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 }
1199
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1201 if (playbackThread != NULL) {
1202 return playbackThread->getParameters(keys);
1203 }
1204 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1205 if (recordThread != NULL) {
1206 return recordThread->getParameters(keys);
1207 }
1208 return String8("");
1209}
1210
Glenn Kastendd8104c2012-07-02 12:42:44 -07001211size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1212 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213{
Eric Laurenta1884f92011-08-23 08:25:03 -07001214 status_t ret = initCheck();
1215 if (ret != NO_ERROR) {
1216 return 0;
1217 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001218 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001219 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001220 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001221 return 0;
1222 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001223
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001224 AutoMutex lock(mHardwareLock);
1225 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001226 audio_config_t config, proposed;
1227 memset(&proposed, 0, sizeof(proposed));
1228 proposed.sample_rate = sampleRate;
1229 proposed.channel_mask = channelMask;
1230 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001231
John Grossmanee578c02012-07-23 17:05:46 -07001232 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001233 size_t frames;
1234 for (;;) {
1235 // Note: config is currently a const parameter for get_input_buffer_size()
1236 // but we use a copy from proposed in case config changes from the call.
1237 config = proposed;
1238 frames = dev->get_input_buffer_size(dev, &config);
1239 if (frames != 0) {
1240 break; // hal success, config is the result
1241 }
1242 // change one parameter of the configuration each iteration to a more "common" value
1243 // to see if the device will support it.
1244 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1245 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1246 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1247 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1248 } else {
1249 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1250 "format %#x, channelMask 0x%X",
1251 sampleRate, format, channelMask);
1252 break; // retries failed, break out of loop with frames == 0.
1253 }
1254 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001255 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001256 if (frames > 0 && config.sample_rate != sampleRate) {
1257 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1258 }
1259 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260}
1261
Glenn Kasten5f972c02014-01-13 09:59:31 -08001262uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 Mutex::Autolock _l(mLock);
1265
1266 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1267 if (recordThread != NULL) {
1268 return recordThread->getInputFramesLost();
1269 }
1270 return 0;
1271}
1272
1273status_t AudioFlinger::setVoiceVolume(float value)
1274{
Eric Laurenta1884f92011-08-23 08:25:03 -07001275 status_t ret = initCheck();
1276 if (ret != NO_ERROR) {
1277 return ret;
1278 }
1279
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 // check calling permissions
1281 if (!settingsAllowed()) {
1282 return PERMISSION_DENIED;
1283 }
1284
1285 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001286 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001287 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001288 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 mHardwareStatus = AUDIO_HW_IDLE;
1290
1291 return ret;
1292}
1293
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001294status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001295 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 Mutex::Autolock _l(mLock);
1298
1299 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1300 if (playbackThread != NULL) {
1301 return playbackThread->getRenderPosition(halFrames, dspFrames);
1302 }
1303
1304 return BAD_VALUE;
1305}
1306
1307void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1308{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001310 if (client == 0) {
1311 return;
1312 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001313 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001314 {
1315 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001316 if (mNotificationClients.indexOfKey(pid) < 0) {
1317 sp<NotificationClient> notificationClient = new NotificationClient(this,
1318 client,
1319 pid);
1320 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001321
Eric Laurent021cf962014-05-13 10:18:14 -07001322 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323
Marco Nelissen06b46062014-11-14 07:58:25 -08001324 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001325 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001326 }
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328
Eric Laurent021cf962014-05-13 10:18:14 -07001329 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001330 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001331 // the config change is always sent from playback or record threads to avoid deadlock
1332 // with AudioSystem::gLock
1333 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1334 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001337 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1338 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 }
1340}
1341
1342void AudioFlinger::removeNotificationClient(pid_t pid)
1343{
1344 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001345 {
1346 Mutex::Autolock _cl(mClientLock);
1347 mNotificationClients.removeItem(pid);
1348 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001349
Steve Block3856b092011-10-20 11:56:00 +01001350 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001351 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001352 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001353 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001354 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001355 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001356 if (ref->mPid == pid) {
1357 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001358 mAudioSessionRefs.removeAt(i);
1359 delete ref;
1360 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001361 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001362 } else {
1363 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001364 }
1365 }
1366 if (removed) {
1367 purgeStaleEffects_l();
1368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369}
1370
Eric Laurent73e26b62015-04-27 16:55:58 -07001371void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372 const sp<AudioIoDescriptor>& ioDesc,
1373 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurent021cf962014-05-13 10:18:14 -07001375 Mutex::Autolock _l(mClientLock);
1376 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001378 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1379 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 }
1382}
1383
Eric Laurent021cf962014-05-13 10:18:14 -07001384// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385void AudioFlinger::removeClient_l(pid_t pid)
1386{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001387 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001388 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 mClients.removeItem(pid);
1390}
1391
Eric Laurent717e1282012-06-29 16:36:52 -07001392// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001393sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1394 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001395{
1396 sp<PlaybackThread> thread;
1397
1398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1399 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1400 ALOG_ASSERT(thread == 0);
1401 thread = mPlaybackThreads.valueAt(i);
1402 }
1403 }
1404
1405 return thread;
1406}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409
1410// ----------------------------------------------------------------------------
1411
1412AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1413 : RefBase(),
1414 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001415 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416{
Eric Laurentda73b6c2015-08-20 16:18:53 -07001417 size_t heapSize = kClientSharedHeapSizeBytes;
1418 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1419 // invalidated tracks
1420 if (!audioFlinger->isLowRamDevice()) {
1421 heapSize *= kClientSharedHeapSizeMultiplier;
1422 }
1423 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424}
1425
Eric Laurent021cf962014-05-13 10:18:14 -07001426// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427AudioFlinger::Client::~Client()
1428{
1429 mAudioFlinger->removeClient_l(mPid);
1430}
1431
Glenn Kasten435dbe62012-01-30 10:15:48 -08001432sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433{
1434 return mMemoryDealer;
1435}
1436
1437// ----------------------------------------------------------------------------
1438
1439AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1440 const sp<IAudioFlingerClient>& client,
1441 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001442 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443{
1444}
1445
1446AudioFlinger::NotificationClient::~NotificationClient()
1447{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448}
1449
Glenn Kasten0f11b512014-01-31 16:18:54 -08001450void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451{
1452 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001453 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454}
1455
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456
1457// ----------------------------------------------------------------------------
1458
1459sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001460 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001461 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001462 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001463 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001464 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001465 size_t *frameCount,
Glenn Kasteneeca3262013-07-31 16:12:48 -07001466 IAudioFlinger::track_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001467 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001468 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001469 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001470 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001471 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001472 sp<IMemory>& cblk,
1473 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 status_t *status)
1475{
1476 sp<RecordThread::RecordTrack> recordTrack;
1477 sp<RecordHandle> recordHandle;
1478 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001480 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481
Glenn Kastend776ac62014-05-07 09:16:09 -07001482 cblk.clear();
1483 buffers.clear();
1484
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001485 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001486 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1487 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001488 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001489 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1490 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001491 updatePid = true;
1492 }
1493
1494 if (updatePid) {
1495 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1496 ALOGW_IF(pid != -1 && pid != callingPid,
1497 "%s uid %d pid %d tried to pass itself off as pid %d",
1498 __func__, callingUid, callingPid, pid);
1499 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001500 }
1501
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001503 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001504 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 lStatus = PERMISSION_DENIED;
1506 goto Exit;
1507 }
1508
Glenn Kasten53b5d092014-02-05 10:00:23 -08001509 // further sample rate checks are performed by createRecordTrack_l()
1510 if (sampleRate == 0) {
1511 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1512 lStatus = BAD_VALUE;
1513 goto Exit;
1514 }
1515
Andy Hung6770c6f2015-04-07 13:43:36 -07001516 // we don't yet support anything other than linear PCM
1517 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001518 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522
Glenn Kasten53b5d092014-02-05 10:00:23 -08001523 // further channel mask checks are performed by createRecordTrack_l()
1524 if (!audio_is_input_channel(channelMask)) {
1525 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1526 lStatus = BAD_VALUE;
1527 goto Exit;
1528 }
1529
Glenn Kasten05997e22014-03-13 15:08:33 -07001530 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001532 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001534 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 lStatus = BAD_VALUE;
1536 goto Exit;
1537 }
1538
Eric Laurent021cf962014-05-13 10:18:14 -07001539 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001541 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001542 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1543 lStatus = BAD_VALUE;
1544 goto Exit;
1545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 lSessionId = *sessionId;
1547 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001548 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001549 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 if (sessionId != NULL) {
1551 *sessionId = lSessionId;
1552 }
1553 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001554 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001555
Glenn Kasten1879fff2012-07-11 15:36:59 -07001556 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001557 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001558 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001559 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001560
1561 if (lStatus == NO_ERROR) {
1562 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1563 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001564 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001565 if (chain != 0) {
1566 Mutex::Autolock _l(thread->mLock);
1567 thread->addEffectChain_l(chain);
1568 }
1569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 }
Glenn Kastene198c362013-08-13 09:13:36 -07001571
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001572 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001573 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001574 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001575 // Don't hold mClientLock when releasing the reference on the track as the
1576 // destructor will acquire it.
1577 {
1578 Mutex::Autolock _cl(mClientLock);
1579 client.clear();
1580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 goto Exit;
1583 }
1584
Glenn Kastend776ac62014-05-07 09:16:09 -07001585 cblk = recordTrack->getCblk();
1586 buffers = recordTrack->getBuffers();
1587
Glenn Kasten2fc14732013-08-05 14:58:14 -07001588 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590
1591Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001592 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 return recordHandle;
1594}
1595
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001596
1597
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598// ----------------------------------------------------------------------------
1599
Eric Laurenta4c5a552012-03-29 10:12:40 -07001600audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1601{
Eric Laurent44622db2014-08-01 19:00:33 -07001602 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001603 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001604 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001605 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001606 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001607 }
1608 Mutex::Autolock _l(mLock);
1609 return loadHwModule_l(name);
1610}
1611
1612// loadHwModule_l() must be called with AudioFlinger::mLock held
1613audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1614{
1615 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1616 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1617 ALOGW("loadHwModule() module %s already loaded", name);
1618 return mAudioHwDevs.keyAt(i);
1619 }
1620 }
1621
Eric Laurenta4c5a552012-03-29 10:12:40 -07001622 audio_hw_device_t *dev;
1623
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001624 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001625 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001626 ALOGE("loadHwModule() error %d loading 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
1630 mHardwareStatus = AUDIO_HW_INIT;
1631 rc = dev->init_check(dev);
1632 mHardwareStatus = AUDIO_HW_IDLE;
1633 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001634 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001635 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001636 }
1637
John Grossmanee578c02012-07-23 17:05:46 -07001638 // Check and cache this HAL's level of support for master mute and master
1639 // volume. If this is the first HAL opened, and it supports the get
1640 // methods, use the initial values provided by the HAL as the current
1641 // master mute and volume settings.
1642
1643 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1644 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001645 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001646
1647 if (0 == mAudioHwDevs.size()) {
1648 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1649 if (NULL != dev->get_master_volume) {
1650 float mv;
1651 if (OK == dev->get_master_volume(dev, &mv)) {
1652 mMasterVolume = mv;
1653 }
1654 }
1655
1656 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1657 if (NULL != dev->get_master_mute) {
1658 bool mm;
1659 if (OK == dev->get_master_mute(dev, &mm)) {
1660 mMasterMute = mm;
1661 }
1662 }
1663 }
1664
Eric Laurenta4c5a552012-03-29 10:12:40 -07001665 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001666 if ((NULL != dev->set_master_volume) &&
1667 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1668 flags = static_cast<AudioHwDevice::Flags>(flags |
1669 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1670 }
1671
1672 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1673 if ((NULL != dev->set_master_mute) &&
1674 (OK == dev->set_master_mute(dev, mMasterMute))) {
1675 flags = static_cast<AudioHwDevice::Flags>(flags |
1676 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1677 }
1678
Eric Laurenta4c5a552012-03-29 10:12:40 -07001679 mHardwareStatus = AUDIO_HW_IDLE;
1680 }
1681
Glenn Kastena13cde92016-03-28 15:26:02 -07001682 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001683 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001684
1685 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001686 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001687
1688 return handle;
1689
1690}
1691
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001692// ----------------------------------------------------------------------------
1693
Glenn Kasten3b16c762012-11-14 08:44:39 -08001694uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001695{
1696 Mutex::Autolock _l(mLock);
1697 PlaybackThread *thread = primaryPlaybackThread_l();
1698 return thread != NULL ? thread->sampleRate() : 0;
1699}
1700
Glenn Kastene33054e2012-11-14 12:54:39 -08001701size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001702{
1703 Mutex::Autolock _l(mLock);
1704 PlaybackThread *thread = primaryPlaybackThread_l();
1705 return thread != NULL ? thread->frameCountHAL() : 0;
1706}
1707
1708// ----------------------------------------------------------------------------
1709
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001710status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1711{
1712 uid_t uid = IPCThreadState::self()->getCallingUid();
1713 if (uid != AID_SYSTEM) {
1714 return PERMISSION_DENIED;
1715 }
1716 Mutex::Autolock _l(mLock);
1717 if (mIsDeviceTypeKnown) {
1718 return INVALID_OPERATION;
1719 }
1720 mIsLowRamDevice = isLowRamDevice;
1721 mIsDeviceTypeKnown = true;
1722 return NO_ERROR;
1723}
1724
Eric Laurent93c3d412014-08-01 14:48:35 -07001725audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1726{
1727 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001728
1729 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1730 if (index >= 0) {
1731 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1732 mHwAvSyncIds.valueAt(index), sessionId);
1733 return mHwAvSyncIds.valueAt(index);
1734 }
1735
1736 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1737 if (dev == NULL) {
1738 return AUDIO_HW_SYNC_INVALID;
1739 }
1740 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1741 AudioParameter param = AudioParameter(String8(reply));
1742 free(reply);
1743
1744 int value;
1745 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1746 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1747 return AUDIO_HW_SYNC_INVALID;
1748 }
1749
1750 // allow only one session for a given HW A/V sync ID.
1751 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1752 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1753 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1754 value, mHwAvSyncIds.keyAt(i));
1755 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001756 break;
1757 }
1758 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001759
1760 mHwAvSyncIds.add(sessionId, value);
1761
1762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1763 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1764 uint32_t sessions = thread->hasAudioSession(sessionId);
1765 if (sessions & PlaybackThread::TRACK_SESSION) {
1766 AudioParameter param = AudioParameter();
1767 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1768 thread->setParameters(param.toString());
1769 break;
1770 }
1771 }
1772
1773 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1774 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001775}
1776
Eric Laurent72e3f392015-05-20 14:43:50 -07001777status_t AudioFlinger::systemReady()
1778{
1779 Mutex::Autolock _l(mLock);
1780 ALOGI("%s", __FUNCTION__);
1781 if (mSystemReady) {
1782 ALOGW("%s called twice", __FUNCTION__);
1783 return NO_ERROR;
1784 }
1785 mSystemReady = true;
1786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1787 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1788 thread->systemReady();
1789 }
1790 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1791 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1792 thread->systemReady();
1793 }
1794 return NO_ERROR;
1795}
1796
Eric Laurentfa90e842014-10-17 18:12:31 -07001797// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1798void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1799{
1800 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1801 if (index >= 0) {
1802 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1803 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1804 AudioParameter param = AudioParameter();
1805 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1806 thread->setParameters(param.toString());
1807 }
1808}
1809
1810
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001811// ----------------------------------------------------------------------------
1812
Eric Laurent83b88082014-06-20 18:31:16 -07001813
1814sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001815 audio_io_handle_t *output,
1816 audio_config_t *config,
1817 audio_devices_t devices,
1818 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001819 audio_output_flags_t flags)
1820{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001821 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001822 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001823 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001824 }
1825
Eric Laurentcf2c0212014-07-25 16:20:43 -07001826 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001827 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1828 } else {
1829 // Audio Policy does not currently request a specific output handle.
1830 // If this is ever needed, see openInput_l() for example code.
1831 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1832 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001833 }
Eric Laurent83b88082014-06-20 18:31:16 -07001834
1835 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1836
Eric Laurent83b88082014-06-20 18:31:16 -07001837 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001838 // This if statement allows overriding the audio policy settings
1839 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1840 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1841 // Check only for Normal Mixing mode
1842 if (kEnableExtendedPrecision) {
1843 // Specify format (uncomment one below to choose)
1844 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1845 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1846 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1847 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001848 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001849 }
1850 if (kEnableExtendedChannels) {
1851 // Specify channel mask (uncomment one below to choose)
1852 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1853 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1854 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1855 }
Eric Laurent83b88082014-06-20 18:31:16 -07001856 }
1857
Phil Burk062e67a2015-02-11 13:40:50 -08001858 AudioStreamOut *outputStream = NULL;
1859 status_t status = outHwDev->openOutputStream(
1860 &outputStream,
1861 *output,
1862 devices,
1863 flags,
1864 config,
1865 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001866
1867 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001868
Phil Burk062e67a2015-02-11 13:40:50 -08001869 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001870
1871 PlaybackThread *thread;
1872 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001873 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001874 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001875 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1876 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001877 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001878 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001879 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001880 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001881 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001883 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001884 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001885 return thread;
1886 }
1887
1888 return 0;
1889}
1890
Eric Laurentcf2c0212014-07-25 16:20:43 -07001891status_t AudioFlinger::openOutput(audio_module_handle_t module,
1892 audio_io_handle_t *output,
1893 audio_config_t *config,
1894 audio_devices_t *devices,
1895 const String8& address,
1896 uint32_t *latencyMs,
1897 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898{
Phil Burk062e67a2015-02-11 13:40:50 -08001899 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001900 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001901 (devices != NULL) ? *devices : 0,
1902 config->sample_rate,
1903 config->format,
1904 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001905 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906
Eric Laurentcf2c0212014-07-25 16:20:43 -07001907 if (*devices == AUDIO_DEVICE_NONE) {
1908 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001910
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911 Mutex::Autolock _l(mLock);
1912
Eric Laurentcf2c0212014-07-25 16:20:43 -07001913 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001914 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001915 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
1917 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001918 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001919
1920 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001921 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001922 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001923 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001924
1925 AutoMutex lock(mHardwareLock);
1926 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001927 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001928 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001929 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001930 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 }
1932
Eric Laurentcf2c0212014-07-25 16:20:43 -07001933 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934}
1935
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001936audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1937 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938{
1939 Mutex::Autolock _l(mLock);
1940 MixerThread *thread1 = checkMixerThread_l(output1);
1941 MixerThread *thread2 = checkMixerThread_l(output2);
1942
1943 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001944 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1945 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001946 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 }
1948
Glenn Kasteneeecb982016-02-26 10:44:04 -08001949 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001950 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 thread->addOutputTrack(thread2);
1952 mPlaybackThreads.add(id, thread);
1953 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001954 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 return id;
1956}
1957
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001958status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959{
Glenn Kastend96c5722012-04-25 13:44:49 -07001960 return closeOutput_nonvirtual(output);
1961}
1962
1963status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1964{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 // keep strong reference on the playback thread so that
1966 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001967 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 {
1969 Mutex::Autolock _l(mLock);
1970 thread = checkPlaybackThread_l(output);
1971 if (thread == NULL) {
1972 return BAD_VALUE;
1973 }
1974
Steve Block3856b092011-10-20 11:56:00 +01001975 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001977 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001979 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001980 DuplicatingThread *dupThread =
1981 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001983 }
1984 }
1985 }
1986
1987
1988 mPlaybackThreads.removeItem(output);
1989 // save all effects to the default thread
1990 if (mPlaybackThreads.size()) {
1991 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1992 if (dstThread != NULL) {
1993 // audioflinger lock is held here so the acquisition order of thread locks does not
1994 // matter
1995 Mutex::Autolock _dl(dstThread->mLock);
1996 Mutex::Autolock _sl(thread->mLock);
1997 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1998 for (size_t i = 0; i < effectChains.size(); i ++) {
1999 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 }
2001 }
2002 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002003 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2004 ioDesc->mIoHandle = output;
2005 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 }
2007 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08002008 // The thread entity (active unit of execution) is no longer running here,
2009 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
Eric Laurentf6870ae2015-05-08 10:50:03 -07002011 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07002012 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
Eric Laurent83b88082014-06-20 18:31:16 -07002014
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 return NO_ERROR;
2016}
2017
Eric Laurent83b88082014-06-20 18:31:16 -07002018void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
2019{
2020 AudioStreamOut *out = thread->clearOutput();
2021 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2022 // from now on thread->mOutput is NULL
2023 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
2024 delete out;
2025}
2026
2027void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
2028{
2029 mPlaybackThreads.removeItem(thread->mId);
2030 thread->exit();
2031 closeOutputFinish(thread);
2032}
2033
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002034status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035{
2036 Mutex::Autolock _l(mLock);
2037 PlaybackThread *thread = checkPlaybackThread_l(output);
2038
2039 if (thread == NULL) {
2040 return BAD_VALUE;
2041 }
2042
Steve Block3856b092011-10-20 11:56:00 +01002043 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 thread->suspend();
2045
2046 return NO_ERROR;
2047}
2048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002049status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050{
2051 Mutex::Autolock _l(mLock);
2052 PlaybackThread *thread = checkPlaybackThread_l(output);
2053
2054 if (thread == NULL) {
2055 return BAD_VALUE;
2056 }
2057
Steve Block3856b092011-10-20 11:56:00 +01002058 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059
2060 thread->restore();
2061
2062 return NO_ERROR;
2063}
2064
Eric Laurentcf2c0212014-07-25 16:20:43 -07002065status_t AudioFlinger::openInput(audio_module_handle_t module,
2066 audio_io_handle_t *input,
2067 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002068 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002069 const String8& address,
2070 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002071 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072{
Eric Laurent83b88082014-06-20 18:31:16 -07002073 Mutex::Autolock _l(mLock);
2074
Glenn Kastene7d66712015-03-05 13:46:52 -08002075 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002076 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002077 }
2078
Glenn Kastene7d66712015-03-05 13:46:52 -08002079 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002080
2081 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002082 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002083 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002084 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002087}
Dima Zavin799a70e2011-04-18 16:57:27 -07002088
Eric Laurent83b88082014-06-20 18:31:16 -07002089sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002090 audio_io_handle_t *input,
2091 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002092 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002093 const String8& address,
2094 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002095 audio_input_flags_t flags)
2096{
Glenn Kastene7d66712015-03-05 13:46:52 -08002097 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002098 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002099 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002100 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002101 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002102
Glenn Kasteneeecb982016-02-26 10:44:04 -08002103 // Audio Policy can request a specific handle for hardware hotword.
2104 // The goal here is not to re-open an already opened input.
2105 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002107 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2108 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2109 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2110 return 0;
2111 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2112 // This should not happen in a transient state with current design.
2113 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2114 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002115 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002116
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 audio_config_t halconfig = *config;
2118 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002119 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002120 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002121 &inStream, flags, address.string(), source);
2122 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002123 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002124 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002125 halconfig.sample_rate,
2126 halconfig.format,
2127 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002128 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002129 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002131 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002132 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002133 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002134 audio_is_linear_pcm(config->format) &&
2135 audio_is_linear_pcm(halconfig.format) &&
2136 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002137 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2138 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002139 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002141 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002142 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002143 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002144 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145 }
2146
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002147 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002148
Glenn Kasten46909e72013-02-26 09:20:22 -08002149#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002150 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2151 // or (re-)create if current Pipe is idle and does not match the new format
2152 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002153 enum {
2154 TEE_SINK_NO, // don't copy input
2155 TEE_SINK_NEW, // copy input using a new pipe
2156 TEE_SINK_OLD, // copy input using an existing pipe
2157 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002158 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2159 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002160 if (!mTeeSinkInputEnabled) {
2161 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002162 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002163 kind = TEE_SINK_NO;
2164 } else if (mRecordTeeSink == 0) {
2165 kind = TEE_SINK_NEW;
2166 } else if (mRecordTeeSink->getStrongCount() != 1) {
2167 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002168 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002169 kind = TEE_SINK_OLD;
2170 } else {
2171 kind = TEE_SINK_NEW;
2172 }
2173 switch (kind) {
2174 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002175 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002176 size_t numCounterOffers = 0;
2177 const NBAIO_Format offers[1] = {format};
2178 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2179 ALOG_ASSERT(index == 0);
2180 PipeReader *pipeReader = new PipeReader(*pipe);
2181 numCounterOffers = 0;
2182 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2183 ALOG_ASSERT(index == 0);
2184 mRecordTeeSink = pipe;
2185 mRecordTeeSource = pipeReader;
2186 teeSink = pipe;
2187 }
2188 break;
2189 case TEE_SINK_OLD:
2190 teeSink = mRecordTeeSink;
2191 break;
2192 case TEE_SINK_NO:
2193 default:
2194 break;
2195 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002196#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002197
Eric Laurentcf2c0212014-07-25 16:20:43 -07002198 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002199
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002200 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002201 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002202 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002203 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002204 inputStream,
2205 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002206 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002207 devices,
2208 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002209#ifdef TEE_SINK
2210 , teeSink
2211#endif
2212 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002213 mRecordThreads.add(*input, thread);
2214 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002215 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216 }
2217
Eric Laurentcf2c0212014-07-25 16:20:43 -07002218 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 return 0;
2220}
2221
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002222status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223{
Glenn Kastend96c5722012-04-25 13:44:49 -07002224 return closeInput_nonvirtual(input);
2225}
2226
2227status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2228{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 // keep strong reference on the record thread so that
2230 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002231 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 {
2233 Mutex::Autolock _l(mLock);
2234 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002235 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236 return BAD_VALUE;
2237 }
2238
Steve Block3856b092011-10-20 11:56:00 +01002239 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002240
2241 // If we still have effect chains, it means that a client still holds a handle
2242 // on at least one effect. We must either move the chain to an existing thread with the
2243 // same session ID or put it aside in case a new record thread is opened for a
2244 // new capture on the same session
2245 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002246 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002247 Mutex::Autolock _sl(thread->mLock);
2248 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002249 // Note: maximum one chain per record thread
2250 if (effectChains.size() != 0) {
2251 chain = effectChains[0];
2252 }
2253 }
2254 if (chain != 0) {
2255 // first check if a record thread is already opened with a client on the same session.
2256 // This should only happen in case of overlap between one thread tear down and the
2257 // creation of its replacement
2258 size_t i;
2259 for (i = 0; i < mRecordThreads.size(); i++) {
2260 sp<RecordThread> t = mRecordThreads.valueAt(i);
2261 if (t == thread) {
2262 continue;
2263 }
2264 if (t->hasAudioSession(chain->sessionId()) != 0) {
2265 Mutex::Autolock _l(t->mLock);
2266 ALOGV("closeInput() found thread %d for effect session %d",
2267 t->id(), chain->sessionId());
2268 t->addEffectChain_l(chain);
2269 break;
2270 }
2271 }
2272 // put the chain aside if we could not find a record thread with the same session id.
2273 if (i == mRecordThreads.size()) {
2274 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002275 }
2276 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002277 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2278 ioDesc->mIoHandle = input;
2279 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 mRecordThreads.removeItem(input);
2281 }
Eric Laurent83b88082014-06-20 18:31:16 -07002282 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2283 // we have a different lock for notification client
2284 closeInputFinish(thread);
2285 return NO_ERROR;
2286}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287
Eric Laurent83b88082014-06-20 18:31:16 -07002288void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2289{
2290 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002291 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002292 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002293 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002294 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002295 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002296}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297
Eric Laurent83b88082014-06-20 18:31:16 -07002298void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2299{
2300 mRecordThreads.removeItem(thread->mId);
2301 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302}
2303
Glenn Kastend2304db2014-02-03 07:40:31 -08002304status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305{
2306 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002307 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308
2309 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2310 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002311 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313
2314 return NO_ERROR;
2315}
2316
2317
Glenn Kasteneeecb982016-02-26 10:44:04 -08002318audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319{
Glenn Kasten9d003132016-04-06 14:38:09 -07002320 // This is a binder API, so a malicious client could pass in a bad parameter.
2321 // Check for that before calling the internal API nextUniqueId().
2322 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2323 ALOGE("newAudioUniqueId invalid use %d", use);
2324 return AUDIO_UNIQUE_ID_ALLOCATE;
2325 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002326 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327}
2328
Glenn Kastend848eb42016-03-08 13:42:11 -08002329void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002330{
2331 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002332 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002333 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2334 if (pid != -1 && (caller == getpid_cached)) {
2335 caller = pid;
2336 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002337
Eric Laurent021cf962014-05-13 10:18:14 -07002338 {
2339 Mutex::Autolock _cl(mClientLock);
2340 // Ignore requests received from processes not known as notification client. The request
2341 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2342 // called from a different pid leaving a stale session reference. Also we don't know how
2343 // to clear this reference if the client process dies.
2344 if (mNotificationClients.indexOfKey(caller) < 0) {
2345 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2346 return;
2347 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002348 }
2349
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002350 size_t num = mAudioSessionRefs.size();
2351 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002352 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002353 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2354 ref->mCnt++;
2355 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002356 return;
2357 }
2358 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002359 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2360 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002361}
2362
Glenn Kastend848eb42016-03-08 13:42:11 -08002363void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002364{
2365 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002366 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002367 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2368 if (pid != -1 && (caller == getpid_cached)) {
2369 caller = pid;
2370 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002371 size_t num = mAudioSessionRefs.size();
2372 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002373 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002374 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2375 ref->mCnt--;
2376 ALOGV(" decremented refcount to %d", ref->mCnt);
2377 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002378 mAudioSessionRefs.removeAt(i);
2379 delete ref;
2380 purgeStaleEffects_l();
2381 }
2382 return;
2383 }
2384 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002385 // If the caller is mediaserver it is likely that the session being released was acquired
2386 // on behalf of a process not in notification clients and we ignore the warning.
2387 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002388}
2389
2390void AudioFlinger::purgeStaleEffects_l() {
2391
Steve Block3856b092011-10-20 11:56:00 +01002392 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002393
2394 Vector< sp<EffectChain> > chains;
2395
2396 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2397 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2398 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2399 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002400 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2401 chains.push(ec);
2402 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002403 }
2404 }
2405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2406 sp<RecordThread> t = mRecordThreads.valueAt(i);
2407 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2408 sp<EffectChain> ec = t->mEffectChains[j];
2409 chains.push(ec);
2410 }
2411 }
2412
2413 for (size_t i = 0; i < chains.size(); i++) {
2414 sp<EffectChain> ec = chains[i];
2415 int sessionid = ec->sessionId();
2416 sp<ThreadBase> t = ec->mThread.promote();
2417 if (t == 0) {
2418 continue;
2419 }
2420 size_t numsessionrefs = mAudioSessionRefs.size();
2421 bool found = false;
2422 for (size_t k = 0; k < numsessionrefs; k++) {
2423 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002424 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002425 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002426 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002427 found = true;
2428 break;
2429 }
2430 }
2431 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002432 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002433 // remove all effects from the chain
2434 while (ec->mEffects.size()) {
2435 sp<EffectModule> effect = ec->mEffects[0];
2436 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002437 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002438 if (effect->purgeHandles()) {
2439 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002440 }
2441 AudioSystem::unregisterEffect(effect->id());
2442 }
2443 }
2444 }
2445 return;
2446}
2447
Glenn Kasteneeecb982016-02-26 10:44:04 -08002448// checkThread_l() must be called with AudioFlinger::mLock held
2449AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2450{
2451 ThreadBase *thread = NULL;
2452 switch (audio_unique_id_get_use(ioHandle)) {
2453 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2454 thread = checkPlaybackThread_l(ioHandle);
2455 break;
2456 case AUDIO_UNIQUE_ID_USE_INPUT:
2457 thread = checkRecordThread_l(ioHandle);
2458 break;
2459 default:
2460 break;
2461 }
2462 return thread;
2463}
2464
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002466AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467{
Glenn Kastena1117922012-01-26 10:53:32 -08002468 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469}
2470
2471// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002472AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473{
2474 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002475 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476}
2477
2478// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002479AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480{
Glenn Kastena1117922012-01-26 10:53:32 -08002481 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482}
2483
Glenn Kasteneeecb982016-02-26 10:44:04 -08002484audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485{
Glenn Kasten9d003132016-04-06 14:38:09 -07002486 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002487 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002488 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2489 for (int retry = 0; retry < maxRetries; retry++) {
2490 // The cast allows wraparound from max positive to min negative instead of abort
2491 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2492 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2493 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2494 // allow wrap by skipping 0 and -1 for session ids
2495 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2496 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2497 return (audio_unique_id_t) (base | use);
2498 }
2499 }
2500 // We have no way of recovering from wraparound
2501 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2502 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002505AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002506{
2507 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2508 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002509 if(thread->isDuplicating()) {
2510 continue;
2511 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002512 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002513 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002514 return thread;
2515 }
2516 }
2517 return NULL;
2518}
2519
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002520audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002521{
2522 PlaybackThread *thread = primaryPlaybackThread_l();
2523
2524 if (thread == NULL) {
2525 return 0;
2526 }
2527
Eric Laurentf1c04f92012-08-28 14:26:53 -07002528 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002529}
2530
Eric Laurenta011e352012-03-29 15:51:43 -07002531sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002532 audio_session_t triggerSession,
2533 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002534 sync_event_callback_t callBack,
Eric Laurent8ea16e42014-02-20 16:26:11 -08002535 wp<RefBase> cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002536{
2537 Mutex::Autolock _l(mLock);
2538
2539 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2540 status_t playStatus = NAME_NOT_FOUND;
2541 status_t recStatus = NAME_NOT_FOUND;
2542 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2543 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2544 if (playStatus == NO_ERROR) {
2545 return event;
2546 }
2547 }
2548 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2549 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2550 if (recStatus == NO_ERROR) {
2551 return event;
2552 }
2553 }
2554 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2555 mPendingSyncEvents.add(event);
2556 } else {
2557 ALOGV("createSyncEvent() invalid event %d", event->type());
2558 event.clear();
2559 }
2560 return event;
2561}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002562
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563// ----------------------------------------------------------------------------
2564// Effect management
2565// ----------------------------------------------------------------------------
2566
2567
Glenn Kastenf587ba52012-01-26 16:25:10 -08002568status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569{
2570 Mutex::Autolock _l(mLock);
2571 return EffectQueryNumberEffects(numEffects);
2572}
2573
Glenn Kastenf587ba52012-01-26 16:25:10 -08002574status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575{
2576 Mutex::Autolock _l(mLock);
2577 return EffectQueryEffect(index, descriptor);
2578}
2579
Glenn Kasten5e92a782012-01-30 07:40:52 -08002580status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002581 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582{
2583 Mutex::Autolock _l(mLock);
2584 return EffectGetDescriptor(pUuid, descriptor);
2585}
2586
2587
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002588sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 effect_descriptor_t *pDesc,
2590 const sp<IEffectClient>& effectClient,
2591 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002592 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002593 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002594 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595 status_t *status,
2596 int *id,
2597 int *enabled)
2598{
2599 status_t lStatus = NO_ERROR;
2600 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002603 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002604 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002605 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606
2607 if (pDesc == NULL) {
2608 lStatus = BAD_VALUE;
2609 goto Exit;
2610 }
2611
Eric Laurent84e9a102010-09-23 16:10:16 -07002612 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002613 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002614 lStatus = PERMISSION_DENIED;
2615 goto Exit;
2616 }
2617
Dima Zavinfce7a472011-04-19 22:30:36 -07002618 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002619 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002620 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002621 lStatus = PERMISSION_DENIED;
2622 goto Exit;
2623 }
2624
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 if (!EffectIsNullUuid(&pDesc->uuid)) {
2627 // if uuid is specified, request effect descriptor
2628 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2629 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002630 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 goto Exit;
2632 }
2633 } else {
2634 // if uuid is not specified, look for an available implementation
2635 // of the required type in effect factory
2636 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002637 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 lStatus = BAD_VALUE;
2639 goto Exit;
2640 }
2641 uint32_t numEffects = 0;
2642 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002643 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644 bool found = false;
2645
2646 lStatus = EffectQueryNumberEffects(&numEffects);
2647 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002648 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 goto Exit;
2650 }
2651 for (uint32_t i = 0; i < numEffects; i++) {
2652 lStatus = EffectQueryEffect(i, &desc);
2653 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002654 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 continue;
2656 }
2657 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2658 // If matching type found save effect descriptor. If the session is
2659 // 0 and the effect is not auxiliary, continue enumeration in case
2660 // an auxiliary version of this effect type is available
2661 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002662 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002663 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2665 break;
2666 }
2667 }
2668 }
2669 if (!found) {
2670 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002671 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 goto Exit;
2673 }
2674 // For same effect type, chose auxiliary version over insert version if
2675 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002676 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002678 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 }
2680 }
2681
2682 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002683 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2685 lStatus = INVALID_OPERATION;
2686 goto Exit;
2687 }
2688
Eric Laurent59255e42011-07-27 19:49:51 -07002689 // check recording permission for visualizer
2690 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002691 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002692 lStatus = PERMISSION_DENIED;
2693 goto Exit;
2694 }
2695
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002697 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002698 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002699 // if the output returned by getOutputForEffect() is removed before we lock the
2700 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2701 // and we will exit safely
2702 io = AudioSystem::getOutputForEffect(&desc);
2703 ALOGV("createEffect got output %d", io);
2704 }
2705
2706 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707
2708 // If output is not specified try to find a matching audio session ID in one of the
2709 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002710 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2711 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002712 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002713 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002714 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2715 // output must be specified by AudioPolicyManager when using session
2716 // AUDIO_SESSION_OUTPUT_STAGE
2717 lStatus = BAD_VALUE;
2718 goto Exit;
2719 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002720 // look for the thread where the specified audio session is present
2721 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2722 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2723 io = mPlaybackThreads.keyAt(i);
2724 break;
2725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002727 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002728 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2729 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2730 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002731 break;
2732 }
2733 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002734 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002735 // If no output thread contains the requested session ID, default to
2736 // first output. The effect chain will be moved to the correct output
2737 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002738 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002739 io = mPlaybackThreads.keyAt(0);
2740 }
Steve Block3856b092011-10-20 11:56:00 +01002741 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002742 }
2743 ThreadBase *thread = checkRecordThread_l(io);
2744 if (thread == NULL) {
2745 thread = checkPlaybackThread_l(io);
2746 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002747 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002748 lStatus = BAD_VALUE;
2749 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002750 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002751 } else {
2752 // Check if one effect chain was awaiting for an effect to be created on this
2753 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002754 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002755 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002756 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002757 thread->addEffectChain_l(chain);
2758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002760
Eric Laurent021cf962014-05-13 10:18:14 -07002761 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002763 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002764 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2765 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 if (handle != 0 && id != NULL) {
2767 *id = handle->id();
2768 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002769 if (handle == 0) {
2770 // remove local strong reference to Client with mClientLock held
2771 Mutex::Autolock _cl(mClientLock);
2772 client.clear();
2773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 }
2775
2776Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002777 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 return handle;
2779}
2780
Glenn Kastend848eb42016-03-08 13:42:11 -08002781status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002782 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002783{
Steve Block3856b092011-10-20 11:56:00 +01002784 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002785 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002786 Mutex::Autolock _l(mLock);
2787 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002788 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002789 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790 }
Eric Laurentde070132010-07-13 04:45:46 -07002791 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2792 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002793 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002794 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 }
Eric Laurentde070132010-07-13 04:45:46 -07002796 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2797 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002798 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002799 return BAD_VALUE;
2800 }
2801
2802 Mutex::Autolock _dl(dstThread->mLock);
2803 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002804 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805}
2806
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002807// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002808status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002809 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002810 AudioFlinger::PlaybackThread *dstThread,
2811 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002812{
Steve Block3856b092011-10-20 11:56:00 +01002813 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002814 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002815
Eric Laurent59255e42011-07-27 19:49:51 -07002816 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002817 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002818 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002819 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002820 return INVALID_OPERATION;
2821 }
2822
Andy Hung9a592762014-07-21 21:56:01 -07002823 // Check whether the destination thread has a channel count of FCC_2, which is
2824 // currently required for (most) effects. Prevent moving the effect chain here rather
2825 // than disabling the addEffect_l() call in dstThread below.
Eric Laurentf6870ae2015-05-08 10:50:03 -07002826 if ((dstThread->type() == ThreadBase::MIXER || dstThread->isDuplicating()) &&
Eric Laurentb10352f2014-11-03 16:25:39 -08002827 dstThread->mChannelCount != FCC_2) {
Andy Hung9a592762014-07-21 21:56:01 -07002828 ALOGW("moveEffectChain_l() effect chain failed because"
2829 " destination thread %p channel count(%u) != %u",
2830 dstThread, dstThread->mChannelCount, FCC_2);
2831 return INVALID_OPERATION;
2832 }
2833
Eric Laurent39e94f82010-07-28 01:32:47 -07002834 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002835 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002836 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002837 // removed.
2838 srcThread->removeEffectChain_l(chain);
2839
2840 // transfer all effects one by one so that new effect chain is created on new thread with
2841 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002842 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002843 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002844 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002845 Vector< sp<EffectModule> > removed;
2846 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002847 while (effect != 0) {
2848 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002849 removed.add(effect);
2850 status = dstThread->addEffect_l(effect);
2851 if (status != NO_ERROR) {
2852 break;
2853 }
Eric Laurentec35a142011-10-05 17:42:25 -07002854 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2855 if (effect->state() == EffectModule::ACTIVE ||
2856 effect->state() == EffectModule::STOPPING) {
2857 effect->start();
2858 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002859 // if the move request is not received from audio policy manager, the effect must be
2860 // re-registered with the new strategy and output
2861 if (dstChain == 0) {
2862 dstChain = effect->chain().promote();
2863 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002864 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002865 status = NO_INIT;
2866 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002867 }
2868 strategy = dstChain->strategy();
2869 }
2870 if (reRegister) {
2871 AudioSystem::unregisterEffect(effect->id());
2872 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002873 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002874 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002875 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002876 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002877 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002878 }
Eric Laurentde070132010-07-13 04:45:46 -07002879 effect = chain->getEffectFromId_l(0);
2880 }
2881
Eric Laurent5baf2af2013-09-12 17:37:00 -07002882 if (status != NO_ERROR) {
2883 for (size_t i = 0; i < removed.size(); i++) {
2884 srcThread->addEffect_l(removed[i]);
2885 if (dstChain != 0 && reRegister) {
2886 AudioSystem::unregisterEffect(removed[i]->id());
2887 AudioSystem::registerEffect(&removed[i]->desc(),
2888 srcThread->id(),
2889 strategy,
2890 sessionId,
2891 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002892 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002893 }
2894 }
2895 }
2896
2897 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898}
2899
Eric Laurent5baf2af2013-09-12 17:37:00 -07002900bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002901{
2902 if (mGlobalEffectEnableTime != 0 &&
2903 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2904 return true;
2905 }
2906
2907 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2908 sp<EffectChain> ec =
2909 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002910 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002911 return true;
2912 }
2913 }
2914 return false;
2915}
2916
Eric Laurent5baf2af2013-09-12 17:37:00 -07002917void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002918{
2919 Mutex::Autolock _l(mLock);
2920
2921 mGlobalEffectEnableTime = systemTime();
2922
2923 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2924 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2925 if (t->mType == ThreadBase::OFFLOAD) {
2926 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2927 }
2928 }
2929
2930}
2931
Eric Laurentaaa44472014-09-12 17:41:50 -07002932status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2933{
Glenn Kastend848eb42016-03-08 13:42:11 -08002934 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002935 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002936 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002937 if (index >= 0) {
2938 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2939 return ALREADY_EXISTS;
2940 }
2941 mOrphanEffectChains.add(session, chain);
2942 return NO_ERROR;
2943}
2944
2945sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2946{
2947 sp<EffectChain> chain;
2948 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002949 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002950 if (index >= 0) {
2951 chain = mOrphanEffectChains.valueAt(index);
2952 mOrphanEffectChains.removeItemsAt(index);
2953 }
2954 return chain;
2955}
2956
2957bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2958{
2959 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002960 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002961 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002962 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002963 if (index >= 0) {
2964 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2965 if (chain->removeEffect_l(effect) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002966 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002967 mOrphanEffectChains.removeItemsAt(index);
2968 }
2969 return true;
2970 }
2971 return false;
2972}
2973
2974
Glenn Kastenda6ef132013-01-10 12:31:01 -08002975struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002976#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2977 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002978};
2979
2980int comparEntry(const void *p1, const void *p2)
2981{
Glenn Kasten2f55e762015-03-05 16:05:08 -08002982 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002983}
2984
Glenn Kasten46909e72013-02-26 09:20:22 -08002985#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002986void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987{
Eric Laurent81784c32012-11-19 14:55:58 -08002988 NBAIO_Source *teeSource = source.get();
2989 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002990 // .wav rotation
2991 // There is a benign race condition if 2 threads call this simultaneously.
2992 // They would both traverse the directory, but the result would simply be
2993 // failures at unlink() which are ignored. It's also unlikely since
2994 // normally dumpsys is only done by bugreport or from the command line.
2995 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08002996 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08002997 size_t teePathLen = strlen(teePath);
2998 DIR *dir = opendir(teePath);
2999 teePath[teePathLen++] = '/';
3000 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003001#define TEE_MAX_SORT 20 // number of entries to sort
3002#define TEE_MAX_KEEP 10 // number of entries to keep
3003 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003004 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003005 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003006 struct dirent de;
3007 struct dirent *result = NULL;
3008 int rc = readdir_r(dir, &de, &result);
3009 if (rc != 0) {
3010 ALOGW("readdir_r failed %d", rc);
3011 break;
3012 }
3013 if (result == NULL) {
3014 break;
3015 }
3016 if (result != &de) {
3017 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3018 break;
3019 }
3020 // ignore non .wav file entries
3021 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003022 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003023 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3024 continue;
3025 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003026 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003027 }
3028 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003029 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003030 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003031 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3032 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003033 (void) unlink(teePath);
3034 }
3035 }
3036 } else {
3037 if (fd >= 0) {
Glenn Kasten9a003992016-02-23 15:24:34 -08003038 dprintf(fd, "unable to rotate tees in %.*s: %s\n", teePathLen, teePath,
3039 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003040 }
3041 }
Eric Laurent81784c32012-11-19 14:55:58 -08003042 char teeTime[16];
3043 struct timeval tv;
3044 gettimeofday(&tv, NULL);
3045 struct tm tm;
3046 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003047 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3048 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3049 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3050 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003052 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003053 char wavHeader[44];
3054 memcpy(wavHeader,
3055 "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",
3056 sizeof(wavHeader));
3057 NBAIO_Format format = teeSource->format();
3058 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003059 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003060 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003061 wavHeader[22] = channelCount; // number of channels
3062 wavHeader[24] = sampleRate; // sample rate
3063 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003064 wavHeader[32] = frameSize; // block alignment
3065 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003066 write(teeFd, wavHeader, sizeof(wavHeader));
3067 size_t total = 0;
3068 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003069#define TEE_SINK_READ 1024 // frames per I/O operation
3070 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003071 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003072 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003073 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003074 bool wasFirstRead = firstRead;
3075 firstRead = false;
3076 if (actual <= 0) {
3077 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3078 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003079 }
Eric Laurent81784c32012-11-19 14:55:58 -08003080 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003081 }
Eric Laurent81784c32012-11-19 14:55:58 -08003082 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003083 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003084 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003085 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003086 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003087 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003088 uint32_t temp = 44 + total * frameSize - 8;
3089 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003090 write(teeFd, &temp, sizeof(temp));
3091 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003092 temp = total * frameSize;
3093 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003094 write(teeFd, &temp, sizeof(temp));
3095 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003096 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003097 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003098 }
Eric Laurent59255e42011-07-27 19:49:51 -07003099 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003100 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003101 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003102 }
Eric Laurent59255e42011-07-27 19:49:51 -07003103 }
3104 }
3105}
Glenn Kasten46909e72013-02-26 09:20:22 -08003106#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003107
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108// ----------------------------------------------------------------------------
3109
3110status_t AudioFlinger::onTransact(
3111 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3112{
3113 return BnAudioFlinger::onTransact(code, data, reply, flags);
3114}
3115
Glenn Kasten63238ef2015-03-02 15:50:29 -08003116} // namespace android