blob: 48f75146e10c3d3b2589e3ca495c74230ec7c080 [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <utils/String16.h>
35#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070036#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037
Dima Zavinfce7a472011-04-19 22:30:36 -070038#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <cutils/properties.h>
40
Dima Zavin64760242011-05-11 14:15:23 -070041#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070042#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
44#include "AudioMixer.h"
45#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080046#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
Andy Hung6770c6f2015-04-07 13:43:36 -070048#include <media/AudioResamplerPublic.h>
49
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070051#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070052#include <audio_effects/effect_ns.h>
53#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054
Glenn Kasten3b21c502011-12-15 09:52:39 -080055#include <audio_utils/primitives.h>
56
Eric Laurentfeb0db62011-07-22 09:04:31 -070057#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080058
John Grossman4ff14ba2012-02-08 16:37:41 -080059#include <common_time/cc_helper.h>
Glenn Kasten58912562012-04-03 10:45:00 -070060
Glenn Kasten9e58b552013-01-18 15:09:48 -080061#include <media/IMediaLogService.h>
62
Glenn Kastenda6ef132013-01-10 12:31:01 -080063#include <media/nbaio/Pipe.h>
64#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070065#include <media/AudioParameter.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) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530111 switch (format & AUDIO_FORMAT_MAIN_MASK) {
112 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";
Marco Nelissenb2208842014-02-07 14:00:50 -0800134 default:
135 break;
136 }
137 return "unknown";
138}
139
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700140static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700141{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700142 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700143 int rc;
144
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700145 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
146 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
147 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
148 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700149 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700150 }
151 rc = audio_hw_device_open(mod, dev);
152 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
153 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
154 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700155 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700156 }
Eric Laurent5806b352014-05-22 12:23:26 -0700157 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700158 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
159 rc = BAD_VALUE;
160 goto out;
161 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700162 return 0;
163
164out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700165 *dev = NULL;
166 return rc;
167}
168
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169// ----------------------------------------------------------------------------
170
171AudioFlinger::AudioFlinger()
172 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800173 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800174 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700175 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800176 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterMute(false),
178 mNextUniqueId(1),
179 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700180 mBtNrecIsOff(false),
181 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700182 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700183 mGlobalEffectEnableTime(0),
184 mPrimaryOutputSampleRate(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700185{
Glenn Kasten949a9262013-04-16 12:35:20 -0700186 getpid_cached = getpid();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800187 char value[PROPERTY_VALUE_MAX];
188 bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
189 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800190 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
191 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800192 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700193
Glenn Kasten46909e72013-02-26 09:20:22 -0800194#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800195 (void) property_get("ro.debuggable", value, "0");
196 int debuggable = atoi(value);
197 int teeEnabled = 0;
198 if (debuggable) {
199 (void) property_get("af.tee", value, "0");
200 teeEnabled = atoi(value);
201 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800202 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700203 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800204 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700205 }
206 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800207 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700208 }
209 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800210 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700211 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800212#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700213}
214
215void AudioFlinger::onFirstRef()
216{
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700218
Eric Laurent93575202011-01-18 18:39:02 -0800219 Mutex::Autolock _l(mLock);
220
Dima Zavin799a70e2011-04-18 16:57:27 -0700221 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800222 char val_str[PROPERTY_VALUE_MAX] = { 0 };
223 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
224 uint32_t int_val;
225 if (1 == sscanf(val_str, "%u", &int_val)) {
226 mStandbyTimeInNsecs = milliseconds(int_val);
227 ALOGI("Using %u mSec as standby time.", int_val);
228 } else {
229 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
230 ALOGI("Using default %u mSec as standby time.",
231 (uint32_t)(mStandbyTimeInNsecs / 1000000));
232 }
233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234
Eric Laurent1c333e22014-05-20 10:48:17 -0700235 mPatchPanel = new PatchPanel(this);
236
Eric Laurenta4c5a552012-03-29 10:12:40 -0700237 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700238}
239
240AudioFlinger::~AudioFlinger()
241{
242 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700243 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700244 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
246 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700247 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700248 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700250
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800251 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
252 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700253 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
254 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700256
257 // Tell media.log service about any old writers that still need to be unregistered
258 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
259 if (binder != 0) {
260 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
261 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
262 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
263 mUnregisteredWriters.pop();
264 mediaLogService->unregisterWriter(iMemory);
265 }
266 }
267
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268}
269
Eric Laurenta4c5a552012-03-29 10:12:40 -0700270static const char * const audio_interfaces[] = {
271 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
272 AUDIO_HARDWARE_MODULE_ID_A2DP,
273 AUDIO_HARDWARE_MODULE_ID_USB,
274};
275#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
276
Phil Burk062e67a2015-02-11 13:40:50 -0800277AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700278 audio_module_handle_t module,
279 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700280{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700281 // if module is 0, the request comes from an old policy manager and we should load
282 // well known modules
283 if (module == 0) {
284 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
285 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
286 loadHwModule_l(audio_interfaces[i]);
287 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700288 // then try to find a module supporting the requested device.
289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
291 audio_hw_device_t *dev = audioHwDevice->hwDevice();
292 if ((dev->get_supported_devices != NULL) &&
293 (dev->get_supported_devices(dev) & devices) == devices)
294 return audioHwDevice;
295 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 } else {
297 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700298 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
299 if (audioHwDevice != NULL) {
300 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700301 }
302 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700303
Dima Zavin799a70e2011-04-18 16:57:27 -0700304 return NULL;
305}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700306
Glenn Kasten0f11b512014-01-31 16:18:54 -0800307void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700308{
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
312
313 result.append("Clients:\n");
314 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800315 sp<Client> client = mClients.valueAt(i).promote();
316 if (client != 0) {
317 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
318 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 }
320 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321
Eric Laurentd1b28d42013-09-18 18:47:13 -0700322 result.append("Notification Clients:\n");
323 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
324 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
325 result.append(buffer);
326 }
327
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700328 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800329 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800332 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333 result.append(buffer);
334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
338
Glenn Kasten0f11b512014-01-31 16:18:54 -0800339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800344 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345
John Grossman4ff14ba2012-02-08 16:37:41 -0800346 snprintf(buffer, SIZE, "Hardware status: %d\n"
347 "Standby Time mSec: %u\n",
348 hardwareStatus,
349 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 result.append(buffer);
351 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Glenn Kasten0f11b512014-01-31 16:18:54 -0800354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 snprintf(buffer, SIZE, "Permission Denial: "
360 "can't dump AudioFlinger from pid=%d, uid=%d\n",
361 IPCThreadState::self()->getCallingPid(),
362 IPCThreadState::self()->getCallingUid());
363 result.append(buffer);
364 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365}
366
Eric Laurent81784c32012-11-19 14:55:58 -0800367bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368{
369 bool locked = false;
370 for (int i = 0; i < kDumpLockRetries; ++i) {
371 if (mutex.tryLock() == NO_ERROR) {
372 locked = true;
373 break;
374 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800375 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 }
377 return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
Glenn Kasten44deb052012-02-05 18:09:08 -0800382 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpPermissionDenial(fd, args);
384 } else {
385 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800386 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 if (!hardwareLocked) {
388 String8 result(kHardwareLockedString);
389 write(fd, result.string(), result.size());
390 } else {
391 mHardwareLock.unlock();
392 }
393
Eric Laurent81784c32012-11-19 14:55:58 -0800394 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395
396 // failed to lock - AudioFlinger is probably deadlocked
397 if (!locked) {
398 String8 result(kDeadlockedString);
399 write(fd, result.string(), result.size());
400 }
401
Eric Laurent021cf962014-05-13 10:18:14 -0700402 bool clientLocked = dumpTryLock(mClientLock);
403 if (!clientLocked) {
404 String8 result(kClientLockedString);
405 write(fd, result.string(), result.size());
406 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700407
408 EffectDumpEffects(fd);
409
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700411 if (clientLocked) {
412 mClientLock.unlock();
413 }
414
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415 dumpInternals(fd, args);
416
417 // dump playback threads
418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
419 mPlaybackThreads.valueAt(i)->dump(fd, args);
420 }
421
422 // dump record threads
423 for (size_t i = 0; i < mRecordThreads.size(); i++) {
424 mRecordThreads.valueAt(i)->dump(fd, args);
425 }
426
Eric Laurentaaa44472014-09-12 17:41:50 -0700427 // dump orphan effect chains
428 if (mOrphanEffectChains.size() != 0) {
429 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
430 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
431 mOrphanEffectChains.valueAt(i)->dump(fd, args);
432 }
433 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700434 // dump all hardware devs
435 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700436 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700437 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700439
Glenn Kasten46909e72013-02-26 09:20:22 -0800440#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700441 // dump the serially shared record tee sink
442 if (mRecordTeeSource != 0) {
443 dumpTee(fd, mRecordTeeSource);
444 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800445#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700446
Glenn Kastend65d73c2012-06-22 17:21:07 -0700447 if (locked) {
448 mLock.unlock();
449 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800450
451 // append a copy of media.log here by forwarding fd to it, but don't attempt
452 // to lookup the service if it's not running, as it will block for a second
453 if (mLogMemoryDealer != 0) {
454 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
455 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700456 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800457 Vector<String16> args;
458 binder->dump(fd, args);
459 }
460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 }
462 return NO_ERROR;
463}
464
Eric Laurent021cf962014-05-13 10:18:14 -0700465sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800466{
Eric Laurent021cf962014-05-13 10:18:14 -0700467 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800468 // If pid is already in the mClients wp<> map, then use that entry
469 // (for which promote() is always != 0), otherwise create a new entry and Client.
470 sp<Client> client = mClients.valueFor(pid).promote();
471 if (client == 0) {
472 client = new Client(this, pid);
473 mClients.add(pid, client);
474 }
475
476 return client;
477}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478
Glenn Kasten9e58b552013-01-18 15:09:48 -0800479sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
480{
Glenn Kasten481fb672013-09-30 14:39:28 -0700481 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800482 if (mLogMemoryDealer == 0) {
483 return new NBLog::Writer();
484 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800485 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700486 // Similarly if we can't contact the media.log service, also return a dummy writer
487 if (binder == 0) {
488 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800489 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700490 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
491 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
492 // If allocation fails, consult the vector of previously unregistered writers
493 // and garbage-collect one or more them until an allocation succeeds
494 if (shared == 0) {
495 Mutex::Autolock _l(mUnregisteredWritersLock);
496 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
497 {
498 // Pick the oldest stale writer to garbage-collect
499 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
500 mUnregisteredWriters.removeAt(0);
501 mediaLogService->unregisterWriter(iMemory);
502 // Now the media.log remote reference to IMemory is gone. When our last local
503 // reference to IMemory also drops to zero at end of this block,
504 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
505 }
506 // Re-attempt the allocation
507 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
508 if (shared != 0) {
509 goto success;
510 }
511 }
512 // Even after garbage-collecting all old writers, there is still not enough memory,
513 // so return a dummy writer
514 return new NBLog::Writer();
515 }
516success:
517 mediaLogService->registerWriter(shared, size, name);
518 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800519}
520
521void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
522{
Glenn Kasten685ef092013-02-04 08:15:34 -0800523 if (writer == 0) {
524 return;
525 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800526 sp<IMemory> iMemory(writer->getIMemory());
527 if (iMemory == 0) {
528 return;
529 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700530 // Rather than removing the writer immediately, append it to a queue of old writers to
531 // be garbage-collected later. This allows us to continue to view old logs for a while.
532 Mutex::Autolock _l(mUnregisteredWritersLock);
533 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800534}
535
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536// IAudioFlinger interface
537
538
539sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800540 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800542 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700543 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800544 size_t *frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800545 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800548 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549 int *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800550 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551 status_t *status)
552{
553 sp<PlaybackThread::Track> track;
554 sp<TrackHandle> trackHandle;
555 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 status_t lStatus;
557 int lSessionId;
558
Glenn Kasten263709e2012-01-06 08:40:01 -0800559 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
560 // but if someone uses binder directly they could bypass that and cause us to crash
561 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000562 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 lStatus = BAD_VALUE;
564 goto Exit;
565 }
566
Glenn Kasten53b5d092014-02-05 10:00:23 -0800567 // further sample rate checks are performed by createTrack_l() depending on the thread type
568 if (sampleRate == 0) {
569 ALOGE("createTrack() invalid sample rate %u", sampleRate);
570 lStatus = BAD_VALUE;
571 goto Exit;
572 }
573
574 // further channel mask checks are performed by createTrack_l() depending on the thread type
575 if (!audio_is_output_channel(channelMask)) {
576 ALOGE("createTrack() invalid channel mask %#x", channelMask);
577 lStatus = BAD_VALUE;
578 goto Exit;
579 }
580
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700581 // further format checks are performed by createTrack_l() depending on the thread type
582 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800583 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700584 lStatus = BAD_VALUE;
585 goto Exit;
586 }
587
Glenn Kasten663c2242013-09-24 11:52:37 -0700588 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
589 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
590 lStatus = BAD_VALUE;
591 goto Exit;
592 }
593
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 {
595 Mutex::Autolock _l(mLock);
596 PlaybackThread *thread = checkPlaybackThread_l(output);
597 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800598 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 lStatus = BAD_VALUE;
600 goto Exit;
601 }
602
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800603 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -0700604 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605
Glenn Kastene848bd92014-03-13 15:00:32 -0700606 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700607 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700608 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700609 // check if an effect chain with the same session ID is present on another
610 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700611 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700612 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
613 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700614 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700615 if (sessions & PlaybackThread::EFFECT_SESSION) {
616 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700617 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700618 }
Eric Laurentde070132010-07-13 04:45:46 -0700619 }
620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700621 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700622 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700623 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 if (sessionId != NULL) {
625 *sessionId = lSessionId;
626 }
627 }
Steve Block3856b092011-10-20 11:56:00 +0100628 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
630 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800631 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800632 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700633 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700634
635 // move effect chain to this output thread if an effect on same session was waiting
636 // for a track to be created
637 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700638 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700639 Mutex::Autolock _dl(thread->mLock);
640 Mutex::Autolock _sl(effectThread->mLock);
641 moveEffectChain_l(lSessionId, effectThread, thread, true);
642 }
Eric Laurenta011e352012-03-29 15:51:43 -0700643
644 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700645 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700646 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
647 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700648 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700649 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700650 } else {
651 mPendingSyncEvents[i]->cancel();
652 }
Eric Laurenta011e352012-03-29 15:51:43 -0700653 mPendingSyncEvents.removeAt(i);
654 i--;
655 }
656 }
657 }
Glenn Kastene198c362013-08-13 09:13:36 -0700658
Eric Laurentfa90e842014-10-17 18:12:31 -0700659 setAudioHwSyncForSession_l(thread, (audio_session_t)lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 }
Glenn Kastene198c362013-08-13 09:13:36 -0700661
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700662 if (lStatus != NO_ERROR) {
663 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700664 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700665 // Don't hold mClientLock when releasing the reference on the track as the
666 // destructor will acquire it.
667 {
668 Mutex::Autolock _cl(mClientLock);
669 client.clear();
670 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700672 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 }
674
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700675 // return handle to client
676 trackHandle = new TrackHandle(track);
677
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700679 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680 return trackHandle;
681}
682
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800683uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684{
685 Mutex::Autolock _l(mLock);
686 PlaybackThread *thread = checkPlaybackThread_l(output);
687 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000688 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 return 0;
690 }
691 return thread->sampleRate();
692}
693
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800694audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695{
696 Mutex::Autolock _l(mLock);
697 PlaybackThread *thread = checkPlaybackThread_l(output);
698 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000699 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800700 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 }
702 return thread->format();
703}
704
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800705size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706{
707 Mutex::Autolock _l(mLock);
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000710 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 return 0;
712 }
Glenn Kasten58912562012-04-03 10:45:00 -0700713 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
714 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715 return thread->frameCount();
716}
717
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800718uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719{
720 Mutex::Autolock _l(mLock);
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800723 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 return 0;
725 }
726 return thread->latency();
727}
728
729status_t AudioFlinger::setMasterVolume(float value)
730{
Eric Laurenta1884f92011-08-23 08:25:03 -0700731 status_t ret = initCheck();
732 if (ret != NO_ERROR) {
733 return ret;
734 }
735
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 // check calling permissions
737 if (!settingsAllowed()) {
738 return PERMISSION_DENIED;
739 }
740
Eric Laurenta4c5a552012-03-29 10:12:40 -0700741 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700742 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700743
John Grossmanee578c02012-07-23 17:05:46 -0700744 // Set master volume in the HALs which support it.
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 AutoMutex lock(mHardwareLock);
747 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800748
John Grossmanee578c02012-07-23 17:05:46 -0700749 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
750 if (dev->canSetMasterVolume()) {
751 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800752 }
John Grossmanee578c02012-07-23 17:05:46 -0700753 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755
John Grossmanee578c02012-07-23 17:05:46 -0700756 // Now set the master volume in each playback thread. Playback threads
757 // assigned to HALs which do not have master volume support will apply
758 // master volume during the mix operation. Threads with HALs which do
759 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800760 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700761 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762
763 return NO_ERROR;
764}
765
Glenn Kastenf78aee72012-01-04 11:00:47 -0800766status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767{
Eric Laurenta1884f92011-08-23 08:25:03 -0700768 status_t ret = initCheck();
769 if (ret != NO_ERROR) {
770 return ret;
771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772
773 // check calling permissions
774 if (!settingsAllowed()) {
775 return PERMISSION_DENIED;
776 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800777 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000778 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 return BAD_VALUE;
780 }
781
782 { // scope for the lock
783 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700784 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700786 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 mHardwareStatus = AUDIO_HW_IDLE;
788 }
789
790 if (NO_ERROR == ret) {
791 Mutex::Autolock _l(mLock);
792 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800793 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700794 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 }
796
797 return ret;
798}
799
800status_t AudioFlinger::setMicMute(bool state)
801{
Eric Laurenta1884f92011-08-23 08:25:03 -0700802 status_t ret = initCheck();
803 if (ret != NO_ERROR) {
804 return ret;
805 }
806
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807 // check calling permissions
808 if (!settingsAllowed()) {
809 return PERMISSION_DENIED;
810 }
811
812 AutoMutex lock(mHardwareLock);
813 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700814 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
815 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
816 status_t result = dev->set_mic_mute(dev, state);
817 if (result != NO_ERROR) {
818 ret = result;
819 }
820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 mHardwareStatus = AUDIO_HW_IDLE;
822 return ret;
823}
824
825bool AudioFlinger::getMicMute() const
826{
Eric Laurenta1884f92011-08-23 08:25:03 -0700827 status_t ret = initCheck();
828 if (ret != NO_ERROR) {
829 return false;
830 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800831 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700832 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800833 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800835 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
836 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
837 status_t result = dev->get_mic_mute(dev, &state);
838 if (result == NO_ERROR) {
839 mute = mute && state;
840 }
841 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800843
844 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845}
846
847status_t AudioFlinger::setMasterMute(bool muted)
848{
John Grossmand8f178d2012-07-20 14:51:35 -0700849 status_t ret = initCheck();
850 if (ret != NO_ERROR) {
851 return ret;
852 }
853
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 // check calling permissions
855 if (!settingsAllowed()) {
856 return PERMISSION_DENIED;
857 }
858
John Grossmanee578c02012-07-23 17:05:46 -0700859 Mutex::Autolock _l(mLock);
860 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700861
John Grossmanee578c02012-07-23 17:05:46 -0700862 // Set master mute in the HALs which support it.
863 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
864 AutoMutex lock(mHardwareLock);
865 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700866
John Grossmanee578c02012-07-23 17:05:46 -0700867 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
868 if (dev->canSetMasterMute()) {
869 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700870 }
John Grossmanee578c02012-07-23 17:05:46 -0700871 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700872 }
873
John Grossmanee578c02012-07-23 17:05:46 -0700874 // Now set the master mute in each playback thread. Playback threads
875 // assigned to HALs which do not have master mute support will apply master
876 // mute during the mix operation. Threads with HALs which do support master
877 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800878 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700879 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880
881 return NO_ERROR;
882}
883
884float AudioFlinger::masterVolume() const
885{
Glenn Kasten98067102011-12-13 11:47:54 -0800886 Mutex::Autolock _l(mLock);
887 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888}
889
890bool AudioFlinger::masterMute() const
891{
Glenn Kasten98067102011-12-13 11:47:54 -0800892 Mutex::Autolock _l(mLock);
893 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700894}
895
John Grossman4ff14ba2012-02-08 16:37:41 -0800896float AudioFlinger::masterVolume_l() const
897{
John Grossman4ff14ba2012-02-08 16:37:41 -0800898 return mMasterVolume;
899}
900
John Grossmand8f178d2012-07-20 14:51:35 -0700901bool AudioFlinger::masterMute_l() const
902{
John Grossmanee578c02012-07-23 17:05:46 -0700903 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700904}
905
Eric Laurent223fd5c2014-11-11 13:43:36 -0800906status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
907{
908 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
909 ALOGW("setStreamVolume() invalid stream %d", stream);
910 return BAD_VALUE;
911 }
912 pid_t caller = IPCThreadState::self()->getCallingPid();
913 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
914 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
915 return PERMISSION_DENIED;
916 }
917
918 return NO_ERROR;
919}
920
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800921status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
922 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923{
924 // check calling permissions
925 if (!settingsAllowed()) {
926 return PERMISSION_DENIED;
927 }
928
Eric Laurent223fd5c2014-11-11 13:43:36 -0800929 status_t status = checkStreamType(stream);
930 if (status != NO_ERROR) {
931 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800933 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934
935 AutoMutex lock(mLock);
936 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700937 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 thread = checkPlaybackThread_l(output);
939 if (thread == NULL) {
940 return BAD_VALUE;
941 }
942 }
943
944 mStreamTypes[stream].volume = value;
945
946 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800947 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700948 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 }
950 } else {
951 thread->setStreamVolume(stream, value);
952 }
953
954 return NO_ERROR;
955}
956
Glenn Kastenfff6d712012-01-12 16:38:12 -0800957status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958{
959 // check calling permissions
960 if (!settingsAllowed()) {
961 return PERMISSION_DENIED;
962 }
963
Eric Laurent223fd5c2014-11-11 13:43:36 -0800964 status_t status = checkStreamType(stream);
965 if (status != NO_ERROR) {
966 return status;
967 }
968 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
969
970 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000971 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 return BAD_VALUE;
973 }
974
Eric Laurent93575202011-01-18 18:39:02 -0800975 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700977 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700978 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979
980 return NO_ERROR;
981}
982
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800983float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984{
Eric Laurent223fd5c2014-11-11 13:43:36 -0800985 status_t status = checkStreamType(stream);
986 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 return 0.0f;
988 }
989
990 AutoMutex lock(mLock);
991 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -0700992 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 PlaybackThread *thread = checkPlaybackThread_l(output);
994 if (thread == NULL) {
995 return 0.0f;
996 }
997 volume = thread->streamVolume(stream);
998 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800999 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 }
1001
1002 return volume;
1003}
1004
Glenn Kastenfff6d712012-01-12 16:38:12 -08001005bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001007 status_t status = checkStreamType(stream);
1008 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 return true;
1010 }
1011
Glenn Kasten6637baa2012-01-09 09:40:36 -08001012 AutoMutex lock(mLock);
1013 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014}
1015
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001016status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001018 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1019 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001020
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 // check calling permissions
1022 if (!settingsAllowed()) {
1023 return PERMISSION_DENIED;
1024 }
1025
Glenn Kasten142f5192014-03-25 17:44:59 -07001026 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1027 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001028 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001029 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001030 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001031 AutoMutex lock(mHardwareLock);
1032 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1033 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1034 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1035 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1036 final_result = result ?: final_result;
1037 }
1038 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001039 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001040 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1041 AudioParameter param = AudioParameter(keyValuePairs);
1042 String8 value;
1043 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001044 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1045 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001046 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1047 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001048 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001049 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1050 // collect all of the thread's session IDs
1051 KeyedVector<int, bool> ids = thread->sessionIds();
1052 // suspend effects associated with those session IDs
1053 for (size_t j = 0; j < ids.size(); ++j) {
1054 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001055 thread->setEffectSuspended(FX_IID_AEC,
1056 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001057 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001058 thread->setEffectSuspended(FX_IID_NS,
1059 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001060 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001061 }
1062 }
Eric Laurentbee53372011-08-29 12:42:48 -07001063 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001064 }
1065 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001066 String8 screenState;
1067 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1068 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001069 if (isOff != (AudioFlinger::mScreenState & 1)) {
1070 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001071 }
1072 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001073 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 }
1075
1076 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1077 // and the thread is exited once the lock is released
1078 sp<ThreadBase> thread;
1079 {
1080 Mutex::Autolock _l(mLock);
1081 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001082 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001084 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001085 // indicate output device change to all input threads for pre processing
1086 AudioParameter param = AudioParameter(keyValuePairs);
1087 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001088 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1089 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001090 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1091 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1092 }
1093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 }
1095 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001096 if (thread != 0) {
1097 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 }
1099 return BAD_VALUE;
1100}
1101
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001102String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001104 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1105 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106
Eric Laurenta4c5a552012-03-29 10:12:40 -07001107 Mutex::Autolock _l(mLock);
1108
Glenn Kasten142f5192014-03-25 17:44:59 -07001109 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001110 String8 out_s8;
1111
Dima Zavin799a70e2011-04-18 16:57:27 -07001112 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001113 char *s;
1114 {
1115 AutoMutex lock(mHardwareLock);
1116 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001117 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001118 s = dev->get_parameters(dev, keys.string());
1119 mHardwareStatus = AUDIO_HW_IDLE;
1120 }
John Grossmanef7740b2012-02-09 11:28:36 -08001121 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001122 free(s);
1123 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001124 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 }
1126
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1128 if (playbackThread != NULL) {
1129 return playbackThread->getParameters(keys);
1130 }
1131 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1132 if (recordThread != NULL) {
1133 return recordThread->getParameters(keys);
1134 }
1135 return String8("");
1136}
1137
Glenn Kastendd8104c2012-07-02 12:42:44 -07001138size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1139 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140{
Eric Laurenta1884f92011-08-23 08:25:03 -07001141 status_t ret = initCheck();
1142 if (ret != NO_ERROR) {
1143 return 0;
1144 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001145 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
1146 return 0;
1147 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001148
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001149 AutoMutex lock(mHardwareLock);
1150 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001151 audio_config_t config, proposed;
1152 memset(&proposed, 0, sizeof(proposed));
1153 proposed.sample_rate = sampleRate;
1154 proposed.channel_mask = channelMask;
1155 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001156
John Grossmanee578c02012-07-23 17:05:46 -07001157 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001158 size_t frames;
1159 for (;;) {
1160 // Note: config is currently a const parameter for get_input_buffer_size()
1161 // but we use a copy from proposed in case config changes from the call.
1162 config = proposed;
1163 frames = dev->get_input_buffer_size(dev, &config);
1164 if (frames != 0) {
1165 break; // hal success, config is the result
1166 }
1167 // change one parameter of the configuration each iteration to a more "common" value
1168 // to see if the device will support it.
1169 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1170 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1171 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1172 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1173 } else {
1174 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1175 "format %#x, channelMask 0x%X",
1176 sampleRate, format, channelMask);
1177 break; // retries failed, break out of loop with frames == 0.
1178 }
1179 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001180 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001181 if (frames > 0 && config.sample_rate != sampleRate) {
1182 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1183 }
1184 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185}
1186
Glenn Kasten5f972c02014-01-13 09:59:31 -08001187uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 Mutex::Autolock _l(mLock);
1190
1191 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1192 if (recordThread != NULL) {
1193 return recordThread->getInputFramesLost();
1194 }
1195 return 0;
1196}
1197
1198status_t AudioFlinger::setVoiceVolume(float value)
1199{
Eric Laurenta1884f92011-08-23 08:25:03 -07001200 status_t ret = initCheck();
1201 if (ret != NO_ERROR) {
1202 return ret;
1203 }
1204
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 // check calling permissions
1206 if (!settingsAllowed()) {
1207 return PERMISSION_DENIED;
1208 }
1209
1210 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001211 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001212 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001213 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 mHardwareStatus = AUDIO_HW_IDLE;
1215
1216 return ret;
1217}
1218
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001219status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001220 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221{
1222 status_t status;
1223
1224 Mutex::Autolock _l(mLock);
1225
1226 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1227 if (playbackThread != NULL) {
1228 return playbackThread->getRenderPosition(halFrames, dspFrames);
1229 }
1230
1231 return BAD_VALUE;
1232}
1233
1234void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1235{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001237 if (client == 0) {
1238 return;
1239 }
Eric Laurent021cf962014-05-13 10:18:14 -07001240 bool clientAdded = false;
1241 {
1242 Mutex::Autolock _cl(mClientLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243
Eric Laurent021cf962014-05-13 10:18:14 -07001244 pid_t pid = IPCThreadState::self()->getCallingPid();
1245 if (mNotificationClients.indexOfKey(pid) < 0) {
1246 sp<NotificationClient> notificationClient = new NotificationClient(this,
1247 client,
1248 pid);
1249 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250
Eric Laurent021cf962014-05-13 10:18:14 -07001251 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252
Marco Nelissen06b46062014-11-14 07:58:25 -08001253 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001254 binder->linkToDeath(notificationClient);
1255 clientAdded = true;
1256 }
1257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258
Eric Laurent021cf962014-05-13 10:18:14 -07001259 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001260 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent021cf962014-05-13 10:18:14 -07001261 if (clientAdded) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 // the config change is always sent from playback or record threads to avoid deadlock
1263 // with AudioSystem::gLock
1264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001265 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266 }
1267
1268 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001269 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 }
1271 }
1272}
1273
1274void AudioFlinger::removeNotificationClient(pid_t pid)
1275{
1276 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001277 {
1278 Mutex::Autolock _cl(mClientLock);
1279 mNotificationClients.removeItem(pid);
1280 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001281
Steve Block3856b092011-10-20 11:56:00 +01001282 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001283 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001284 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001285 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001286 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001287 ALOGV(" pid %d @ %d", ref->mPid, i);
1288 if (ref->mPid == pid) {
1289 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001290 mAudioSessionRefs.removeAt(i);
1291 delete ref;
1292 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001293 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001294 } else {
1295 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001296 }
1297 }
1298 if (removed) {
1299 purgeStaleEffects_l();
1300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301}
1302
Eric Laurent021cf962014-05-13 10:18:14 -07001303void AudioFlinger::audioConfigChanged(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304{
Eric Laurent021cf962014-05-13 10:18:14 -07001305 Mutex::Autolock _l(mClientLock);
1306 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 for (size_t i = 0; i < size; i++) {
Eric Laurent021cf962014-05-13 10:18:14 -07001308 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event,
Eric Laurent10351942014-05-08 18:49:52 -07001309 ioHandle,
1310 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311 }
1312}
1313
Eric Laurent021cf962014-05-13 10:18:14 -07001314// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315void AudioFlinger::removeClient_l(pid_t pid)
1316{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001317 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001318 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319 mClients.removeItem(pid);
1320}
1321
Eric Laurent717e1282012-06-29 16:36:52 -07001322// getEffectThread_l() must be called with AudioFlinger::mLock held
1323sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1324{
1325 sp<PlaybackThread> thread;
1326
1327 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1328 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1329 ALOG_ASSERT(thread == 0);
1330 thread = mPlaybackThreads.valueAt(i);
1331 }
1332 }
1333
1334 return thread;
1335}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001336
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338
1339// ----------------------------------------------------------------------------
1340
1341AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1342 : RefBase(),
1343 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08001344 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07001345 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08001346 mPid(pid),
1347 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348{
1349 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
1350}
1351
Eric Laurent021cf962014-05-13 10:18:14 -07001352// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353AudioFlinger::Client::~Client()
1354{
1355 mAudioFlinger->removeClient_l(mPid);
1356}
1357
Glenn Kasten435dbe62012-01-30 10:15:48 -08001358sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359{
1360 return mMemoryDealer;
1361}
1362
John Grossman4ff14ba2012-02-08 16:37:41 -08001363// Reserve one of the limited slots for a timed audio track associated
1364// with this client
1365bool AudioFlinger::Client::reserveTimedTrack()
1366{
1367 const int kMaxTimedTracksPerClient = 4;
1368
1369 Mutex::Autolock _l(mTimedTrackLock);
1370
1371 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1372 ALOGW("can not create timed track - pid %d has exceeded the limit",
1373 mPid);
1374 return false;
1375 }
1376
1377 mTimedTrackCount++;
1378 return true;
1379}
1380
1381// Release a slot for a timed audio track
1382void AudioFlinger::Client::releaseTimedTrack()
1383{
1384 Mutex::Autolock _l(mTimedTrackLock);
1385 mTimedTrackCount--;
1386}
1387
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388// ----------------------------------------------------------------------------
1389
1390AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1391 const sp<IAudioFlingerClient>& client,
1392 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001393 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394{
1395}
1396
1397AudioFlinger::NotificationClient::~NotificationClient()
1398{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399}
1400
Glenn Kasten0f11b512014-01-31 16:18:54 -08001401void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402{
1403 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001404 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405}
1406
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407
1408// ----------------------------------------------------------------------------
1409
Jeff Brown893a5642013-08-16 20:19:26 -07001410static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1411 return audio_is_remote_submix_device(inDevice);
1412}
1413
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001415 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001417 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001418 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001419 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001420 size_t *frameCount,
Glenn Kasteneeca3262013-07-31 16:12:48 -07001421 IAudioFlinger::track_flags_t *flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001422 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 int *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001424 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001425 sp<IMemory>& cblk,
1426 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 status_t *status)
1428{
1429 sp<RecordThread::RecordTrack> recordTrack;
1430 sp<RecordHandle> recordHandle;
1431 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 int lSessionId;
1434
Glenn Kastend776ac62014-05-07 09:16:09 -07001435 cblk.clear();
1436 buffers.clear();
1437
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 // check calling permissions
Svet Ganovbe71aa22015-04-28 12:06:02 -07001439 if (!recordingAllowed(opPackageName)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001440 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 lStatus = PERMISSION_DENIED;
1442 goto Exit;
1443 }
1444
Glenn Kasten53b5d092014-02-05 10:00:23 -08001445 // further sample rate checks are performed by createRecordTrack_l()
1446 if (sampleRate == 0) {
1447 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1448 lStatus = BAD_VALUE;
1449 goto Exit;
1450 }
1451
Andy Hung6770c6f2015-04-07 13:43:36 -07001452 // we don't yet support anything other than linear PCM
1453 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001454 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001455 lStatus = BAD_VALUE;
1456 goto Exit;
1457 }
1458
Glenn Kasten53b5d092014-02-05 10:00:23 -08001459 // further channel mask checks are performed by createRecordTrack_l()
1460 if (!audio_is_input_channel(channelMask)) {
1461 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1462 lStatus = BAD_VALUE;
1463 goto Exit;
1464 }
1465
Glenn Kasten05997e22014-03-13 15:08:33 -07001466 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001468 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001470 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 lStatus = BAD_VALUE;
1472 goto Exit;
1473 }
1474
Glenn Kasten8d6cc842012-02-03 11:06:53 -08001475 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001476 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001478 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 lSessionId = *sessionId;
1480 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001481 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001482 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001483 if (sessionId != NULL) {
1484 *sessionId = lSessionId;
1485 }
1486 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001487 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001488
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001489 // TODO: the uid should be passed in as a parameter to openRecord
Glenn Kasten1879fff2012-07-11 15:36:59 -07001490 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001491 frameCount, lSessionId, notificationFrames,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001492 IPCThreadState::self()->getCallingUid(),
1493 flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001494 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001495
1496 if (lStatus == NO_ERROR) {
1497 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1498 // session and move it to this thread.
1499 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)lSessionId);
1500 if (chain != 0) {
1501 Mutex::Autolock _l(thread->mLock);
1502 thread->addEffectChain_l(chain);
1503 }
1504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 }
Glenn Kastene198c362013-08-13 09:13:36 -07001506
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001507 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001508 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001509 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001510 // Don't hold mClientLock when releasing the reference on the track as the
1511 // destructor will acquire it.
1512 {
1513 Mutex::Autolock _cl(mClientLock);
1514 client.clear();
1515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 goto Exit;
1518 }
1519
Glenn Kastend776ac62014-05-07 09:16:09 -07001520 cblk = recordTrack->getCblk();
1521 buffers = recordTrack->getBuffers();
1522
Glenn Kasten2fc14732013-08-05 14:58:14 -07001523 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525
1526Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001527 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 return recordHandle;
1529}
1530
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001531
1532
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533// ----------------------------------------------------------------------------
1534
Eric Laurenta4c5a552012-03-29 10:12:40 -07001535audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1536{
Eric Laurent44622db2014-08-01 19:00:33 -07001537 if (name == NULL) {
1538 return 0;
1539 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001540 if (!settingsAllowed()) {
1541 return 0;
1542 }
1543 Mutex::Autolock _l(mLock);
1544 return loadHwModule_l(name);
1545}
1546
1547// loadHwModule_l() must be called with AudioFlinger::mLock held
1548audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1549{
1550 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1551 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1552 ALOGW("loadHwModule() module %s already loaded", name);
1553 return mAudioHwDevs.keyAt(i);
1554 }
1555 }
1556
Eric Laurenta4c5a552012-03-29 10:12:40 -07001557 audio_hw_device_t *dev;
1558
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001559 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001560 if (rc) {
1561 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1562 return 0;
1563 }
1564
1565 mHardwareStatus = AUDIO_HW_INIT;
1566 rc = dev->init_check(dev);
1567 mHardwareStatus = AUDIO_HW_IDLE;
1568 if (rc) {
1569 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1570 return 0;
1571 }
1572
John Grossmanee578c02012-07-23 17:05:46 -07001573 // Check and cache this HAL's level of support for master mute and master
1574 // volume. If this is the first HAL opened, and it supports the get
1575 // methods, use the initial values provided by the HAL as the current
1576 // master mute and volume settings.
1577
1578 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1579 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001580 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001581
1582 if (0 == mAudioHwDevs.size()) {
1583 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1584 if (NULL != dev->get_master_volume) {
1585 float mv;
1586 if (OK == dev->get_master_volume(dev, &mv)) {
1587 mMasterVolume = mv;
1588 }
1589 }
1590
1591 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1592 if (NULL != dev->get_master_mute) {
1593 bool mm;
1594 if (OK == dev->get_master_mute(dev, &mm)) {
1595 mMasterMute = mm;
1596 }
1597 }
1598 }
1599
Eric Laurenta4c5a552012-03-29 10:12:40 -07001600 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001601 if ((NULL != dev->set_master_volume) &&
1602 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1603 flags = static_cast<AudioHwDevice::Flags>(flags |
1604 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1605 }
1606
1607 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1608 if ((NULL != dev->set_master_mute) &&
1609 (OK == dev->set_master_mute(dev, mMasterMute))) {
1610 flags = static_cast<AudioHwDevice::Flags>(flags |
1611 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1612 }
1613
Eric Laurenta4c5a552012-03-29 10:12:40 -07001614 mHardwareStatus = AUDIO_HW_IDLE;
1615 }
1616
1617 audio_module_handle_t handle = nextUniqueId();
Eric Laurent83b88082014-06-20 18:31:16 -07001618 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001619
1620 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001621 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001622
1623 return handle;
1624
1625}
1626
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001627// ----------------------------------------------------------------------------
1628
Glenn Kasten3b16c762012-11-14 08:44:39 -08001629uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001630{
1631 Mutex::Autolock _l(mLock);
1632 PlaybackThread *thread = primaryPlaybackThread_l();
1633 return thread != NULL ? thread->sampleRate() : 0;
1634}
1635
Glenn Kastene33054e2012-11-14 12:54:39 -08001636size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001637{
1638 Mutex::Autolock _l(mLock);
1639 PlaybackThread *thread = primaryPlaybackThread_l();
1640 return thread != NULL ? thread->frameCountHAL() : 0;
1641}
1642
1643// ----------------------------------------------------------------------------
1644
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001645status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1646{
1647 uid_t uid = IPCThreadState::self()->getCallingUid();
1648 if (uid != AID_SYSTEM) {
1649 return PERMISSION_DENIED;
1650 }
1651 Mutex::Autolock _l(mLock);
1652 if (mIsDeviceTypeKnown) {
1653 return INVALID_OPERATION;
1654 }
1655 mIsLowRamDevice = isLowRamDevice;
1656 mIsDeviceTypeKnown = true;
1657 return NO_ERROR;
1658}
1659
Eric Laurent93c3d412014-08-01 14:48:35 -07001660audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1661{
1662 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001663
1664 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1665 if (index >= 0) {
1666 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1667 mHwAvSyncIds.valueAt(index), sessionId);
1668 return mHwAvSyncIds.valueAt(index);
1669 }
1670
1671 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1672 if (dev == NULL) {
1673 return AUDIO_HW_SYNC_INVALID;
1674 }
1675 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1676 AudioParameter param = AudioParameter(String8(reply));
1677 free(reply);
1678
1679 int value;
1680 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1681 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1682 return AUDIO_HW_SYNC_INVALID;
1683 }
1684
1685 // allow only one session for a given HW A/V sync ID.
1686 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1687 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1688 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1689 value, mHwAvSyncIds.keyAt(i));
1690 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001691 break;
1692 }
1693 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001694
1695 mHwAvSyncIds.add(sessionId, value);
1696
1697 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1698 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1699 uint32_t sessions = thread->hasAudioSession(sessionId);
1700 if (sessions & PlaybackThread::TRACK_SESSION) {
1701 AudioParameter param = AudioParameter();
1702 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1703 thread->setParameters(param.toString());
1704 break;
1705 }
1706 }
1707
1708 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1709 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001710}
1711
Eric Laurentfa90e842014-10-17 18:12:31 -07001712// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1713void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1714{
1715 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1716 if (index >= 0) {
1717 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1718 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1719 AudioParameter param = AudioParameter();
1720 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1721 thread->setParameters(param.toString());
1722 }
1723}
1724
1725
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001726// ----------------------------------------------------------------------------
1727
Eric Laurent83b88082014-06-20 18:31:16 -07001728
1729sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001730 audio_io_handle_t *output,
1731 audio_config_t *config,
1732 audio_devices_t devices,
1733 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001734 audio_output_flags_t flags)
1735{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001736 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001737 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001738 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001739 }
1740
1741 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001742 if (*output == AUDIO_IO_HANDLE_NONE) {
1743 *output = nextUniqueId();
1744 }
Eric Laurent83b88082014-06-20 18:31:16 -07001745
1746 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1747
Eric Laurent83b88082014-06-20 18:31:16 -07001748 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001749 // This if statement allows overriding the audio policy settings
1750 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1751 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1752 // Check only for Normal Mixing mode
1753 if (kEnableExtendedPrecision) {
1754 // Specify format (uncomment one below to choose)
1755 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1756 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1757 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1758 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001759 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001760 }
1761 if (kEnableExtendedChannels) {
1762 // Specify channel mask (uncomment one below to choose)
1763 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1764 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1765 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1766 }
Eric Laurent83b88082014-06-20 18:31:16 -07001767 }
1768
Phil Burk062e67a2015-02-11 13:40:50 -08001769 AudioStreamOut *outputStream = NULL;
1770 status_t status = outHwDev->openOutputStream(
1771 &outputStream,
1772 *output,
1773 devices,
1774 flags,
1775 config,
1776 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001777
1778 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001779
Phil Burk062e67a2015-02-11 13:40:50 -08001780 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001781
1782 PlaybackThread *thread;
1783 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001784 thread = new OffloadThread(this, outputStream, *output, devices);
1785 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001786 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1787 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001788 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001789 thread = new DirectOutputThread(this, outputStream, *output, devices);
1790 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001791 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001792 thread = new MixerThread(this, outputStream, *output, devices);
1793 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001794 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001795 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001796 return thread;
1797 }
1798
1799 return 0;
1800}
1801
Eric Laurentcf2c0212014-07-25 16:20:43 -07001802status_t AudioFlinger::openOutput(audio_module_handle_t module,
1803 audio_io_handle_t *output,
1804 audio_config_t *config,
1805 audio_devices_t *devices,
1806 const String8& address,
1807 uint32_t *latencyMs,
1808 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809{
Phil Burk062e67a2015-02-11 13:40:50 -08001810 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001811 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001812 (devices != NULL) ? *devices : 0,
1813 config->sample_rate,
1814 config->format,
1815 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001816 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
Eric Laurentcf2c0212014-07-25 16:20:43 -07001818 if (*devices == AUDIO_DEVICE_NONE) {
1819 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001821
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 Mutex::Autolock _l(mLock);
1823
Eric Laurentcf2c0212014-07-25 16:20:43 -07001824 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001825 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001826 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827
1828 // notify client processes of the new output creation
Eric Laurent021cf962014-05-13 10:18:14 -07001829 thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001830
1831 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001832 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001833 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001834 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001835
1836 AutoMutex lock(mHardwareLock);
1837 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001838 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001839 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten4ea00a22014-06-02 08:29:22 -07001840
Eric Laurentcf2c0212014-07-25 16:20:43 -07001841 mPrimaryOutputSampleRate = config->sample_rate;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001842 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001843 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 }
1845
Eric Laurentcf2c0212014-07-25 16:20:43 -07001846 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001849audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1850 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851{
1852 Mutex::Autolock _l(mLock);
1853 MixerThread *thread1 = checkMixerThread_l(output1);
1854 MixerThread *thread2 = checkMixerThread_l(output2);
1855
1856 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001857 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1858 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001859 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 }
1861
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001862 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
1864 thread->addOutputTrack(thread2);
1865 mPlaybackThreads.add(id, thread);
1866 // notify client processes of the new output creation
Eric Laurent021cf962014-05-13 10:18:14 -07001867 thread->audioConfigChanged(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 return id;
1869}
1870
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001871status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872{
Glenn Kastend96c5722012-04-25 13:44:49 -07001873 return closeOutput_nonvirtual(output);
1874}
1875
1876status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1877{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 // keep strong reference on the playback thread so that
1879 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001880 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 {
1882 Mutex::Autolock _l(mLock);
1883 thread = checkPlaybackThread_l(output);
1884 if (thread == NULL) {
1885 return BAD_VALUE;
1886 }
1887
Steve Block3856b092011-10-20 11:56:00 +01001888 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001890 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001892 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001893 DuplicatingThread *dupThread =
1894 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001896
1897 }
1898 }
1899 }
1900
1901
1902 mPlaybackThreads.removeItem(output);
1903 // save all effects to the default thread
1904 if (mPlaybackThreads.size()) {
1905 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1906 if (dstThread != NULL) {
1907 // audioflinger lock is held here so the acquisition order of thread locks does not
1908 // matter
1909 Mutex::Autolock _dl(dstThread->mLock);
1910 Mutex::Autolock _sl(thread->mLock);
1911 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1912 for (size_t i = 0; i < effectChains.size(); i ++) {
1913 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 }
1915 }
1916 }
Eric Laurent021cf962014-05-13 10:18:14 -07001917 audioConfigChanged(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 }
1919 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001920 // The thread entity (active unit of execution) is no longer running here,
1921 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001923 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurent83b88082014-06-20 18:31:16 -07001924 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 }
Eric Laurent83b88082014-06-20 18:31:16 -07001926
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 return NO_ERROR;
1928}
1929
Eric Laurent83b88082014-06-20 18:31:16 -07001930void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1931{
1932 AudioStreamOut *out = thread->clearOutput();
1933 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1934 // from now on thread->mOutput is NULL
1935 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1936 delete out;
1937}
1938
1939void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1940{
1941 mPlaybackThreads.removeItem(thread->mId);
1942 thread->exit();
1943 closeOutputFinish(thread);
1944}
1945
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001946status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947{
1948 Mutex::Autolock _l(mLock);
1949 PlaybackThread *thread = checkPlaybackThread_l(output);
1950
1951 if (thread == NULL) {
1952 return BAD_VALUE;
1953 }
1954
Steve Block3856b092011-10-20 11:56:00 +01001955 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 thread->suspend();
1957
1958 return NO_ERROR;
1959}
1960
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001961status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962{
1963 Mutex::Autolock _l(mLock);
1964 PlaybackThread *thread = checkPlaybackThread_l(output);
1965
1966 if (thread == NULL) {
1967 return BAD_VALUE;
1968 }
1969
Steve Block3856b092011-10-20 11:56:00 +01001970 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971
1972 thread->restore();
1973
1974 return NO_ERROR;
1975}
1976
Eric Laurentcf2c0212014-07-25 16:20:43 -07001977status_t AudioFlinger::openInput(audio_module_handle_t module,
1978 audio_io_handle_t *input,
1979 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08001980 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001981 const String8& address,
1982 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07001983 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984{
Eric Laurent83b88082014-06-20 18:31:16 -07001985 Mutex::Autolock _l(mLock);
1986
Glenn Kastene7d66712015-03-05 13:46:52 -08001987 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001988 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07001989 }
1990
Glenn Kastene7d66712015-03-05 13:46:52 -08001991 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001992
1993 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07001994 // notify client processes of the new input creation
1995 thread->audioConfigChanged(AudioSystem::INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001996 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001998 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07001999}
Dima Zavin799a70e2011-04-18 16:57:27 -07002000
Eric Laurent83b88082014-06-20 18:31:16 -07002001sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002002 audio_io_handle_t *input,
2003 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002004 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002005 const String8& address,
2006 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002007 audio_input_flags_t flags)
2008{
Glenn Kastene7d66712015-03-05 13:46:52 -08002009 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002010 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002011 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002012 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002013 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002014
Eric Laurentcf2c0212014-07-25 16:20:43 -07002015 if (*input == AUDIO_IO_HANDLE_NONE) {
2016 *input = nextUniqueId();
2017 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002018
Eric Laurentcf2c0212014-07-25 16:20:43 -07002019 audio_config_t halconfig = *config;
2020 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002021 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002022 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002023 &inStream, flags, address.string(), source);
2024 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002025 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002027 halconfig.sample_rate,
2028 halconfig.format,
2029 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002030 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002031 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002033 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002034 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002035 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002036 audio_is_linear_pcm(config->format) &&
2037 audio_is_linear_pcm(halconfig.format) &&
2038 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Eric Laurentcf2c0212014-07-25 16:20:43 -07002039 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
2040 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002041 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002042 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002043 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002044 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002045 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002046 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 }
2048
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002049 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002050
Glenn Kasten46909e72013-02-26 09:20:22 -08002051#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002052 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2053 // or (re-)create if current Pipe is idle and does not match the new format
2054 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002055 enum {
2056 TEE_SINK_NO, // don't copy input
2057 TEE_SINK_NEW, // copy input using a new pipe
2058 TEE_SINK_OLD, // copy input using an existing pipe
2059 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002060 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2061 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002062 if (!mTeeSinkInputEnabled) {
2063 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002064 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002065 kind = TEE_SINK_NO;
2066 } else if (mRecordTeeSink == 0) {
2067 kind = TEE_SINK_NEW;
2068 } else if (mRecordTeeSink->getStrongCount() != 1) {
2069 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002070 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002071 kind = TEE_SINK_OLD;
2072 } else {
2073 kind = TEE_SINK_NEW;
2074 }
2075 switch (kind) {
2076 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002077 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002078 size_t numCounterOffers = 0;
2079 const NBAIO_Format offers[1] = {format};
2080 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2081 ALOG_ASSERT(index == 0);
2082 PipeReader *pipeReader = new PipeReader(*pipe);
2083 numCounterOffers = 0;
2084 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2085 ALOG_ASSERT(index == 0);
2086 mRecordTeeSink = pipe;
2087 mRecordTeeSource = pipeReader;
2088 teeSink = pipe;
2089 }
2090 break;
2091 case TEE_SINK_OLD:
2092 teeSink = mRecordTeeSink;
2093 break;
2094 case TEE_SINK_NO:
2095 default:
2096 break;
2097 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002098#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002099
Eric Laurentcf2c0212014-07-25 16:20:43 -07002100 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002101
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002102 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002103 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002104 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002105 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106 inputStream,
2107 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002108 primaryOutputDevice_l(),
Glenn Kastene7d66712015-03-05 13:46:52 -08002109 devices
Glenn Kasten46909e72013-02-26 09:20:22 -08002110#ifdef TEE_SINK
2111 , teeSink
2112#endif
2113 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002114 mRecordThreads.add(*input, thread);
2115 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002116 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 }
2118
Eric Laurentcf2c0212014-07-25 16:20:43 -07002119 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 return 0;
2121}
2122
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002123status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124{
Glenn Kastend96c5722012-04-25 13:44:49 -07002125 return closeInput_nonvirtual(input);
2126}
2127
2128status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2129{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 // keep strong reference on the record thread so that
2131 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002132 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133 {
2134 Mutex::Autolock _l(mLock);
2135 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002136 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 return BAD_VALUE;
2138 }
2139
Steve Block3856b092011-10-20 11:56:00 +01002140 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002141
2142 // If we still have effect chains, it means that a client still holds a handle
2143 // on at least one effect. We must either move the chain to an existing thread with the
2144 // same session ID or put it aside in case a new record thread is opened for a
2145 // new capture on the same session
2146 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002147 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002148 Mutex::Autolock _sl(thread->mLock);
2149 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002150 // Note: maximum one chain per record thread
2151 if (effectChains.size() != 0) {
2152 chain = effectChains[0];
2153 }
2154 }
2155 if (chain != 0) {
2156 // first check if a record thread is already opened with a client on the same session.
2157 // This should only happen in case of overlap between one thread tear down and the
2158 // creation of its replacement
2159 size_t i;
2160 for (i = 0; i < mRecordThreads.size(); i++) {
2161 sp<RecordThread> t = mRecordThreads.valueAt(i);
2162 if (t == thread) {
2163 continue;
2164 }
2165 if (t->hasAudioSession(chain->sessionId()) != 0) {
2166 Mutex::Autolock _l(t->mLock);
2167 ALOGV("closeInput() found thread %d for effect session %d",
2168 t->id(), chain->sessionId());
2169 t->addEffectChain_l(chain);
2170 break;
2171 }
2172 }
2173 // put the chain aside if we could not find a record thread with the same session id.
2174 if (i == mRecordThreads.size()) {
2175 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002176 }
2177 }
Eric Laurent021cf962014-05-13 10:18:14 -07002178 audioConfigChanged(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 mRecordThreads.removeItem(input);
2180 }
Eric Laurent83b88082014-06-20 18:31:16 -07002181 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2182 // we have a different lock for notification client
2183 closeInputFinish(thread);
2184 return NO_ERROR;
2185}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186
Eric Laurent83b88082014-06-20 18:31:16 -07002187void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2188{
2189 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002190 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002191 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002192 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002193 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002194 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002195}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196
Eric Laurent83b88082014-06-20 18:31:16 -07002197void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2198{
2199 mRecordThreads.removeItem(thread->mId);
2200 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201}
2202
Glenn Kastend2304db2014-02-03 07:40:31 -08002203status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204{
2205 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002206 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207
2208 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2209 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002210 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212
2213 return NO_ERROR;
2214}
2215
2216
Eric Laurentde3f8392014-07-27 18:38:22 -07002217audio_unique_id_t AudioFlinger::newAudioUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002219 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220}
2221
Marco Nelissend457c972014-02-11 08:47:07 -08002222void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002223{
2224 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002225 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002226 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2227 if (pid != -1 && (caller == getpid_cached)) {
2228 caller = pid;
2229 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002230
Eric Laurent021cf962014-05-13 10:18:14 -07002231 {
2232 Mutex::Autolock _cl(mClientLock);
2233 // Ignore requests received from processes not known as notification client. The request
2234 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2235 // called from a different pid leaving a stale session reference. Also we don't know how
2236 // to clear this reference if the client process dies.
2237 if (mNotificationClients.indexOfKey(caller) < 0) {
2238 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2239 return;
2240 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002241 }
2242
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002243 size_t num = mAudioSessionRefs.size();
2244 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002245 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002246 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2247 ref->mCnt++;
2248 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002249 return;
2250 }
2251 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002252 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2253 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002254}
2255
Marco Nelissend457c972014-02-11 08:47:07 -08002256void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002257{
2258 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002259 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002260 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2261 if (pid != -1 && (caller == getpid_cached)) {
2262 caller = pid;
2263 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002264 size_t num = mAudioSessionRefs.size();
2265 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002266 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002267 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2268 ref->mCnt--;
2269 ALOGV(" decremented refcount to %d", ref->mCnt);
2270 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002271 mAudioSessionRefs.removeAt(i);
2272 delete ref;
2273 purgeStaleEffects_l();
2274 }
2275 return;
2276 }
2277 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002278 // If the caller is mediaserver it is likely that the session being released was acquired
2279 // on behalf of a process not in notification clients and we ignore the warning.
2280 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002281}
2282
2283void AudioFlinger::purgeStaleEffects_l() {
2284
Steve Block3856b092011-10-20 11:56:00 +01002285 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002286
2287 Vector< sp<EffectChain> > chains;
2288
2289 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2290 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2291 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2292 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002293 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2294 chains.push(ec);
2295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002296 }
2297 }
2298 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2299 sp<RecordThread> t = mRecordThreads.valueAt(i);
2300 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2301 sp<EffectChain> ec = t->mEffectChains[j];
2302 chains.push(ec);
2303 }
2304 }
2305
2306 for (size_t i = 0; i < chains.size(); i++) {
2307 sp<EffectChain> ec = chains[i];
2308 int sessionid = ec->sessionId();
2309 sp<ThreadBase> t = ec->mThread.promote();
2310 if (t == 0) {
2311 continue;
2312 }
2313 size_t numsessionrefs = mAudioSessionRefs.size();
2314 bool found = false;
2315 for (size_t k = 0; k < numsessionrefs; k++) {
2316 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002317 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002318 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002319 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002320 found = true;
2321 break;
2322 }
2323 }
2324 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002325 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002326 // remove all effects from the chain
2327 while (ec->mEffects.size()) {
2328 sp<EffectModule> effect = ec->mEffects[0];
2329 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002330 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002331 if (effect->purgeHandles()) {
2332 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002333 }
2334 AudioSystem::unregisterEffect(effect->id());
2335 }
2336 }
2337 }
2338 return;
2339}
2340
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002342AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343{
Glenn Kastena1117922012-01-26 10:53:32 -08002344 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345}
2346
2347// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002348AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349{
2350 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002351 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352}
2353
2354// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002355AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356{
Glenn Kastena1117922012-01-26 10:53:32 -08002357 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358}
2359
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002360uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361{
Glenn Kastenbcefec32014-01-17 12:09:05 -08002362 return (uint32_t) android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363}
2364
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002365AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002366{
2367 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2368 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002369 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002370 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002371 return thread;
2372 }
2373 }
2374 return NULL;
2375}
2376
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002377audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002378{
2379 PlaybackThread *thread = primaryPlaybackThread_l();
2380
2381 if (thread == NULL) {
2382 return 0;
2383 }
2384
Eric Laurentf1c04f92012-08-28 14:26:53 -07002385 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002386}
2387
Eric Laurenta011e352012-03-29 15:51:43 -07002388sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2389 int triggerSession,
2390 int listenerSession,
2391 sync_event_callback_t callBack,
Eric Laurent8ea16e42014-02-20 16:26:11 -08002392 wp<RefBase> cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002393{
2394 Mutex::Autolock _l(mLock);
2395
2396 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2397 status_t playStatus = NAME_NOT_FOUND;
2398 status_t recStatus = NAME_NOT_FOUND;
2399 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2400 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2401 if (playStatus == NO_ERROR) {
2402 return event;
2403 }
2404 }
2405 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2406 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2407 if (recStatus == NO_ERROR) {
2408 return event;
2409 }
2410 }
2411 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2412 mPendingSyncEvents.add(event);
2413 } else {
2414 ALOGV("createSyncEvent() invalid event %d", event->type());
2415 event.clear();
2416 }
2417 return event;
2418}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002419
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420// ----------------------------------------------------------------------------
2421// Effect management
2422// ----------------------------------------------------------------------------
2423
2424
Glenn Kastenf587ba52012-01-26 16:25:10 -08002425status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426{
2427 Mutex::Autolock _l(mLock);
2428 return EffectQueryNumberEffects(numEffects);
2429}
2430
Glenn Kastenf587ba52012-01-26 16:25:10 -08002431status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432{
2433 Mutex::Autolock _l(mLock);
2434 return EffectQueryEffect(index, descriptor);
2435}
2436
Glenn Kasten5e92a782012-01-30 07:40:52 -08002437status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002438 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439{
2440 Mutex::Autolock _l(mLock);
2441 return EffectGetDescriptor(pUuid, descriptor);
2442}
2443
2444
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002445sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 effect_descriptor_t *pDesc,
2447 const sp<IEffectClient>& effectClient,
2448 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002449 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 int sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002451 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 status_t *status,
2453 int *id,
2454 int *enabled)
2455{
2456 status_t lStatus = NO_ERROR;
2457 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002460 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002461 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002462 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463
2464 if (pDesc == NULL) {
2465 lStatus = BAD_VALUE;
2466 goto Exit;
2467 }
2468
Eric Laurent84e9a102010-09-23 16:10:16 -07002469 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002470 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002471 lStatus = PERMISSION_DENIED;
2472 goto Exit;
2473 }
2474
Dima Zavinfce7a472011-04-19 22:30:36 -07002475 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002476 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002477 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002478 lStatus = PERMISSION_DENIED;
2479 goto Exit;
2480 }
2481
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483 if (!EffectIsNullUuid(&pDesc->uuid)) {
2484 // if uuid is specified, request effect descriptor
2485 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2486 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002487 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488 goto Exit;
2489 }
2490 } else {
2491 // if uuid is not specified, look for an available implementation
2492 // of the required type in effect factory
2493 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002494 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 lStatus = BAD_VALUE;
2496 goto Exit;
2497 }
2498 uint32_t numEffects = 0;
2499 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002500 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 bool found = false;
2502
2503 lStatus = EffectQueryNumberEffects(&numEffects);
2504 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002505 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 goto Exit;
2507 }
2508 for (uint32_t i = 0; i < numEffects; i++) {
2509 lStatus = EffectQueryEffect(i, &desc);
2510 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002511 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 continue;
2513 }
2514 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2515 // If matching type found save effect descriptor. If the session is
2516 // 0 and the effect is not auxiliary, continue enumeration in case
2517 // an auxiliary version of this effect type is available
2518 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002519 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002520 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2522 break;
2523 }
2524 }
2525 }
2526 if (!found) {
2527 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002528 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 goto Exit;
2530 }
2531 // For same effect type, chose auxiliary version over insert version if
2532 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002533 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002535 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 }
2537 }
2538
2539 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002540 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2542 lStatus = INVALID_OPERATION;
2543 goto Exit;
2544 }
2545
Eric Laurent59255e42011-07-27 19:49:51 -07002546 // check recording permission for visualizer
2547 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganovbe71aa22015-04-28 12:06:02 -07002548 !recordingAllowed(opPackageName)) {
Eric Laurent59255e42011-07-27 19:49:51 -07002549 lStatus = PERMISSION_DENIED;
2550 goto Exit;
2551 }
2552
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002554 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002555 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002556 // if the output returned by getOutputForEffect() is removed before we lock the
2557 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2558 // and we will exit safely
2559 io = AudioSystem::getOutputForEffect(&desc);
2560 ALOGV("createEffect got output %d", io);
2561 }
2562
2563 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564
2565 // If output is not specified try to find a matching audio session ID in one of the
2566 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002567 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2568 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002569 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002570 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002571 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2572 // output must be specified by AudioPolicyManager when using session
2573 // AUDIO_SESSION_OUTPUT_STAGE
2574 lStatus = BAD_VALUE;
2575 goto Exit;
2576 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002577 // look for the thread where the specified audio session is present
2578 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2579 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2580 io = mPlaybackThreads.keyAt(i);
2581 break;
2582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002584 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002585 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2586 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2587 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002588 break;
2589 }
2590 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002591 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002592 // If no output thread contains the requested session ID, default to
2593 // first output. The effect chain will be moved to the correct output
2594 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002595 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002596 io = mPlaybackThreads.keyAt(0);
2597 }
Steve Block3856b092011-10-20 11:56:00 +01002598 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002599 }
2600 ThreadBase *thread = checkRecordThread_l(io);
2601 if (thread == NULL) {
2602 thread = checkPlaybackThread_l(io);
2603 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002604 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002605 lStatus = BAD_VALUE;
2606 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002607 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002608 } else {
2609 // Check if one effect chain was awaiting for an effect to be created on this
2610 // session and used it instead of creating a new one.
2611 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2612 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002613 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002614 thread->addEffectChain_l(chain);
2615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002617
Eric Laurent021cf962014-05-13 10:18:14 -07002618 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002620 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002621 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2622 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 if (handle != 0 && id != NULL) {
2624 *id = handle->id();
2625 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002626 if (handle == 0) {
2627 // remove local strong reference to Client with mClientLock held
2628 Mutex::Autolock _cl(mClientLock);
2629 client.clear();
2630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 }
2632
2633Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002634 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 return handle;
2636}
2637
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002638status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2639 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002640{
Steve Block3856b092011-10-20 11:56:00 +01002641 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002642 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002643 Mutex::Autolock _l(mLock);
2644 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002645 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002646 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 }
Eric Laurentde070132010-07-13 04:45:46 -07002648 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2649 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002650 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002651 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 }
Eric Laurentde070132010-07-13 04:45:46 -07002653 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2654 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002655 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002656 return BAD_VALUE;
2657 }
2658
2659 Mutex::Autolock _dl(dstThread->mLock);
2660 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002661 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002662}
2663
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002664// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07002665status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002666 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002667 AudioFlinger::PlaybackThread *dstThread,
2668 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002669{
Steve Block3856b092011-10-20 11:56:00 +01002670 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002671 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002672
Eric Laurent59255e42011-07-27 19:49:51 -07002673 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002674 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002675 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002676 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002677 return INVALID_OPERATION;
2678 }
2679
Andy Hung9a592762014-07-21 21:56:01 -07002680 // Check whether the destination thread has a channel count of FCC_2, which is
2681 // currently required for (most) effects. Prevent moving the effect chain here rather
2682 // than disabling the addEffect_l() call in dstThread below.
Eric Laurentb10352f2014-11-03 16:25:39 -08002683 if ((dstThread->type() == ThreadBase::MIXER || dstThread->type() == ThreadBase::DUPLICATING) &&
2684 dstThread->mChannelCount != FCC_2) {
Andy Hung9a592762014-07-21 21:56:01 -07002685 ALOGW("moveEffectChain_l() effect chain failed because"
2686 " destination thread %p channel count(%u) != %u",
2687 dstThread, dstThread->mChannelCount, FCC_2);
2688 return INVALID_OPERATION;
2689 }
2690
Eric Laurent39e94f82010-07-28 01:32:47 -07002691 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002692 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002693 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002694 // removed.
2695 srcThread->removeEffectChain_l(chain);
2696
2697 // transfer all effects one by one so that new effect chain is created on new thread with
2698 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002699 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002700 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002701 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002702 Vector< sp<EffectModule> > removed;
2703 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002704 while (effect != 0) {
2705 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002706 removed.add(effect);
2707 status = dstThread->addEffect_l(effect);
2708 if (status != NO_ERROR) {
2709 break;
2710 }
Eric Laurentec35a142011-10-05 17:42:25 -07002711 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2712 if (effect->state() == EffectModule::ACTIVE ||
2713 effect->state() == EffectModule::STOPPING) {
2714 effect->start();
2715 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002716 // if the move request is not received from audio policy manager, the effect must be
2717 // re-registered with the new strategy and output
2718 if (dstChain == 0) {
2719 dstChain = effect->chain().promote();
2720 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002721 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002722 status = NO_INIT;
2723 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002724 }
2725 strategy = dstChain->strategy();
2726 }
2727 if (reRegister) {
2728 AudioSystem::unregisterEffect(effect->id());
2729 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002730 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002731 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002732 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002733 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002734 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002735 }
Eric Laurentde070132010-07-13 04:45:46 -07002736 effect = chain->getEffectFromId_l(0);
2737 }
2738
Eric Laurent5baf2af2013-09-12 17:37:00 -07002739 if (status != NO_ERROR) {
2740 for (size_t i = 0; i < removed.size(); i++) {
2741 srcThread->addEffect_l(removed[i]);
2742 if (dstChain != 0 && reRegister) {
2743 AudioSystem::unregisterEffect(removed[i]->id());
2744 AudioSystem::registerEffect(&removed[i]->desc(),
2745 srcThread->id(),
2746 strategy,
2747 sessionId,
2748 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002749 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002750 }
2751 }
2752 }
2753
2754 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755}
2756
Eric Laurent5baf2af2013-09-12 17:37:00 -07002757bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002758{
2759 if (mGlobalEffectEnableTime != 0 &&
2760 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2761 return true;
2762 }
2763
2764 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2765 sp<EffectChain> ec =
2766 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002767 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002768 return true;
2769 }
2770 }
2771 return false;
2772}
2773
Eric Laurent5baf2af2013-09-12 17:37:00 -07002774void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002775{
2776 Mutex::Autolock _l(mLock);
2777
2778 mGlobalEffectEnableTime = systemTime();
2779
2780 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2781 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2782 if (t->mType == ThreadBase::OFFLOAD) {
2783 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2784 }
2785 }
2786
2787}
2788
Eric Laurentaaa44472014-09-12 17:41:50 -07002789status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2790{
2791 audio_session_t session = (audio_session_t)chain->sessionId();
2792 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2793 ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2794 if (index >= 0) {
2795 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2796 return ALREADY_EXISTS;
2797 }
2798 mOrphanEffectChains.add(session, chain);
2799 return NO_ERROR;
2800}
2801
2802sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2803{
2804 sp<EffectChain> chain;
2805 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2806 ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2807 if (index >= 0) {
2808 chain = mOrphanEffectChains.valueAt(index);
2809 mOrphanEffectChains.removeItemsAt(index);
2810 }
2811 return chain;
2812}
2813
2814bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2815{
2816 Mutex::Autolock _l(mLock);
2817 audio_session_t session = (audio_session_t)effect->sessionId();
2818 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2819 ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2820 if (index >= 0) {
2821 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2822 if (chain->removeEffect_l(effect) == 0) {
2823 ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2824 mOrphanEffectChains.removeItemsAt(index);
2825 }
2826 return true;
2827 }
2828 return false;
2829}
2830
2831
Glenn Kastenda6ef132013-01-10 12:31:01 -08002832struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002833#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2834 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002835};
2836
2837int comparEntry(const void *p1, const void *p2)
2838{
Glenn Kasten2f55e762015-03-05 16:05:08 -08002839 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002840}
2841
Glenn Kasten46909e72013-02-26 09:20:22 -08002842#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002843void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844{
Eric Laurent81784c32012-11-19 14:55:58 -08002845 NBAIO_Source *teeSource = source.get();
2846 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002847 // .wav rotation
2848 // There is a benign race condition if 2 threads call this simultaneously.
2849 // They would both traverse the directory, but the result would simply be
2850 // failures at unlink() which are ignored. It's also unlikely since
2851 // normally dumpsys is only done by bugreport or from the command line.
2852 char teePath[32+256];
2853 strcpy(teePath, "/data/misc/media");
2854 size_t teePathLen = strlen(teePath);
2855 DIR *dir = opendir(teePath);
2856 teePath[teePathLen++] = '/';
2857 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002858#define TEE_MAX_SORT 20 // number of entries to sort
2859#define TEE_MAX_KEEP 10 // number of entries to keep
2860 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002861 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08002862 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002863 struct dirent de;
2864 struct dirent *result = NULL;
2865 int rc = readdir_r(dir, &de, &result);
2866 if (rc != 0) {
2867 ALOGW("readdir_r failed %d", rc);
2868 break;
2869 }
2870 if (result == NULL) {
2871 break;
2872 }
2873 if (result != &de) {
2874 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2875 break;
2876 }
2877 // ignore non .wav file entries
2878 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002879 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08002880 strcmp(&de.d_name[nameLen - 4], ".wav")) {
2881 continue;
2882 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08002883 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002884 }
2885 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002886 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002887 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002888 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
2889 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002890 (void) unlink(teePath);
2891 }
2892 }
2893 } else {
2894 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07002895 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08002896 }
2897 }
Eric Laurent81784c32012-11-19 14:55:58 -08002898 char teeTime[16];
2899 struct timeval tv;
2900 gettimeofday(&tv, NULL);
2901 struct tm tm;
2902 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002903 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2904 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2905 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2906 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08002907 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07002908 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08002909 char wavHeader[44];
2910 memcpy(wavHeader,
2911 "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",
2912 sizeof(wavHeader));
2913 NBAIO_Format format = teeSource->format();
2914 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002915 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07002916 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002917 wavHeader[22] = channelCount; // number of channels
2918 wavHeader[24] = sampleRate; // sample rate
2919 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07002920 wavHeader[32] = frameSize; // block alignment
2921 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08002922 write(teeFd, wavHeader, sizeof(wavHeader));
2923 size_t total = 0;
2924 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07002925#define TEE_SINK_READ 1024 // frames per I/O operation
2926 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002927 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08002928 size_t count = TEE_SINK_READ;
2929 ssize_t actual = teeSource->read(buffer, count,
2930 AudioBufferProvider::kInvalidPTS);
2931 bool wasFirstRead = firstRead;
2932 firstRead = false;
2933 if (actual <= 0) {
2934 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2935 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07002936 }
Eric Laurent81784c32012-11-19 14:55:58 -08002937 break;
Eric Laurent59255e42011-07-27 19:49:51 -07002938 }
Eric Laurent81784c32012-11-19 14:55:58 -08002939 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07002940 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002941 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07002942 }
Glenn Kasten329f6512014-08-28 16:23:16 -07002943 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002944 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07002945 uint32_t temp = 44 + total * frameSize - 8;
2946 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08002947 write(teeFd, &temp, sizeof(temp));
2948 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07002949 temp = total * frameSize;
2950 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08002951 write(teeFd, &temp, sizeof(temp));
2952 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002953 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07002954 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002955 }
Eric Laurent59255e42011-07-27 19:49:51 -07002956 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002957 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07002958 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08002959 }
Eric Laurent59255e42011-07-27 19:49:51 -07002960 }
2961 }
2962}
Glenn Kasten46909e72013-02-26 09:20:22 -08002963#endif
Eric Laurent59255e42011-07-27 19:49:51 -07002964
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965// ----------------------------------------------------------------------------
2966
2967status_t AudioFlinger::onTransact(
2968 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2969{
2970 return BnAudioFlinger::onTransact(code, data, reply, flags);
2971}
2972
Glenn Kasten63238ef2015-03-02 15:50:29 -08002973} // namespace android