blob: d2786b9e453880d4bf2795693ac7f3d06245775e [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>
Wei Jia3f273d12015-11-24 09:06:49 -080066#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070067#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080068
Mathias Agopian65ab4712010-07-14 17:59:35 -070069// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
John Grossman1c345192012-03-27 14:00:17 -070071// Note: the following macro is used for extremely verbose logging message. In
72// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
73// 0; but one side effect of this is to turn all LOGV's as well. Some messages
74// are so verbose that we want to suppress them even when we have ALOG_ASSERT
75// turned on. Do not uncomment the #def below unless you really know what you
76// are doing and want to see all of the extremely verbose messages.
77//#define VERY_VERY_VERBOSE_LOGGING
78#ifdef VERY_VERY_VERBOSE_LOGGING
79#define ALOGVV ALOGV
80#else
81#define ALOGVV(a...) do { } while(0)
82#endif
Eric Laurentde070132010-07-13 04:45:46 -070083
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Glenn Kastenec1d6b52011-12-12 09:04:45 -080086static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
87static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070088static const char kClientLockedString[] = "Client lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Glenn Kasten58912562012-04-03 10:45:00 -070090
John Grossman4ff14ba2012-02-08 16:37:41 -080091nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080092
Eric Laurent81784c32012-11-19 14:55:58 -080093uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -070094
Glenn Kasten46909e72013-02-26 09:20:22 -080095#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -080096bool AudioFlinger::mTeeSinkInputEnabled = false;
97bool AudioFlinger::mTeeSinkOutputEnabled = false;
98bool AudioFlinger::mTeeSinkTrackEnabled = false;
99
100size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
101size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
102size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800103#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800104
Eric Laurent813e2a72013-08-31 12:59:48 -0700105// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
106// we define a minimum time during which a global effect is considered enabled.
107static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109// ----------------------------------------------------------------------------
110
Marco Nelissenb2208842014-02-07 14:00:50 -0800111const char *formatToString(audio_format_t format) {
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530112 switch (format & AUDIO_FORMAT_MAIN_MASK) {
113 case AUDIO_FORMAT_PCM:
114 switch (format) {
115 case AUDIO_FORMAT_PCM_16_BIT: return "pcm16";
116 case AUDIO_FORMAT_PCM_8_BIT: return "pcm8";
117 case AUDIO_FORMAT_PCM_32_BIT: return "pcm32";
118 case AUDIO_FORMAT_PCM_8_24_BIT: return "pcm8.24";
119 case AUDIO_FORMAT_PCM_FLOAT: return "pcmfloat";
120 case AUDIO_FORMAT_PCM_24_BIT_PACKED: return "pcm24";
121 default:
122 break;
123 }
124 break;
Marco Nelissenb2208842014-02-07 14:00:50 -0800125 case AUDIO_FORMAT_MP3: return "mp3";
126 case AUDIO_FORMAT_AMR_NB: return "amr-nb";
127 case AUDIO_FORMAT_AMR_WB: return "amr-wb";
128 case AUDIO_FORMAT_AAC: return "aac";
129 case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
130 case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
131 case AUDIO_FORMAT_VORBIS: return "vorbis";
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530132 case AUDIO_FORMAT_OPUS: return "opus";
133 case AUDIO_FORMAT_AC3: return "ac-3";
134 case AUDIO_FORMAT_E_AC3: return "e-ac-3";
Marco Nelissenb2208842014-02-07 14:00:50 -0800135 default:
136 break;
137 }
138 return "unknown";
139}
140
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700141static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700142{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700143 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700144 int rc;
145
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700146 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
147 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
148 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
149 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700150 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700151 }
152 rc = audio_hw_device_open(mod, dev);
153 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
154 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
155 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700157 }
Eric Laurent5806b352014-05-22 12:23:26 -0700158 if ((*dev)->common.version < AUDIO_DEVICE_API_VERSION_MIN) {
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700159 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
160 rc = BAD_VALUE;
161 goto out;
162 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 return 0;
164
165out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 *dev = NULL;
167 return rc;
168}
169
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170// ----------------------------------------------------------------------------
171
172AudioFlinger::AudioFlinger()
173 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800175 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700176 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mMasterMute(false),
179 mNextUniqueId(1),
180 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700181 mBtNrecIsOff(false),
182 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700183 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700184 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700185 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700186{
Glenn Kasten949a9262013-04-16 12:35:20 -0700187 getpid_cached = getpid();
Andy Hungce717682015-12-22 13:40:32 -0800188 // disable media.log until the service is reenabled, see b/26306954
189 const bool doLog = false; // property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800190 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800191 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
192 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800193 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700194
Wei Jia3f273d12015-11-24 09:06:49 -0800195 // reset battery stats.
196 // if the audio service has crashed, battery stats could be left
197 // in bad state, reset the state upon service start.
198 BatteryNotifier::getInstance().noteResetAudio();
199
Glenn Kasten46909e72013-02-26 09:20:22 -0800200#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800201 (void) property_get("ro.debuggable", value, "0");
202 int debuggable = atoi(value);
203 int teeEnabled = 0;
204 if (debuggable) {
205 (void) property_get("af.tee", value, "0");
206 teeEnabled = atoi(value);
207 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800208 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700209 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800210 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700211 }
212 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800213 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700214 }
215 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800216 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700217 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800218#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700219}
220
221void AudioFlinger::onFirstRef()
222{
Dima Zavin799a70e2011-04-18 16:57:27 -0700223 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700224
Eric Laurent93575202011-01-18 18:39:02 -0800225 Mutex::Autolock _l(mLock);
226
Dima Zavin799a70e2011-04-18 16:57:27 -0700227 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 char val_str[PROPERTY_VALUE_MAX] = { 0 };
229 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
230 uint32_t int_val;
231 if (1 == sscanf(val_str, "%u", &int_val)) {
232 mStandbyTimeInNsecs = milliseconds(int_val);
233 ALOGI("Using %u mSec as standby time.", int_val);
234 } else {
235 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
236 ALOGI("Using default %u mSec as standby time.",
237 (uint32_t)(mStandbyTimeInNsecs / 1000000));
238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240
Eric Laurent1c333e22014-05-20 10:48:17 -0700241 mPatchPanel = new PatchPanel(this);
242
Eric Laurenta4c5a552012-03-29 10:12:40 -0700243 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244}
245
246AudioFlinger::~AudioFlinger()
247{
248 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700249 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700250 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251 }
252 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700253 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700254 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700255 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700256
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800257 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
258 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700259 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
260 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700262
263 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800264 if (mLogMemoryDealer != 0) {
265 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
266 if (binder != 0) {
267 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
268 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
269 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
270 mUnregisteredWriters.pop();
271 mediaLogService->unregisterWriter(iMemory);
272 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700273 }
274 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275}
276
Eric Laurenta4c5a552012-03-29 10:12:40 -0700277static const char * const audio_interfaces[] = {
278 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
279 AUDIO_HARDWARE_MODULE_ID_A2DP,
280 AUDIO_HARDWARE_MODULE_ID_USB,
281};
282#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
283
Phil Burk062e67a2015-02-11 13:40:50 -0800284AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700285 audio_module_handle_t module,
286 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700287{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700288 // if module is 0, the request comes from an old policy manager and we should load
289 // well known modules
290 if (module == 0) {
291 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
292 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
293 loadHwModule_l(audio_interfaces[i]);
294 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700295 // then try to find a module supporting the requested device.
296 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
297 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
298 audio_hw_device_t *dev = audioHwDevice->hwDevice();
299 if ((dev->get_supported_devices != NULL) &&
300 (dev->get_supported_devices(dev) & devices) == devices)
301 return audioHwDevice;
302 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700303 } else {
304 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700305 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
306 if (audioHwDevice != NULL) {
307 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700308 }
309 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700310
Dima Zavin799a70e2011-04-18 16:57:27 -0700311 return NULL;
312}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313
Glenn Kasten0f11b512014-01-31 16:18:54 -0800314void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315{
316 const size_t SIZE = 256;
317 char buffer[SIZE];
318 String8 result;
319
320 result.append("Clients:\n");
321 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800322 sp<Client> client = mClients.valueAt(i).promote();
323 if (client != 0) {
324 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
325 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 }
327 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700328
Eric Laurentd1b28d42013-09-18 18:47:13 -0700329 result.append("Notification Clients:\n");
330 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
331 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
332 result.append(buffer);
333 }
334
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700335 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800336 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700337 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
338 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800339 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700340 result.append(buffer);
341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700343}
344
345
Glenn Kasten0f11b512014-01-31 16:18:54 -0800346void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347{
348 const size_t SIZE = 256;
349 char buffer[SIZE];
350 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800351 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352
John Grossman4ff14ba2012-02-08 16:37:41 -0800353 snprintf(buffer, SIZE, "Hardware status: %d\n"
354 "Standby Time mSec: %u\n",
355 hardwareStatus,
356 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357 result.append(buffer);
358 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700359}
360
Glenn Kasten0f11b512014-01-31 16:18:54 -0800361void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362{
363 const size_t SIZE = 256;
364 char buffer[SIZE];
365 String8 result;
366 snprintf(buffer, SIZE, "Permission Denial: "
367 "can't dump AudioFlinger from pid=%d, uid=%d\n",
368 IPCThreadState::self()->getCallingPid(),
369 IPCThreadState::self()->getCallingUid());
370 result.append(buffer);
371 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372}
373
Eric Laurent81784c32012-11-19 14:55:58 -0800374bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375{
376 bool locked = false;
377 for (int i = 0; i < kDumpLockRetries; ++i) {
378 if (mutex.tryLock() == NO_ERROR) {
379 locked = true;
380 break;
381 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800382 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 }
384 return locked;
385}
386
387status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
388{
Glenn Kasten44deb052012-02-05 18:09:08 -0800389 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390 dumpPermissionDenial(fd, args);
391 } else {
392 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800393 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700394 if (!hardwareLocked) {
395 String8 result(kHardwareLockedString);
396 write(fd, result.string(), result.size());
397 } else {
398 mHardwareLock.unlock();
399 }
400
Eric Laurent81784c32012-11-19 14:55:58 -0800401 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402
403 // failed to lock - AudioFlinger is probably deadlocked
404 if (!locked) {
405 String8 result(kDeadlockedString);
406 write(fd, result.string(), result.size());
407 }
408
Eric Laurent021cf962014-05-13 10:18:14 -0700409 bool clientLocked = dumpTryLock(mClientLock);
410 if (!clientLocked) {
411 String8 result(kClientLockedString);
412 write(fd, result.string(), result.size());
413 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700414
415 EffectDumpEffects(fd);
416
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700418 if (clientLocked) {
419 mClientLock.unlock();
420 }
421
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422 dumpInternals(fd, args);
423
424 // dump playback threads
425 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
426 mPlaybackThreads.valueAt(i)->dump(fd, args);
427 }
428
429 // dump record threads
430 for (size_t i = 0; i < mRecordThreads.size(); i++) {
431 mRecordThreads.valueAt(i)->dump(fd, args);
432 }
433
Eric Laurentaaa44472014-09-12 17:41:50 -0700434 // dump orphan effect chains
435 if (mOrphanEffectChains.size() != 0) {
436 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
437 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
438 mOrphanEffectChains.valueAt(i)->dump(fd, args);
439 }
440 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700441 // dump all hardware devs
442 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700443 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700444 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700446
Glenn Kasten46909e72013-02-26 09:20:22 -0800447#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700448 // dump the serially shared record tee sink
449 if (mRecordTeeSource != 0) {
450 dumpTee(fd, mRecordTeeSource);
451 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800452#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700453
Glenn Kastend65d73c2012-06-22 17:21:07 -0700454 if (locked) {
455 mLock.unlock();
456 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800457
458 // append a copy of media.log here by forwarding fd to it, but don't attempt
459 // to lookup the service if it's not running, as it will block for a second
460 if (mLogMemoryDealer != 0) {
461 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
462 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700463 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800464 Vector<String16> args;
465 binder->dump(fd, args);
466 }
467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 }
469 return NO_ERROR;
470}
471
Eric Laurent021cf962014-05-13 10:18:14 -0700472sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800473{
Eric Laurent021cf962014-05-13 10:18:14 -0700474 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800475 // If pid is already in the mClients wp<> map, then use that entry
476 // (for which promote() is always != 0), otherwise create a new entry and Client.
477 sp<Client> client = mClients.valueFor(pid).promote();
478 if (client == 0) {
479 client = new Client(this, pid);
480 mClients.add(pid, client);
481 }
482
483 return client;
484}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485
Glenn Kasten9e58b552013-01-18 15:09:48 -0800486sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
487{
Glenn Kasten481fb672013-09-30 14:39:28 -0700488 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800489 if (mLogMemoryDealer == 0) {
490 return new NBLog::Writer();
491 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800492 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700493 // Similarly if we can't contact the media.log service, also return a dummy writer
494 if (binder == 0) {
495 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800496 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700497 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
498 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
499 // If allocation fails, consult the vector of previously unregistered writers
500 // and garbage-collect one or more them until an allocation succeeds
501 if (shared == 0) {
502 Mutex::Autolock _l(mUnregisteredWritersLock);
503 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
504 {
505 // Pick the oldest stale writer to garbage-collect
506 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
507 mUnregisteredWriters.removeAt(0);
508 mediaLogService->unregisterWriter(iMemory);
509 // Now the media.log remote reference to IMemory is gone. When our last local
510 // reference to IMemory also drops to zero at end of this block,
511 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
512 }
513 // Re-attempt the allocation
514 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
515 if (shared != 0) {
516 goto success;
517 }
518 }
519 // Even after garbage-collecting all old writers, there is still not enough memory,
520 // so return a dummy writer
521 return new NBLog::Writer();
522 }
523success:
524 mediaLogService->registerWriter(shared, size, name);
525 return new NBLog::Writer(size, shared);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800526}
527
528void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
529{
Glenn Kasten685ef092013-02-04 08:15:34 -0800530 if (writer == 0) {
531 return;
532 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800533 sp<IMemory> iMemory(writer->getIMemory());
534 if (iMemory == 0) {
535 return;
536 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700537 // Rather than removing the writer immediately, append it to a queue of old writers to
538 // be garbage-collected later. This allows us to continue to view old logs for a while.
539 Mutex::Autolock _l(mUnregisteredWritersLock);
540 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800541}
542
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543// IAudioFlinger interface
544
545
546sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800547 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800549 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700550 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800551 size_t *frameCount,
Glenn Kastene0b07172012-11-06 15:03:34 -0800552 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800554 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800555 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 int *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800557 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 status_t *status)
559{
560 sp<PlaybackThread::Track> track;
561 sp<TrackHandle> trackHandle;
562 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 status_t lStatus;
564 int lSessionId;
565
Glenn Kasten263709e2012-01-06 08:40:01 -0800566 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
567 // but if someone uses binder directly they could bypass that and cause us to crash
568 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000569 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 lStatus = BAD_VALUE;
571 goto Exit;
572 }
573
Glenn Kasten53b5d092014-02-05 10:00:23 -0800574 // further sample rate checks are performed by createTrack_l() depending on the thread type
575 if (sampleRate == 0) {
576 ALOGE("createTrack() invalid sample rate %u", sampleRate);
577 lStatus = BAD_VALUE;
578 goto Exit;
579 }
580
581 // further channel mask checks are performed by createTrack_l() depending on the thread type
582 if (!audio_is_output_channel(channelMask)) {
583 ALOGE("createTrack() invalid channel mask %#x", channelMask);
584 lStatus = BAD_VALUE;
585 goto Exit;
586 }
587
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700588 // further format checks are performed by createTrack_l() depending on the thread type
589 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800590 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700591 lStatus = BAD_VALUE;
592 goto Exit;
593 }
594
Glenn Kasten663c2242013-09-24 11:52:37 -0700595 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
596 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
597 lStatus = BAD_VALUE;
598 goto Exit;
599 }
600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 {
602 Mutex::Autolock _l(mLock);
603 PlaybackThread *thread = checkPlaybackThread_l(output);
604 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800605 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 lStatus = BAD_VALUE;
607 goto Exit;
608 }
609
Glenn Kasten8d6cc842012-02-03 11:06:53 -0800610 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -0700611 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612
Glenn Kastene848bd92014-03-13 15:00:32 -0700613 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700614 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700615 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700616 // check if an effect chain with the same session ID is present on another
617 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700618 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700619 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
620 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700621 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700622 if (sessions & PlaybackThread::EFFECT_SESSION) {
623 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700624 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700625 }
Eric Laurentde070132010-07-13 04:45:46 -0700626 }
627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700629 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700630 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 if (sessionId != NULL) {
632 *sessionId = lSessionId;
633 }
634 }
Steve Block3856b092011-10-20 11:56:00 +0100635 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
637 track = thread->createTrack_l(client, streamType, sampleRate, format,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800638 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, clientUid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800639 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700640 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700641
642 // move effect chain to this output thread if an effect on same session was waiting
643 // for a track to be created
644 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700645 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700646 Mutex::Autolock _dl(thread->mLock);
647 Mutex::Autolock _sl(effectThread->mLock);
648 moveEffectChain_l(lSessionId, effectThread, thread, true);
649 }
Eric Laurenta011e352012-03-29 15:51:43 -0700650
651 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700652 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700653 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
654 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700655 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700656 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700657 } else {
658 mPendingSyncEvents[i]->cancel();
659 }
Eric Laurenta011e352012-03-29 15:51:43 -0700660 mPendingSyncEvents.removeAt(i);
661 i--;
662 }
663 }
664 }
Glenn Kastene198c362013-08-13 09:13:36 -0700665
Eric Laurentfa90e842014-10-17 18:12:31 -0700666 setAudioHwSyncForSession_l(thread, (audio_session_t)lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 }
Glenn Kastene198c362013-08-13 09:13:36 -0700668
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700669 if (lStatus != NO_ERROR) {
670 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700671 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700672 // Don't hold mClientLock when releasing the reference on the track as the
673 // destructor will acquire it.
674 {
675 Mutex::Autolock _cl(mClientLock);
676 client.clear();
677 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700679 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700680 }
681
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700682 // return handle to client
683 trackHandle = new TrackHandle(track);
684
Mathias Agopian65ab4712010-07-14 17:59:35 -0700685Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700686 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700687 return trackHandle;
688}
689
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800690uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691{
692 Mutex::Autolock _l(mLock);
693 PlaybackThread *thread = checkPlaybackThread_l(output);
694 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000695 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 return 0;
697 }
698 return thread->sampleRate();
699}
700
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800701audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702{
703 Mutex::Autolock _l(mLock);
704 PlaybackThread *thread = checkPlaybackThread_l(output);
705 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000706 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800707 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 }
709 return thread->format();
710}
711
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800712size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713{
714 Mutex::Autolock _l(mLock);
715 PlaybackThread *thread = checkPlaybackThread_l(output);
716 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000717 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 return 0;
719 }
Glenn Kasten58912562012-04-03 10:45:00 -0700720 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
721 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 return thread->frameCount();
723}
724
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800725uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726{
727 Mutex::Autolock _l(mLock);
728 PlaybackThread *thread = checkPlaybackThread_l(output);
729 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800730 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 return 0;
732 }
733 return thread->latency();
734}
735
736status_t AudioFlinger::setMasterVolume(float value)
737{
Eric Laurenta1884f92011-08-23 08:25:03 -0700738 status_t ret = initCheck();
739 if (ret != NO_ERROR) {
740 return ret;
741 }
742
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 // check calling permissions
744 if (!settingsAllowed()) {
745 return PERMISSION_DENIED;
746 }
747
Eric Laurenta4c5a552012-03-29 10:12:40 -0700748 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700749 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700750
John Grossmanee578c02012-07-23 17:05:46 -0700751 // Set master volume in the HALs which support it.
752 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
753 AutoMutex lock(mHardwareLock);
754 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800755
John Grossmanee578c02012-07-23 17:05:46 -0700756 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
757 if (dev->canSetMasterVolume()) {
758 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800759 }
John Grossmanee578c02012-07-23 17:05:46 -0700760 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762
John Grossmanee578c02012-07-23 17:05:46 -0700763 // Now set the master volume in each playback thread. Playback threads
764 // assigned to HALs which do not have master volume support will apply
765 // master volume during the mix operation. Threads with HALs which do
766 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700767 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
768 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
769 continue;
770 }
John Grossmanee578c02012-07-23 17:05:46 -0700771 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773
774 return NO_ERROR;
775}
776
Glenn Kastenf78aee72012-01-04 11:00:47 -0800777status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778{
Eric Laurenta1884f92011-08-23 08:25:03 -0700779 status_t ret = initCheck();
780 if (ret != NO_ERROR) {
781 return ret;
782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783
784 // check calling permissions
785 if (!settingsAllowed()) {
786 return PERMISSION_DENIED;
787 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800788 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000789 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 return BAD_VALUE;
791 }
792
793 { // scope for the lock
794 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700795 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700797 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 mHardwareStatus = AUDIO_HW_IDLE;
799 }
800
801 if (NO_ERROR == ret) {
802 Mutex::Autolock _l(mLock);
803 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800804 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700805 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 }
807
808 return ret;
809}
810
811status_t AudioFlinger::setMicMute(bool state)
812{
Eric Laurenta1884f92011-08-23 08:25:03 -0700813 status_t ret = initCheck();
814 if (ret != NO_ERROR) {
815 return ret;
816 }
817
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 // check calling permissions
819 if (!settingsAllowed()) {
820 return PERMISSION_DENIED;
821 }
822
823 AutoMutex lock(mHardwareLock);
824 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700825 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
826 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
827 status_t result = dev->set_mic_mute(dev, state);
828 if (result != NO_ERROR) {
829 ret = result;
830 }
831 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 mHardwareStatus = AUDIO_HW_IDLE;
833 return ret;
834}
835
836bool AudioFlinger::getMicMute() const
837{
Eric Laurenta1884f92011-08-23 08:25:03 -0700838 status_t ret = initCheck();
839 if (ret != NO_ERROR) {
840 return false;
841 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800842 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700843 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800844 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800846 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
847 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
848 status_t result = dev->get_mic_mute(dev, &state);
849 if (result == NO_ERROR) {
850 mute = mute && state;
851 }
852 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800854
855 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856}
857
858status_t AudioFlinger::setMasterMute(bool muted)
859{
John Grossmand8f178d2012-07-20 14:51:35 -0700860 status_t ret = initCheck();
861 if (ret != NO_ERROR) {
862 return ret;
863 }
864
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 // check calling permissions
866 if (!settingsAllowed()) {
867 return PERMISSION_DENIED;
868 }
869
John Grossmanee578c02012-07-23 17:05:46 -0700870 Mutex::Autolock _l(mLock);
871 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700872
John Grossmanee578c02012-07-23 17:05:46 -0700873 // Set master mute in the HALs which support it.
874 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
875 AutoMutex lock(mHardwareLock);
876 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700877
John Grossmanee578c02012-07-23 17:05:46 -0700878 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
879 if (dev->canSetMasterMute()) {
880 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700881 }
John Grossmanee578c02012-07-23 17:05:46 -0700882 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700883 }
884
John Grossmanee578c02012-07-23 17:05:46 -0700885 // Now set the master mute in each playback thread. Playback threads
886 // assigned to HALs which do not have master mute support will apply master
887 // mute during the mix operation. Threads with HALs which do support master
888 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700889 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
890 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
891 continue;
892 }
John Grossmanee578c02012-07-23 17:05:46 -0700893 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700894 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895
896 return NO_ERROR;
897}
898
899float AudioFlinger::masterVolume() const
900{
Glenn Kasten98067102011-12-13 11:47:54 -0800901 Mutex::Autolock _l(mLock);
902 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903}
904
905bool AudioFlinger::masterMute() const
906{
Glenn Kasten98067102011-12-13 11:47:54 -0800907 Mutex::Autolock _l(mLock);
908 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909}
910
John Grossman4ff14ba2012-02-08 16:37:41 -0800911float AudioFlinger::masterVolume_l() const
912{
John Grossman4ff14ba2012-02-08 16:37:41 -0800913 return mMasterVolume;
914}
915
John Grossmand8f178d2012-07-20 14:51:35 -0700916bool AudioFlinger::masterMute_l() const
917{
John Grossmanee578c02012-07-23 17:05:46 -0700918 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700919}
920
Eric Laurent223fd5c2014-11-11 13:43:36 -0800921status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
922{
923 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
924 ALOGW("setStreamVolume() invalid stream %d", stream);
925 return BAD_VALUE;
926 }
927 pid_t caller = IPCThreadState::self()->getCallingPid();
928 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
929 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
930 return PERMISSION_DENIED;
931 }
932
933 return NO_ERROR;
934}
935
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800936status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
937 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938{
939 // check calling permissions
940 if (!settingsAllowed()) {
941 return PERMISSION_DENIED;
942 }
943
Eric Laurent223fd5c2014-11-11 13:43:36 -0800944 status_t status = checkStreamType(stream);
945 if (status != NO_ERROR) {
946 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800948 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949
950 AutoMutex lock(mLock);
951 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700952 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 thread = checkPlaybackThread_l(output);
954 if (thread == NULL) {
955 return BAD_VALUE;
956 }
957 }
958
959 mStreamTypes[stream].volume = value;
960
961 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800962 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700963 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 }
965 } else {
966 thread->setStreamVolume(stream, value);
967 }
968
969 return NO_ERROR;
970}
971
Glenn Kastenfff6d712012-01-12 16:38:12 -0800972status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973{
974 // check calling permissions
975 if (!settingsAllowed()) {
976 return PERMISSION_DENIED;
977 }
978
Eric Laurent223fd5c2014-11-11 13:43:36 -0800979 status_t status = checkStreamType(stream);
980 if (status != NO_ERROR) {
981 return status;
982 }
983 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
984
985 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000986 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 return BAD_VALUE;
988 }
989
Eric Laurent93575202011-01-18 18:39:02 -0800990 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700992 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700993 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994
995 return NO_ERROR;
996}
997
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800998float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001000 status_t status = checkStreamType(stream);
1001 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 return 0.0f;
1003 }
1004
1005 AutoMutex lock(mLock);
1006 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001007 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 PlaybackThread *thread = checkPlaybackThread_l(output);
1009 if (thread == NULL) {
1010 return 0.0f;
1011 }
1012 volume = thread->streamVolume(stream);
1013 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001014 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 }
1016
1017 return volume;
1018}
1019
Glenn Kastenfff6d712012-01-12 16:38:12 -08001020bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001022 status_t status = checkStreamType(stream);
1023 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024 return true;
1025 }
1026
Glenn Kasten6637baa2012-01-09 09:40:36 -08001027 AutoMutex lock(mLock);
1028 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029}
1030
Eric Laurent054d9d32015-04-24 08:48:48 -07001031
1032void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1033{
1034 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1035 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1036 }
1037}
1038
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001039status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001041 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1042 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001043
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 // check calling permissions
1045 if (!settingsAllowed()) {
1046 return PERMISSION_DENIED;
1047 }
1048
Glenn Kasten142f5192014-03-25 17:44:59 -07001049 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1050 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001051 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001052 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001053 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001054 AutoMutex lock(mHardwareLock);
1055 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1056 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1057 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
1058 status_t result = dev->set_parameters(dev, keyValuePairs.string());
1059 final_result = result ?: final_result;
1060 }
1061 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001062 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001063 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1064 AudioParameter param = AudioParameter(keyValuePairs);
1065 String8 value;
1066 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -07001067 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
1068 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001069 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1070 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001071 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001072 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1073 // collect all of the thread's session IDs
1074 KeyedVector<int, bool> ids = thread->sessionIds();
1075 // suspend effects associated with those session IDs
1076 for (size_t j = 0; j < ids.size(); ++j) {
1077 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001078 thread->setEffectSuspended(FX_IID_AEC,
1079 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001080 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001081 thread->setEffectSuspended(FX_IID_NS,
1082 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001083 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001084 }
1085 }
Eric Laurentbee53372011-08-29 12:42:48 -07001086 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001087 }
1088 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001089 String8 screenState;
1090 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1091 bool isOff = screenState == "off";
Eric Laurent81784c32012-11-19 14:55:58 -08001092 if (isOff != (AudioFlinger::mScreenState & 1)) {
1093 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001094 }
1095 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001096 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001097 }
1098
1099 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1100 // and the thread is exited once the lock is released
1101 sp<ThreadBase> thread;
1102 {
1103 Mutex::Autolock _l(mLock);
1104 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001105 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001107 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001108 // indicate output device change to all input threads for pre processing
1109 AudioParameter param = AudioParameter(keyValuePairs);
1110 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001111 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1112 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001113 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 }
1116 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001117 if (thread != 0) {
1118 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 }
1120 return BAD_VALUE;
1121}
1122
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001123String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001125 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1126 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127
Eric Laurenta4c5a552012-03-29 10:12:40 -07001128 Mutex::Autolock _l(mLock);
1129
Glenn Kasten142f5192014-03-25 17:44:59 -07001130 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001131 String8 out_s8;
1132
Dima Zavin799a70e2011-04-18 16:57:27 -07001133 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001134 char *s;
1135 {
1136 AutoMutex lock(mHardwareLock);
1137 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001138 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001139 s = dev->get_parameters(dev, keys.string());
1140 mHardwareStatus = AUDIO_HW_IDLE;
1141 }
John Grossmanef7740b2012-02-09 11:28:36 -08001142 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -07001143 free(s);
1144 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001145 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 }
1147
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1149 if (playbackThread != NULL) {
1150 return playbackThread->getParameters(keys);
1151 }
1152 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1153 if (recordThread != NULL) {
1154 return recordThread->getParameters(keys);
1155 }
1156 return String8("");
1157}
1158
Glenn Kastendd8104c2012-07-02 12:42:44 -07001159size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1160 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161{
Eric Laurenta1884f92011-08-23 08:25:03 -07001162 status_t ret = initCheck();
1163 if (ret != NO_ERROR) {
1164 return 0;
1165 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001166 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
1167 return 0;
1168 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001169
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001170 AutoMutex lock(mHardwareLock);
1171 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001172 audio_config_t config, proposed;
1173 memset(&proposed, 0, sizeof(proposed));
1174 proposed.sample_rate = sampleRate;
1175 proposed.channel_mask = channelMask;
1176 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001177
John Grossmanee578c02012-07-23 17:05:46 -07001178 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001179 size_t frames;
1180 for (;;) {
1181 // Note: config is currently a const parameter for get_input_buffer_size()
1182 // but we use a copy from proposed in case config changes from the call.
1183 config = proposed;
1184 frames = dev->get_input_buffer_size(dev, &config);
1185 if (frames != 0) {
1186 break; // hal success, config is the result
1187 }
1188 // change one parameter of the configuration each iteration to a more "common" value
1189 // to see if the device will support it.
1190 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1191 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1192 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1193 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1194 } else {
1195 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1196 "format %#x, channelMask 0x%X",
1197 sampleRate, format, channelMask);
1198 break; // retries failed, break out of loop with frames == 0.
1199 }
1200 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001201 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001202 if (frames > 0 && config.sample_rate != sampleRate) {
1203 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1204 }
1205 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206}
1207
Glenn Kasten5f972c02014-01-13 09:59:31 -08001208uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 Mutex::Autolock _l(mLock);
1211
1212 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1213 if (recordThread != NULL) {
1214 return recordThread->getInputFramesLost();
1215 }
1216 return 0;
1217}
1218
1219status_t AudioFlinger::setVoiceVolume(float value)
1220{
Eric Laurenta1884f92011-08-23 08:25:03 -07001221 status_t ret = initCheck();
1222 if (ret != NO_ERROR) {
1223 return ret;
1224 }
1225
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 // check calling permissions
1227 if (!settingsAllowed()) {
1228 return PERMISSION_DENIED;
1229 }
1230
1231 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001232 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001233 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001234 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 mHardwareStatus = AUDIO_HW_IDLE;
1236
1237 return ret;
1238}
1239
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001240status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001241 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242{
1243 status_t status;
1244
1245 Mutex::Autolock _l(mLock);
1246
1247 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1248 if (playbackThread != NULL) {
1249 return playbackThread->getRenderPosition(halFrames, dspFrames);
1250 }
1251
1252 return BAD_VALUE;
1253}
1254
1255void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1256{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001258 if (client == 0) {
1259 return;
1260 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001261 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001262 {
1263 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001264 if (mNotificationClients.indexOfKey(pid) < 0) {
1265 sp<NotificationClient> notificationClient = new NotificationClient(this,
1266 client,
1267 pid);
1268 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269
Eric Laurent021cf962014-05-13 10:18:14 -07001270 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271
Marco Nelissen06b46062014-11-14 07:58:25 -08001272 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001273 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001274 }
1275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276
Eric Laurent021cf962014-05-13 10:18:14 -07001277 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001278 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001279 // the config change is always sent from playback or record threads to avoid deadlock
1280 // with AudioSystem::gLock
1281 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1282 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1283 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001285 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1286 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287 }
1288}
1289
1290void AudioFlinger::removeNotificationClient(pid_t pid)
1291{
1292 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001293 {
1294 Mutex::Autolock _cl(mClientLock);
1295 mNotificationClients.removeItem(pid);
1296 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001297
Steve Block3856b092011-10-20 11:56:00 +01001298 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001299 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001300 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001301 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001302 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001303 ALOGV(" pid %d @ %d", ref->mPid, i);
1304 if (ref->mPid == pid) {
1305 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001306 mAudioSessionRefs.removeAt(i);
1307 delete ref;
1308 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001309 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001310 } else {
1311 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001312 }
1313 }
1314 if (removed) {
1315 purgeStaleEffects_l();
1316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317}
1318
Eric Laurent73e26b62015-04-27 16:55:58 -07001319void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001320 const sp<AudioIoDescriptor>& ioDesc,
1321 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322{
Eric Laurent021cf962014-05-13 10:18:14 -07001323 Mutex::Autolock _l(mClientLock);
1324 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001326 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1327 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329 }
1330}
1331
Eric Laurent021cf962014-05-13 10:18:14 -07001332// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001333void AudioFlinger::removeClient_l(pid_t pid)
1334{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001335 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001336 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337 mClients.removeItem(pid);
1338}
1339
Eric Laurent717e1282012-06-29 16:36:52 -07001340// getEffectThread_l() must be called with AudioFlinger::mLock held
1341sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1342{
1343 sp<PlaybackThread> thread;
1344
1345 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1346 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1347 ALOG_ASSERT(thread == 0);
1348 thread = mPlaybackThreads.valueAt(i);
1349 }
1350 }
1351
1352 return thread;
1353}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356
1357// ----------------------------------------------------------------------------
1358
1359AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1360 : RefBase(),
1361 mAudioFlinger(audioFlinger),
John Grossman4ff14ba2012-02-08 16:37:41 -08001362 mPid(pid),
1363 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364{
Eric Laurentda73b6c2015-08-20 16:18:53 -07001365 size_t heapSize = kClientSharedHeapSizeBytes;
1366 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1367 // invalidated tracks
1368 if (!audioFlinger->isLowRamDevice()) {
1369 heapSize *= kClientSharedHeapSizeMultiplier;
1370 }
1371 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372}
1373
Eric Laurent021cf962014-05-13 10:18:14 -07001374// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375AudioFlinger::Client::~Client()
1376{
1377 mAudioFlinger->removeClient_l(mPid);
1378}
1379
Glenn Kasten435dbe62012-01-30 10:15:48 -08001380sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381{
1382 return mMemoryDealer;
1383}
1384
John Grossman4ff14ba2012-02-08 16:37:41 -08001385// Reserve one of the limited slots for a timed audio track associated
1386// with this client
1387bool AudioFlinger::Client::reserveTimedTrack()
1388{
1389 const int kMaxTimedTracksPerClient = 4;
1390
1391 Mutex::Autolock _l(mTimedTrackLock);
1392
1393 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
1394 ALOGW("can not create timed track - pid %d has exceeded the limit",
1395 mPid);
1396 return false;
1397 }
1398
1399 mTimedTrackCount++;
1400 return true;
1401}
1402
1403// Release a slot for a timed audio track
1404void AudioFlinger::Client::releaseTimedTrack()
1405{
1406 Mutex::Autolock _l(mTimedTrackLock);
1407 mTimedTrackCount--;
1408}
1409
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410// ----------------------------------------------------------------------------
1411
1412AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1413 const sp<IAudioFlingerClient>& client,
1414 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001415 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416{
1417}
1418
1419AudioFlinger::NotificationClient::~NotificationClient()
1420{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421}
1422
Glenn Kasten0f11b512014-01-31 16:18:54 -08001423void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424{
1425 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001426 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427}
1428
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429
1430// ----------------------------------------------------------------------------
1431
Jeff Brown893a5642013-08-16 20:19:26 -07001432static bool deviceRequiresCaptureAudioOutputPermission(audio_devices_t inDevice) {
1433 return audio_is_remote_submix_device(inDevice);
1434}
1435
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001437 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001439 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001440 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001441 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001442 size_t *frameCount,
Glenn Kasteneeca3262013-07-31 16:12:48 -07001443 IAudioFlinger::track_flags_t *flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001444 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001445 int clientUid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446 int *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001447 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001448 sp<IMemory>& cblk,
1449 sp<IMemory>& buffers,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450 status_t *status)
1451{
1452 sp<RecordThread::RecordTrack> recordTrack;
1453 sp<RecordHandle> recordHandle;
1454 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 int lSessionId;
1457
Glenn Kastend776ac62014-05-07 09:16:09 -07001458 cblk.clear();
1459 buffers.clear();
1460
Marco Nelissendcb346b2015-09-09 10:47:29 -07001461 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1462 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001463 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001464 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1465 clientUid = callingUid;
1466 }
1467
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001469 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001470 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 lStatus = PERMISSION_DENIED;
1472 goto Exit;
1473 }
1474
Glenn Kasten53b5d092014-02-05 10:00:23 -08001475 // further sample rate checks are performed by createRecordTrack_l()
1476 if (sampleRate == 0) {
1477 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1478 lStatus = BAD_VALUE;
1479 goto Exit;
1480 }
1481
Andy Hung6770c6f2015-04-07 13:43:36 -07001482 // we don't yet support anything other than linear PCM
1483 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001484 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001485 lStatus = BAD_VALUE;
1486 goto Exit;
1487 }
1488
Glenn Kasten53b5d092014-02-05 10:00:23 -08001489 // further channel mask checks are performed by createRecordTrack_l()
1490 if (!audio_is_input_channel(channelMask)) {
1491 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1492 lStatus = BAD_VALUE;
1493 goto Exit;
1494 }
1495
Glenn Kasten05997e22014-03-13 15:08:33 -07001496 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001498 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001500 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
1504
Glenn Kasten8d6cc842012-02-03 11:06:53 -08001505 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001506 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001508 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 lSessionId = *sessionId;
1510 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001511 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001512 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 if (sessionId != NULL) {
1514 *sessionId = lSessionId;
1515 }
1516 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001517 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001518
Glenn Kasten1879fff2012-07-11 15:36:59 -07001519 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001520 frameCount, lSessionId, notificationFrames,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001521 clientUid, flags, tid, &lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001522 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001523
1524 if (lStatus == NO_ERROR) {
1525 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1526 // session and move it to this thread.
1527 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)lSessionId);
1528 if (chain != 0) {
1529 Mutex::Autolock _l(thread->mLock);
1530 thread->addEffectChain_l(chain);
1531 }
1532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 }
Glenn Kastene198c362013-08-13 09:13:36 -07001534
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001535 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001536 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001537 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001538 // Don't hold mClientLock when releasing the reference on the track as the
1539 // destructor will acquire it.
1540 {
1541 Mutex::Autolock _cl(mClientLock);
1542 client.clear();
1543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 goto Exit;
1546 }
1547
Glenn Kastend776ac62014-05-07 09:16:09 -07001548 cblk = recordTrack->getCblk();
1549 buffers = recordTrack->getBuffers();
1550
Glenn Kasten2fc14732013-08-05 14:58:14 -07001551 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553
1554Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001555 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 return recordHandle;
1557}
1558
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001559
1560
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561// ----------------------------------------------------------------------------
1562
Eric Laurenta4c5a552012-03-29 10:12:40 -07001563audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1564{
Eric Laurent44622db2014-08-01 19:00:33 -07001565 if (name == NULL) {
1566 return 0;
1567 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001568 if (!settingsAllowed()) {
1569 return 0;
1570 }
1571 Mutex::Autolock _l(mLock);
1572 return loadHwModule_l(name);
1573}
1574
1575// loadHwModule_l() must be called with AudioFlinger::mLock held
1576audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1577{
1578 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1579 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1580 ALOGW("loadHwModule() module %s already loaded", name);
1581 return mAudioHwDevs.keyAt(i);
1582 }
1583 }
1584
Eric Laurenta4c5a552012-03-29 10:12:40 -07001585 audio_hw_device_t *dev;
1586
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001587 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001588 if (rc) {
1589 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
1590 return 0;
1591 }
1592
1593 mHardwareStatus = AUDIO_HW_INIT;
1594 rc = dev->init_check(dev);
1595 mHardwareStatus = AUDIO_HW_IDLE;
1596 if (rc) {
1597 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
1598 return 0;
1599 }
1600
John Grossmanee578c02012-07-23 17:05:46 -07001601 // Check and cache this HAL's level of support for master mute and master
1602 // volume. If this is the first HAL opened, and it supports the get
1603 // methods, use the initial values provided by the HAL as the current
1604 // master mute and volume settings.
1605
1606 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1607 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001608 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001609
1610 if (0 == mAudioHwDevs.size()) {
1611 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
1612 if (NULL != dev->get_master_volume) {
1613 float mv;
1614 if (OK == dev->get_master_volume(dev, &mv)) {
1615 mMasterVolume = mv;
1616 }
1617 }
1618
1619 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
1620 if (NULL != dev->get_master_mute) {
1621 bool mm;
1622 if (OK == dev->get_master_mute(dev, &mm)) {
1623 mMasterMute = mm;
1624 }
1625 }
1626 }
1627
Eric Laurenta4c5a552012-03-29 10:12:40 -07001628 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001629 if ((NULL != dev->set_master_volume) &&
1630 (OK == dev->set_master_volume(dev, mMasterVolume))) {
1631 flags = static_cast<AudioHwDevice::Flags>(flags |
1632 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1633 }
1634
1635 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1636 if ((NULL != dev->set_master_mute) &&
1637 (OK == dev->set_master_mute(dev, mMasterMute))) {
1638 flags = static_cast<AudioHwDevice::Flags>(flags |
1639 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1640 }
1641
Eric Laurenta4c5a552012-03-29 10:12:40 -07001642 mHardwareStatus = AUDIO_HW_IDLE;
1643 }
1644
1645 audio_module_handle_t handle = nextUniqueId();
Eric Laurent83b88082014-06-20 18:31:16 -07001646 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001647
1648 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001649 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001650
1651 return handle;
1652
1653}
1654
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001655// ----------------------------------------------------------------------------
1656
Glenn Kasten3b16c762012-11-14 08:44:39 -08001657uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001658{
1659 Mutex::Autolock _l(mLock);
1660 PlaybackThread *thread = primaryPlaybackThread_l();
1661 return thread != NULL ? thread->sampleRate() : 0;
1662}
1663
Glenn Kastene33054e2012-11-14 12:54:39 -08001664size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001665{
1666 Mutex::Autolock _l(mLock);
1667 PlaybackThread *thread = primaryPlaybackThread_l();
1668 return thread != NULL ? thread->frameCountHAL() : 0;
1669}
1670
1671// ----------------------------------------------------------------------------
1672
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001673status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1674{
1675 uid_t uid = IPCThreadState::self()->getCallingUid();
1676 if (uid != AID_SYSTEM) {
1677 return PERMISSION_DENIED;
1678 }
1679 Mutex::Autolock _l(mLock);
1680 if (mIsDeviceTypeKnown) {
1681 return INVALID_OPERATION;
1682 }
1683 mIsLowRamDevice = isLowRamDevice;
1684 mIsDeviceTypeKnown = true;
1685 return NO_ERROR;
1686}
1687
Eric Laurent93c3d412014-08-01 14:48:35 -07001688audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1689{
1690 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001691
1692 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1693 if (index >= 0) {
1694 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1695 mHwAvSyncIds.valueAt(index), sessionId);
1696 return mHwAvSyncIds.valueAt(index);
1697 }
1698
1699 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1700 if (dev == NULL) {
1701 return AUDIO_HW_SYNC_INVALID;
1702 }
1703 char *reply = dev->get_parameters(dev, AUDIO_PARAMETER_HW_AV_SYNC);
1704 AudioParameter param = AudioParameter(String8(reply));
1705 free(reply);
1706
1707 int value;
1708 if (param.getInt(String8(AUDIO_PARAMETER_HW_AV_SYNC), value) != NO_ERROR) {
1709 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1710 return AUDIO_HW_SYNC_INVALID;
1711 }
1712
1713 // allow only one session for a given HW A/V sync ID.
1714 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1715 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1716 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1717 value, mHwAvSyncIds.keyAt(i));
1718 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001719 break;
1720 }
1721 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001722
1723 mHwAvSyncIds.add(sessionId, value);
1724
1725 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1726 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1727 uint32_t sessions = thread->hasAudioSession(sessionId);
1728 if (sessions & PlaybackThread::TRACK_SESSION) {
1729 AudioParameter param = AudioParameter();
1730 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), value);
1731 thread->setParameters(param.toString());
1732 break;
1733 }
1734 }
1735
1736 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1737 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001738}
1739
Eric Laurent72e3f392015-05-20 14:43:50 -07001740status_t AudioFlinger::systemReady()
1741{
1742 Mutex::Autolock _l(mLock);
1743 ALOGI("%s", __FUNCTION__);
1744 if (mSystemReady) {
1745 ALOGW("%s called twice", __FUNCTION__);
1746 return NO_ERROR;
1747 }
1748 mSystemReady = true;
1749 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1750 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1751 thread->systemReady();
1752 }
1753 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1754 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1755 thread->systemReady();
1756 }
1757 return NO_ERROR;
1758}
1759
Eric Laurentfa90e842014-10-17 18:12:31 -07001760// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1761void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1762{
1763 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1764 if (index >= 0) {
1765 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1766 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1767 AudioParameter param = AudioParameter();
1768 param.addInt(String8(AUDIO_PARAMETER_STREAM_HW_AV_SYNC), syncId);
1769 thread->setParameters(param.toString());
1770 }
1771}
1772
1773
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001774// ----------------------------------------------------------------------------
1775
Eric Laurent83b88082014-06-20 18:31:16 -07001776
1777sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001778 audio_io_handle_t *output,
1779 audio_config_t *config,
1780 audio_devices_t devices,
1781 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001782 audio_output_flags_t flags)
1783{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001784 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001785 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001786 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001787 }
1788
1789 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001790 if (*output == AUDIO_IO_HANDLE_NONE) {
1791 *output = nextUniqueId();
1792 }
Eric Laurent83b88082014-06-20 18:31:16 -07001793
1794 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1795
Eric Laurent83b88082014-06-20 18:31:16 -07001796 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001797 // This if statement allows overriding the audio policy settings
1798 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1799 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1800 // Check only for Normal Mixing mode
1801 if (kEnableExtendedPrecision) {
1802 // Specify format (uncomment one below to choose)
1803 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1804 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1805 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1806 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001807 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001808 }
1809 if (kEnableExtendedChannels) {
1810 // Specify channel mask (uncomment one below to choose)
1811 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1812 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1813 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1814 }
Eric Laurent83b88082014-06-20 18:31:16 -07001815 }
1816
Phil Burk062e67a2015-02-11 13:40:50 -08001817 AudioStreamOut *outputStream = NULL;
1818 status_t status = outHwDev->openOutputStream(
1819 &outputStream,
1820 *output,
1821 devices,
1822 flags,
1823 config,
1824 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001825
1826 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001827
Phil Burk062e67a2015-02-11 13:40:50 -08001828 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001829
1830 PlaybackThread *thread;
1831 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001832 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001833 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001834 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1835 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001836 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001837 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001838 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001839 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001840 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001841 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001842 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001843 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001844 return thread;
1845 }
1846
1847 return 0;
1848}
1849
Eric Laurentcf2c0212014-07-25 16:20:43 -07001850status_t AudioFlinger::openOutput(audio_module_handle_t module,
1851 audio_io_handle_t *output,
1852 audio_config_t *config,
1853 audio_devices_t *devices,
1854 const String8& address,
1855 uint32_t *latencyMs,
1856 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857{
Phil Burk062e67a2015-02-11 13:40:50 -08001858 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001859 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001860 (devices != NULL) ? *devices : 0,
1861 config->sample_rate,
1862 config->format,
1863 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001864 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865
Eric Laurentcf2c0212014-07-25 16:20:43 -07001866 if (*devices == AUDIO_DEVICE_NONE) {
1867 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001869
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 Mutex::Autolock _l(mLock);
1871
Eric Laurentcf2c0212014-07-25 16:20:43 -07001872 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001873 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001874 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875
1876 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001877 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001878
1879 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001880 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001881 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001882 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001883
1884 AutoMutex lock(mHardwareLock);
1885 mHardwareStatus = AUDIO_HW_SET_MODE;
Eric Laurent83b88082014-06-20 18:31:16 -07001886 mPrimaryHardwareDev->hwDevice()->set_mode(mPrimaryHardwareDev->hwDevice(), mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001887 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001888 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001889 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 }
1891
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893}
1894
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001895audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1896 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897{
1898 Mutex::Autolock _l(mLock);
1899 MixerThread *thread1 = checkMixerThread_l(output1);
1900 MixerThread *thread2 = checkMixerThread_l(output2);
1901
1902 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001903 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1904 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001905 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 }
1907
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001908 audio_io_handle_t id = nextUniqueId();
Eric Laurent72e3f392015-05-20 14:43:50 -07001909 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 thread->addOutputTrack(thread2);
1911 mPlaybackThreads.add(id, thread);
1912 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001913 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914 return id;
1915}
1916
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001917status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918{
Glenn Kastend96c5722012-04-25 13:44:49 -07001919 return closeOutput_nonvirtual(output);
1920}
1921
1922status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1923{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 // keep strong reference on the playback thread so that
1925 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001926 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 {
1928 Mutex::Autolock _l(mLock);
1929 thread = checkPlaybackThread_l(output);
1930 if (thread == NULL) {
1931 return BAD_VALUE;
1932 }
1933
Steve Block3856b092011-10-20 11:56:00 +01001934 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001936 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001938 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001939 DuplicatingThread *dupThread =
1940 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 }
1943 }
1944 }
1945
1946
1947 mPlaybackThreads.removeItem(output);
1948 // save all effects to the default thread
1949 if (mPlaybackThreads.size()) {
1950 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1951 if (dstThread != NULL) {
1952 // audioflinger lock is held here so the acquisition order of thread locks does not
1953 // matter
1954 Mutex::Autolock _dl(dstThread->mLock);
1955 Mutex::Autolock _sl(thread->mLock);
1956 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1957 for (size_t i = 0; i < effectChains.size(); i ++) {
1958 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 }
1960 }
1961 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001962 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1963 ioDesc->mIoHandle = output;
1964 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 }
1966 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001967 // The thread entity (active unit of execution) is no longer running here,
1968 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969
Eric Laurentf6870ae2015-05-08 10:50:03 -07001970 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07001971 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
Eric Laurent83b88082014-06-20 18:31:16 -07001973
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 return NO_ERROR;
1975}
1976
Eric Laurent83b88082014-06-20 18:31:16 -07001977void AudioFlinger::closeOutputFinish(sp<PlaybackThread> thread)
1978{
1979 AudioStreamOut *out = thread->clearOutput();
1980 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1981 // from now on thread->mOutput is NULL
1982 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
1983 delete out;
1984}
1985
1986void AudioFlinger::closeOutputInternal_l(sp<PlaybackThread> thread)
1987{
1988 mPlaybackThreads.removeItem(thread->mId);
1989 thread->exit();
1990 closeOutputFinish(thread);
1991}
1992
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001993status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994{
1995 Mutex::Autolock _l(mLock);
1996 PlaybackThread *thread = checkPlaybackThread_l(output);
1997
1998 if (thread == NULL) {
1999 return BAD_VALUE;
2000 }
2001
Steve Block3856b092011-10-20 11:56:00 +01002002 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 thread->suspend();
2004
2005 return NO_ERROR;
2006}
2007
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002008status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009{
2010 Mutex::Autolock _l(mLock);
2011 PlaybackThread *thread = checkPlaybackThread_l(output);
2012
2013 if (thread == NULL) {
2014 return BAD_VALUE;
2015 }
2016
Steve Block3856b092011-10-20 11:56:00 +01002017 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018
2019 thread->restore();
2020
2021 return NO_ERROR;
2022}
2023
Eric Laurentcf2c0212014-07-25 16:20:43 -07002024status_t AudioFlinger::openInput(audio_module_handle_t module,
2025 audio_io_handle_t *input,
2026 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002027 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002028 const String8& address,
2029 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002030 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031{
Eric Laurent83b88082014-06-20 18:31:16 -07002032 Mutex::Autolock _l(mLock);
2033
Glenn Kastene7d66712015-03-05 13:46:52 -08002034 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002035 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002036 }
2037
Glenn Kastene7d66712015-03-05 13:46:52 -08002038 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002039
2040 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002041 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002042 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002043 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002045 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002046}
Dima Zavin799a70e2011-04-18 16:57:27 -07002047
Eric Laurent83b88082014-06-20 18:31:16 -07002048sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002049 audio_io_handle_t *input,
2050 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002051 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002052 const String8& address,
2053 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002054 audio_input_flags_t flags)
2055{
Glenn Kastene7d66712015-03-05 13:46:52 -08002056 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002057 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002058 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002059 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002060 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002061
Eric Laurentcf2c0212014-07-25 16:20:43 -07002062 if (*input == AUDIO_IO_HANDLE_NONE) {
2063 *input = nextUniqueId();
2064 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002065
Eric Laurentcf2c0212014-07-25 16:20:43 -07002066 audio_config_t halconfig = *config;
2067 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Glenn Kasten32550952013-08-06 10:45:10 -07002068 audio_stream_in_t *inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002069 status_t status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002070 &inStream, flags, address.string(), source);
2071 ALOGV("openInput_l() openInputStream returned input %p, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002072 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Dima Zavin799a70e2011-04-18 16:57:27 -07002073 inStream,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002074 halconfig.sample_rate,
2075 halconfig.format,
2076 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002077 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002078 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002080 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002081 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002082 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002083 audio_is_linear_pcm(config->format) &&
2084 audio_is_linear_pcm(halconfig.format) &&
2085 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
Eric Laurentcf2c0212014-07-25 16:20:43 -07002086 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_2) &&
2087 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_2)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002088 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002089 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002090 inStream = NULL;
Glenn Kastene7d66712015-03-05 13:46:52 -08002091 status = inHwHal->open_input_stream(inHwHal, *input, devices, &halconfig,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002092 &inStream, flags, address.string(), source);
Glenn Kasten85948432013-08-19 12:09:05 -07002093 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 }
2095
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002096 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002097
Glenn Kasten46909e72013-02-26 09:20:22 -08002098#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002099 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2100 // or (re-)create if current Pipe is idle and does not match the new format
2101 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002102 enum {
2103 TEE_SINK_NO, // don't copy input
2104 TEE_SINK_NEW, // copy input using a new pipe
2105 TEE_SINK_OLD, // copy input using an existing pipe
2106 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002107 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2108 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002109 if (!mTeeSinkInputEnabled) {
2110 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002111 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002112 kind = TEE_SINK_NO;
2113 } else if (mRecordTeeSink == 0) {
2114 kind = TEE_SINK_NEW;
2115 } else if (mRecordTeeSink->getStrongCount() != 1) {
2116 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002117 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002118 kind = TEE_SINK_OLD;
2119 } else {
2120 kind = TEE_SINK_NEW;
2121 }
2122 switch (kind) {
2123 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002124 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002125 size_t numCounterOffers = 0;
2126 const NBAIO_Format offers[1] = {format};
2127 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2128 ALOG_ASSERT(index == 0);
2129 PipeReader *pipeReader = new PipeReader(*pipe);
2130 numCounterOffers = 0;
2131 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2132 ALOG_ASSERT(index == 0);
2133 mRecordTeeSink = pipe;
2134 mRecordTeeSource = pipeReader;
2135 teeSink = pipe;
2136 }
2137 break;
2138 case TEE_SINK_OLD:
2139 teeSink = mRecordTeeSink;
2140 break;
2141 case TEE_SINK_NO:
2142 default:
2143 break;
2144 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002145#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002146
Eric Laurentcf2c0212014-07-25 16:20:43 -07002147 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002148
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002149 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002150 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002151 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002152 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002153 inputStream,
2154 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002155 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002156 devices,
2157 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002158#ifdef TEE_SINK
2159 , teeSink
2160#endif
2161 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002162 mRecordThreads.add(*input, thread);
2163 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002164 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 }
2166
Eric Laurentcf2c0212014-07-25 16:20:43 -07002167 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 return 0;
2169}
2170
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002171status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172{
Glenn Kastend96c5722012-04-25 13:44:49 -07002173 return closeInput_nonvirtual(input);
2174}
2175
2176status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2177{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 // keep strong reference on the record thread so that
2179 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002180 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 {
2182 Mutex::Autolock _l(mLock);
2183 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002184 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 return BAD_VALUE;
2186 }
2187
Steve Block3856b092011-10-20 11:56:00 +01002188 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002189
2190 // If we still have effect chains, it means that a client still holds a handle
2191 // on at least one effect. We must either move the chain to an existing thread with the
2192 // same session ID or put it aside in case a new record thread is opened for a
2193 // new capture on the same session
2194 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002195 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002196 Mutex::Autolock _sl(thread->mLock);
2197 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002198 // Note: maximum one chain per record thread
2199 if (effectChains.size() != 0) {
2200 chain = effectChains[0];
2201 }
2202 }
2203 if (chain != 0) {
2204 // first check if a record thread is already opened with a client on the same session.
2205 // This should only happen in case of overlap between one thread tear down and the
2206 // creation of its replacement
2207 size_t i;
2208 for (i = 0; i < mRecordThreads.size(); i++) {
2209 sp<RecordThread> t = mRecordThreads.valueAt(i);
2210 if (t == thread) {
2211 continue;
2212 }
2213 if (t->hasAudioSession(chain->sessionId()) != 0) {
2214 Mutex::Autolock _l(t->mLock);
2215 ALOGV("closeInput() found thread %d for effect session %d",
2216 t->id(), chain->sessionId());
2217 t->addEffectChain_l(chain);
2218 break;
2219 }
2220 }
2221 // put the chain aside if we could not find a record thread with the same session id.
2222 if (i == mRecordThreads.size()) {
2223 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002224 }
2225 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002226 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2227 ioDesc->mIoHandle = input;
2228 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 mRecordThreads.removeItem(input);
2230 }
Eric Laurent83b88082014-06-20 18:31:16 -07002231 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2232 // we have a different lock for notification client
2233 closeInputFinish(thread);
2234 return NO_ERROR;
2235}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236
Eric Laurent83b88082014-06-20 18:31:16 -07002237void AudioFlinger::closeInputFinish(sp<RecordThread> thread)
2238{
2239 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002240 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002241 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002242 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07002243 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07002244 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002245}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246
Eric Laurent83b88082014-06-20 18:31:16 -07002247void AudioFlinger::closeInputInternal_l(sp<RecordThread> thread)
2248{
2249 mRecordThreads.removeItem(thread->mId);
2250 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251}
2252
Glenn Kastend2304db2014-02-03 07:40:31 -08002253status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254{
2255 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002256 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257
2258 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2259 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002260 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262
2263 return NO_ERROR;
2264}
2265
2266
Eric Laurentde3f8392014-07-27 18:38:22 -07002267audio_unique_id_t AudioFlinger::newAudioUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002269 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270}
2271
Marco Nelissend457c972014-02-11 08:47:07 -08002272void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002273{
2274 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002275 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002276 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2277 if (pid != -1 && (caller == getpid_cached)) {
2278 caller = pid;
2279 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002280
Eric Laurent021cf962014-05-13 10:18:14 -07002281 {
2282 Mutex::Autolock _cl(mClientLock);
2283 // Ignore requests received from processes not known as notification client. The request
2284 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2285 // called from a different pid leaving a stale session reference. Also we don't know how
2286 // to clear this reference if the client process dies.
2287 if (mNotificationClients.indexOfKey(caller) < 0) {
2288 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2289 return;
2290 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002291 }
2292
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002293 size_t num = mAudioSessionRefs.size();
2294 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002295 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002296 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2297 ref->mCnt++;
2298 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002299 return;
2300 }
2301 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002302 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2303 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002304}
2305
Marco Nelissend457c972014-02-11 08:47:07 -08002306void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002307{
2308 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002309 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002310 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2311 if (pid != -1 && (caller == getpid_cached)) {
2312 caller = pid;
2313 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002314 size_t num = mAudioSessionRefs.size();
2315 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002316 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002317 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2318 ref->mCnt--;
2319 ALOGV(" decremented refcount to %d", ref->mCnt);
2320 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002321 mAudioSessionRefs.removeAt(i);
2322 delete ref;
2323 purgeStaleEffects_l();
2324 }
2325 return;
2326 }
2327 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002328 // If the caller is mediaserver it is likely that the session being released was acquired
2329 // on behalf of a process not in notification clients and we ignore the warning.
2330 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002331}
2332
2333void AudioFlinger::purgeStaleEffects_l() {
2334
Steve Block3856b092011-10-20 11:56:00 +01002335 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002336
2337 Vector< sp<EffectChain> > chains;
2338
2339 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2340 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2341 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2342 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002343 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2344 chains.push(ec);
2345 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002346 }
2347 }
2348 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2349 sp<RecordThread> t = mRecordThreads.valueAt(i);
2350 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2351 sp<EffectChain> ec = t->mEffectChains[j];
2352 chains.push(ec);
2353 }
2354 }
2355
2356 for (size_t i = 0; i < chains.size(); i++) {
2357 sp<EffectChain> ec = chains[i];
2358 int sessionid = ec->sessionId();
2359 sp<ThreadBase> t = ec->mThread.promote();
2360 if (t == 0) {
2361 continue;
2362 }
2363 size_t numsessionrefs = mAudioSessionRefs.size();
2364 bool found = false;
2365 for (size_t k = 0; k < numsessionrefs; k++) {
2366 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002367 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002368 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002369 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002370 found = true;
2371 break;
2372 }
2373 }
2374 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002375 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002376 // remove all effects from the chain
2377 while (ec->mEffects.size()) {
2378 sp<EffectModule> effect = ec->mEffects[0];
2379 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002380 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002381 if (effect->purgeHandles()) {
2382 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002383 }
2384 AudioSystem::unregisterEffect(effect->id());
2385 }
2386 }
2387 }
2388 return;
2389}
2390
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002392AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393{
Glenn Kastena1117922012-01-26 10:53:32 -08002394 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
2397// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002398AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399{
2400 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002401 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402}
2403
2404// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002405AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406{
Glenn Kastena1117922012-01-26 10:53:32 -08002407 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408}
2409
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002410uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002411{
Glenn Kastenbcefec32014-01-17 12:09:05 -08002412 return (uint32_t) android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413}
2414
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002415AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002416{
2417 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2418 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002419 if(thread->isDuplicating()) {
2420 continue;
2421 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002422 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002423 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002424 return thread;
2425 }
2426 }
2427 return NULL;
2428}
2429
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002430audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002431{
2432 PlaybackThread *thread = primaryPlaybackThread_l();
2433
2434 if (thread == NULL) {
2435 return 0;
2436 }
2437
Eric Laurentf1c04f92012-08-28 14:26:53 -07002438 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002439}
2440
Eric Laurenta011e352012-03-29 15:51:43 -07002441sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
2442 int triggerSession,
2443 int listenerSession,
2444 sync_event_callback_t callBack,
Eric Laurent8ea16e42014-02-20 16:26:11 -08002445 wp<RefBase> cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002446{
2447 Mutex::Autolock _l(mLock);
2448
2449 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2450 status_t playStatus = NAME_NOT_FOUND;
2451 status_t recStatus = NAME_NOT_FOUND;
2452 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2453 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2454 if (playStatus == NO_ERROR) {
2455 return event;
2456 }
2457 }
2458 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2459 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2460 if (recStatus == NO_ERROR) {
2461 return event;
2462 }
2463 }
2464 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2465 mPendingSyncEvents.add(event);
2466 } else {
2467 ALOGV("createSyncEvent() invalid event %d", event->type());
2468 event.clear();
2469 }
2470 return event;
2471}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002472
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473// ----------------------------------------------------------------------------
2474// Effect management
2475// ----------------------------------------------------------------------------
2476
2477
Glenn Kastenf587ba52012-01-26 16:25:10 -08002478status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479{
2480 Mutex::Autolock _l(mLock);
2481 return EffectQueryNumberEffects(numEffects);
2482}
2483
Glenn Kastenf587ba52012-01-26 16:25:10 -08002484status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485{
2486 Mutex::Autolock _l(mLock);
2487 return EffectQueryEffect(index, descriptor);
2488}
2489
Glenn Kasten5e92a782012-01-30 07:40:52 -08002490status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002491 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492{
2493 Mutex::Autolock _l(mLock);
2494 return EffectGetDescriptor(pUuid, descriptor);
2495}
2496
2497
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002498sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499 effect_descriptor_t *pDesc,
2500 const sp<IEffectClient>& effectClient,
2501 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002502 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 int sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002504 const String16& opPackageName,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 status_t *status,
2506 int *id,
2507 int *enabled)
2508{
2509 status_t lStatus = NO_ERROR;
2510 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002513 pid_t pid = IPCThreadState::self()->getCallingPid();
Glenn Kasten98ec94c2012-01-25 14:28:29 -08002514 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002515 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516
2517 if (pDesc == NULL) {
2518 lStatus = BAD_VALUE;
2519 goto Exit;
2520 }
2521
Eric Laurent84e9a102010-09-23 16:10:16 -07002522 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002523 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002524 lStatus = PERMISSION_DENIED;
2525 goto Exit;
2526 }
2527
Dima Zavinfce7a472011-04-19 22:30:36 -07002528 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002529 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002530 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002531 lStatus = PERMISSION_DENIED;
2532 goto Exit;
2533 }
2534
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 if (!EffectIsNullUuid(&pDesc->uuid)) {
2537 // if uuid is specified, request effect descriptor
2538 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
2539 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002540 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 goto Exit;
2542 }
2543 } else {
2544 // if uuid is not specified, look for an available implementation
2545 // of the required type in effect factory
2546 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002547 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 lStatus = BAD_VALUE;
2549 goto Exit;
2550 }
2551 uint32_t numEffects = 0;
2552 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002553 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554 bool found = false;
2555
2556 lStatus = EffectQueryNumberEffects(&numEffects);
2557 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002558 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 goto Exit;
2560 }
2561 for (uint32_t i = 0; i < numEffects; i++) {
2562 lStatus = EffectQueryEffect(i, &desc);
2563 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002564 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 continue;
2566 }
2567 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2568 // If matching type found save effect descriptor. If the session is
2569 // 0 and the effect is not auxiliary, continue enumeration in case
2570 // an auxiliary version of this effect type is available
2571 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002572 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002573 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2575 break;
2576 }
2577 }
2578 }
2579 if (!found) {
2580 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002581 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 goto Exit;
2583 }
2584 // For same effect type, chose auxiliary version over insert version if
2585 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002586 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002588 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 }
2590 }
2591
2592 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002593 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2595 lStatus = INVALID_OPERATION;
2596 goto Exit;
2597 }
2598
Eric Laurent59255e42011-07-27 19:49:51 -07002599 // check recording permission for visualizer
2600 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002601 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002602 lStatus = PERMISSION_DENIED;
2603 goto Exit;
2604 }
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002607 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002608 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002609 // if the output returned by getOutputForEffect() is removed before we lock the
2610 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2611 // and we will exit safely
2612 io = AudioSystem::getOutputForEffect(&desc);
2613 ALOGV("createEffect got output %d", io);
2614 }
2615
2616 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617
2618 // If output is not specified try to find a matching audio session ID in one of the
2619 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002620 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2621 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002622 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002623 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002624 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2625 // output must be specified by AudioPolicyManager when using session
2626 // AUDIO_SESSION_OUTPUT_STAGE
2627 lStatus = BAD_VALUE;
2628 goto Exit;
2629 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002630 // look for the thread where the specified audio session is present
2631 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2632 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2633 io = mPlaybackThreads.keyAt(i);
2634 break;
2635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002637 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002638 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2639 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2640 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002641 break;
2642 }
2643 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002644 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002645 // If no output thread contains the requested session ID, default to
2646 // first output. The effect chain will be moved to the correct output
2647 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002648 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002649 io = mPlaybackThreads.keyAt(0);
2650 }
Steve Block3856b092011-10-20 11:56:00 +01002651 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002652 }
2653 ThreadBase *thread = checkRecordThread_l(io);
2654 if (thread == NULL) {
2655 thread = checkPlaybackThread_l(io);
2656 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002657 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002658 lStatus = BAD_VALUE;
2659 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002660 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002661 } else {
2662 // Check if one effect chain was awaiting for an effect to be created on this
2663 // session and used it instead of creating a new one.
2664 sp<EffectChain> chain = getOrphanEffectChain_l((audio_session_t)sessionId);
2665 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002666 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002667 thread->addEffectChain_l(chain);
2668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002670
Eric Laurent021cf962014-05-13 10:18:14 -07002671 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002673 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07002674 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
2675 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 if (handle != 0 && id != NULL) {
2677 *id = handle->id();
2678 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002679 if (handle == 0) {
2680 // remove local strong reference to Client with mClientLock held
2681 Mutex::Autolock _cl(mClientLock);
2682 client.clear();
2683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 }
2685
2686Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002687 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688 return handle;
2689}
2690
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002691status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
2692 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002693{
Steve Block3856b092011-10-20 11:56:00 +01002694 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002695 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002696 Mutex::Autolock _l(mLock);
2697 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002698 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002699 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 }
Eric Laurentde070132010-07-13 04:45:46 -07002701 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2702 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002703 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002704 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002705 }
Eric Laurentde070132010-07-13 04:45:46 -07002706 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2707 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002708 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002709 return BAD_VALUE;
2710 }
2711
2712 Mutex::Autolock _dl(dstThread->mLock);
2713 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002714 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715}
2716
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002717// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07002718status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002719 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002720 AudioFlinger::PlaybackThread *dstThread,
2721 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002722{
Steve Block3856b092011-10-20 11:56:00 +01002723 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002724 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002725
Eric Laurent59255e42011-07-27 19:49:51 -07002726 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002727 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002728 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002729 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002730 return INVALID_OPERATION;
2731 }
2732
Andy Hung9a592762014-07-21 21:56:01 -07002733 // Check whether the destination thread has a channel count of FCC_2, which is
2734 // currently required for (most) effects. Prevent moving the effect chain here rather
2735 // than disabling the addEffect_l() call in dstThread below.
Eric Laurentf6870ae2015-05-08 10:50:03 -07002736 if ((dstThread->type() == ThreadBase::MIXER || dstThread->isDuplicating()) &&
Eric Laurentb10352f2014-11-03 16:25:39 -08002737 dstThread->mChannelCount != FCC_2) {
Andy Hung9a592762014-07-21 21:56:01 -07002738 ALOGW("moveEffectChain_l() effect chain failed because"
2739 " destination thread %p channel count(%u) != %u",
2740 dstThread, dstThread->mChannelCount, FCC_2);
2741 return INVALID_OPERATION;
2742 }
2743
Eric Laurent39e94f82010-07-28 01:32:47 -07002744 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002745 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002746 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002747 // removed.
2748 srcThread->removeEffectChain_l(chain);
2749
2750 // transfer all effects one by one so that new effect chain is created on new thread with
2751 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002752 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002753 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002754 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002755 Vector< sp<EffectModule> > removed;
2756 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002757 while (effect != 0) {
2758 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002759 removed.add(effect);
2760 status = dstThread->addEffect_l(effect);
2761 if (status != NO_ERROR) {
2762 break;
2763 }
Eric Laurentec35a142011-10-05 17:42:25 -07002764 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2765 if (effect->state() == EffectModule::ACTIVE ||
2766 effect->state() == EffectModule::STOPPING) {
2767 effect->start();
2768 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002769 // if the move request is not received from audio policy manager, the effect must be
2770 // re-registered with the new strategy and output
2771 if (dstChain == 0) {
2772 dstChain = effect->chain().promote();
2773 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002774 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002775 status = NO_INIT;
2776 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002777 }
2778 strategy = dstChain->strategy();
2779 }
2780 if (reRegister) {
2781 AudioSystem::unregisterEffect(effect->id());
2782 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002783 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002784 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002785 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002786 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002787 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002788 }
Eric Laurentde070132010-07-13 04:45:46 -07002789 effect = chain->getEffectFromId_l(0);
2790 }
2791
Eric Laurent5baf2af2013-09-12 17:37:00 -07002792 if (status != NO_ERROR) {
2793 for (size_t i = 0; i < removed.size(); i++) {
2794 srcThread->addEffect_l(removed[i]);
2795 if (dstChain != 0 && reRegister) {
2796 AudioSystem::unregisterEffect(removed[i]->id());
2797 AudioSystem::registerEffect(&removed[i]->desc(),
2798 srcThread->id(),
2799 strategy,
2800 sessionId,
2801 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002802 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002803 }
2804 }
2805 }
2806
2807 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808}
2809
Eric Laurent5baf2af2013-09-12 17:37:00 -07002810bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002811{
2812 if (mGlobalEffectEnableTime != 0 &&
2813 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2814 return true;
2815 }
2816
2817 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2818 sp<EffectChain> ec =
2819 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002820 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002821 return true;
2822 }
2823 }
2824 return false;
2825}
2826
Eric Laurent5baf2af2013-09-12 17:37:00 -07002827void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002828{
2829 Mutex::Autolock _l(mLock);
2830
2831 mGlobalEffectEnableTime = systemTime();
2832
2833 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2834 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2835 if (t->mType == ThreadBase::OFFLOAD) {
2836 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2837 }
2838 }
2839
2840}
2841
Eric Laurentaaa44472014-09-12 17:41:50 -07002842status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2843{
2844 audio_session_t session = (audio_session_t)chain->sessionId();
2845 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2846 ALOGV("putOrphanEffectChain_l session %d index %d", session, index);
2847 if (index >= 0) {
2848 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2849 return ALREADY_EXISTS;
2850 }
2851 mOrphanEffectChains.add(session, chain);
2852 return NO_ERROR;
2853}
2854
2855sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2856{
2857 sp<EffectChain> chain;
2858 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2859 ALOGV("getOrphanEffectChain_l session %d index %d", session, index);
2860 if (index >= 0) {
2861 chain = mOrphanEffectChains.valueAt(index);
2862 mOrphanEffectChains.removeItemsAt(index);
2863 }
2864 return chain;
2865}
2866
2867bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2868{
2869 Mutex::Autolock _l(mLock);
2870 audio_session_t session = (audio_session_t)effect->sessionId();
2871 ssize_t index = mOrphanEffectChains.indexOfKey(session);
2872 ALOGV("updateOrphanEffectChains session %d index %d", session, index);
2873 if (index >= 0) {
2874 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
2875 if (chain->removeEffect_l(effect) == 0) {
2876 ALOGV("updateOrphanEffectChains removing effect chain at index %d", index);
2877 mOrphanEffectChains.removeItemsAt(index);
2878 }
2879 return true;
2880 }
2881 return false;
2882}
2883
2884
Glenn Kastenda6ef132013-01-10 12:31:01 -08002885struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002886#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
2887 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002888};
2889
2890int comparEntry(const void *p1, const void *p2)
2891{
Glenn Kasten2f55e762015-03-05 16:05:08 -08002892 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002893}
2894
Glenn Kasten46909e72013-02-26 09:20:22 -08002895#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08002896void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897{
Eric Laurent81784c32012-11-19 14:55:58 -08002898 NBAIO_Source *teeSource = source.get();
2899 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002900 // .wav rotation
2901 // There is a benign race condition if 2 threads call this simultaneously.
2902 // They would both traverse the directory, but the result would simply be
2903 // failures at unlink() which are ignored. It's also unlikely since
2904 // normally dumpsys is only done by bugreport or from the command line.
2905 char teePath[32+256];
2906 strcpy(teePath, "/data/misc/media");
2907 size_t teePathLen = strlen(teePath);
2908 DIR *dir = opendir(teePath);
2909 teePath[teePathLen++] = '/';
2910 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08002911#define TEE_MAX_SORT 20 // number of entries to sort
2912#define TEE_MAX_KEEP 10 // number of entries to keep
2913 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08002914 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08002915 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002916 struct dirent de;
2917 struct dirent *result = NULL;
2918 int rc = readdir_r(dir, &de, &result);
2919 if (rc != 0) {
2920 ALOGW("readdir_r failed %d", rc);
2921 break;
2922 }
2923 if (result == NULL) {
2924 break;
2925 }
2926 if (result != &de) {
2927 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
2928 break;
2929 }
2930 // ignore non .wav file entries
2931 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002932 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08002933 strcmp(&de.d_name[nameLen - 4], ".wav")) {
2934 continue;
2935 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08002936 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002937 }
2938 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002939 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002940 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08002941 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
2942 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002943 (void) unlink(teePath);
2944 }
2945 }
2946 } else {
2947 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07002948 dprintf(fd, "unable to rotate tees in %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08002949 }
2950 }
Eric Laurent81784c32012-11-19 14:55:58 -08002951 char teeTime[16];
2952 struct timeval tv;
2953 gettimeofday(&tv, NULL);
2954 struct tm tm;
2955 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002956 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
2957 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
2958 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
2959 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08002960 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07002961 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08002962 char wavHeader[44];
2963 memcpy(wavHeader,
2964 "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",
2965 sizeof(wavHeader));
2966 NBAIO_Format format = teeSource->format();
2967 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002968 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07002969 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08002970 wavHeader[22] = channelCount; // number of channels
2971 wavHeader[24] = sampleRate; // sample rate
2972 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07002973 wavHeader[32] = frameSize; // block alignment
2974 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08002975 write(teeFd, wavHeader, sizeof(wavHeader));
2976 size_t total = 0;
2977 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07002978#define TEE_SINK_READ 1024 // frames per I/O operation
2979 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002980 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08002981 size_t count = TEE_SINK_READ;
2982 ssize_t actual = teeSource->read(buffer, count,
2983 AudioBufferProvider::kInvalidPTS);
2984 bool wasFirstRead = firstRead;
2985 firstRead = false;
2986 if (actual <= 0) {
2987 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
2988 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07002989 }
Eric Laurent81784c32012-11-19 14:55:58 -08002990 break;
Eric Laurent59255e42011-07-27 19:49:51 -07002991 }
Eric Laurent81784c32012-11-19 14:55:58 -08002992 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07002993 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002994 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07002995 }
Glenn Kasten329f6512014-08-28 16:23:16 -07002996 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002997 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07002998 uint32_t temp = 44 + total * frameSize - 8;
2999 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003000 write(teeFd, &temp, sizeof(temp));
3001 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003002 temp = total * frameSize;
3003 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003004 write(teeFd, &temp, sizeof(temp));
3005 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003006 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003007 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003008 }
Eric Laurent59255e42011-07-27 19:49:51 -07003009 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003010 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003011 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003012 }
Eric Laurent59255e42011-07-27 19:49:51 -07003013 }
3014 }
3015}
Glenn Kasten46909e72013-02-26 09:20:22 -08003016#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003017
Mathias Agopian65ab4712010-07-14 17:59:35 -07003018// ----------------------------------------------------------------------------
3019
3020status_t AudioFlinger::onTransact(
3021 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3022{
3023 return BnAudioFlinger::onTransact(code, data, reply, flags);
3024}
3025
Glenn Kasten63238ef2015-03-02 15:50:29 -08003026} // namespace android