blob: e4b73c6ff12fb5d274cb3e6eb4b6ef0cf0b677fb [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
Glenn Kasten153b9fe2013-07-15 11:23:36 -070022#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080023#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070034#include <media/audiohal/DeviceHalInterface.h>
35#include <media/audiohal/DevicesFactoryHalInterface.h>
36#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070037#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070038#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070039#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <utils/String16.h>
41#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070042#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
Dima Zavinfce7a472011-04-19 22:30:36 -070044#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <cutils/properties.h>
46
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Andy Hung6770c6f2015-04-07 13:43:36 -070053#include <media/AudioResamplerPublic.h>
54
Mikhail Naganov9fe94012016-10-14 14:57:40 -070055#include <system/audio_effects/effect_visualizer.h>
56#include <system/audio_effects/effect_ns.h>
57#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080062
Glenn Kasten9e58b552013-01-18 15:09:48 -080063#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070064#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065#include <media/nbaio/Pipe.h>
66#include <media/nbaio/PipeReader.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070067#include <media/AudioParameter.h>
Wei Jia3f273d12015-11-24 09:06:49 -080068#include <mediautils/BatteryNotifier.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070069#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070
rago3bd1c872016-09-26 12:58:14 -070071//#define BUFLOG_NDEBUG 0
72#include <BufLog.h>
73
Mathias Agopian65ab4712010-07-14 17:59:35 -070074// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
John Grossman1c345192012-03-27 14:00:17 -070076// Note: the following macro is used for extremely verbose logging message. In
77// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
78// 0; but one side effect of this is to turn all LOGV's as well. Some messages
79// are so verbose that we want to suppress them even when we have ALOG_ASSERT
80// turned on. Do not uncomment the #def below unless you really know what you
81// are doing and want to see all of the extremely verbose messages.
82//#define VERY_VERY_VERBOSE_LOGGING
83#ifdef VERY_VERY_VERBOSE_LOGGING
84#define ALOGVV ALOGV
85#else
86#define ALOGVV(a...) do { } while(0)
87#endif
Eric Laurentde070132010-07-13 04:45:46 -070088
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Glenn Kastenec1d6b52011-12-12 09:04:45 -080091static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
92static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070093static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070094static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
Glenn Kasten58912562012-04-03 10:45:00 -070096
John Grossman4ff14ba2012-02-08 16:37:41 -080097nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -080098
Eric Laurent81784c32012-11-19 14:55:58 -080099uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700100
Glenn Kasten46909e72013-02-26 09:20:22 -0800101#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -0800102bool AudioFlinger::mTeeSinkInputEnabled = false;
103bool AudioFlinger::mTeeSinkOutputEnabled = false;
104bool AudioFlinger::mTeeSinkTrackEnabled = false;
105
106size_t AudioFlinger::mTeeSinkInputFrames = kTeeSinkInputFramesDefault;
107size_t AudioFlinger::mTeeSinkOutputFrames = kTeeSinkOutputFramesDefault;
108size_t AudioFlinger::mTeeSinkTrackFrames = kTeeSinkTrackFramesDefault;
Glenn Kasten46909e72013-02-26 09:20:22 -0800109#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -0800110
Eric Laurent813e2a72013-08-31 12:59:48 -0700111// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
112// we define a minimum time during which a global effect is considered enabled.
113static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
114
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115// ----------------------------------------------------------------------------
116
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700117std::string formatToString(audio_format_t format) {
118 std::string result;
119 FormatConverter::toString(format, result);
120 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800121}
122
Mathias Agopian65ab4712010-07-14 17:59:35 -0700123// ----------------------------------------------------------------------------
124
125AudioFlinger::AudioFlinger()
126 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800127 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800128 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700129 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800130 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800131 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700132 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800133 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700134 mBtNrecIsOff(false),
135 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700136 mIsDeviceTypeKnown(false),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700137 mGlobalEffectEnableTime(0),
Eric Laurent72e3f392015-05-20 14:43:50 -0700138 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700139{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700140 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
141 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
142 // zero ID has a special meaning, so unavailable
143 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
144 }
145
Glenn Kasten949a9262013-04-16 12:35:20 -0700146 getpid_cached = getpid();
Glenn Kastenae0cff12016-02-24 13:57:49 -0800147 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800148 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800149 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
150 MemoryHeapBase::READ_ONLY);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800151 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700152
Wei Jia3f273d12015-11-24 09:06:49 -0800153 // reset battery stats.
154 // if the audio service has crashed, battery stats could be left
155 // in bad state, reset the state upon service start.
156 BatteryNotifier::getInstance().noteResetAudio();
157
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700158 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700159 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
160
Glenn Kasten46909e72013-02-26 09:20:22 -0800161#ifdef TEE_SINK
Glenn Kasten9a003992016-02-23 15:24:34 -0800162 char value[PROPERTY_VALUE_MAX];
Glenn Kastenda6ef132013-01-10 12:31:01 -0800163 (void) property_get("ro.debuggable", value, "0");
164 int debuggable = atoi(value);
165 int teeEnabled = 0;
166 if (debuggable) {
167 (void) property_get("af.tee", value, "0");
168 teeEnabled = atoi(value);
169 }
Glenn Kastenf66b4222014-02-20 10:23:28 -0800170 // FIXME symbolic constants here
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700171 if (teeEnabled & 1) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800172 mTeeSinkInputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700173 }
174 if (teeEnabled & 2) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800175 mTeeSinkOutputEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700176 }
177 if (teeEnabled & 4) {
Glenn Kastenda6ef132013-01-10 12:31:01 -0800178 mTeeSinkTrackEnabled = true;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700179 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800180#endif
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700181}
182
183void AudioFlinger::onFirstRef()
184{
Eric Laurent93575202011-01-18 18:39:02 -0800185 Mutex::Autolock _l(mLock);
186
Dima Zavin799a70e2011-04-18 16:57:27 -0700187 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800188 char val_str[PROPERTY_VALUE_MAX] = { 0 };
189 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
190 uint32_t int_val;
191 if (1 == sscanf(val_str, "%u", &int_val)) {
192 mStandbyTimeInNsecs = milliseconds(int_val);
193 ALOGI("Using %u mSec as standby time.", int_val);
194 } else {
195 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
196 ALOGI("Using default %u mSec as standby time.",
197 (uint32_t)(mStandbyTimeInNsecs / 1000000));
198 }
199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700200
Eric Laurent1c333e22014-05-20 10:48:17 -0700201 mPatchPanel = new PatchPanel(this);
Andy Hungdeb03352016-08-29 14:40:14 -0700202
Eric Laurenta4c5a552012-03-29 10:12:40 -0700203 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700204}
205
206AudioFlinger::~AudioFlinger()
207{
208 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700209 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700210 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211 }
212 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700213 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700214 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700216
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800217 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
218 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700219 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700221
222 // Tell media.log service about any old writers that still need to be unregistered
Andy Hungce717682015-12-22 13:40:32 -0800223 if (mLogMemoryDealer != 0) {
224 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
225 if (binder != 0) {
226 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
227 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
228 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
229 mUnregisteredWriters.pop();
230 mediaLogService->unregisterWriter(iMemory);
231 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700232 }
233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234}
235
Eric Laurenta4c5a552012-03-29 10:12:40 -0700236static const char * const audio_interfaces[] = {
237 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
238 AUDIO_HARDWARE_MODULE_ID_A2DP,
239 AUDIO_HARDWARE_MODULE_ID_USB,
240};
241#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
242
Phil Burk062e67a2015-02-11 13:40:50 -0800243AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700244 audio_module_handle_t module,
245 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700246{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700247 // if module is 0, the request comes from an old policy manager and we should load
248 // well known modules
249 if (module == 0) {
250 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
251 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
252 loadHwModule_l(audio_interfaces[i]);
253 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700254 // then try to find a module supporting the requested device.
255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
256 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700257 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
258 uint32_t supportedDevices;
259 if (dev->getSupportedDevices(&supportedDevices) == OK &&
260 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700261 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700262 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700263 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700264 } else {
265 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700266 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
267 if (audioHwDevice != NULL) {
268 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269 }
270 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271
Dima Zavin799a70e2011-04-18 16:57:27 -0700272 return NULL;
273}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274
Glenn Kasten0f11b512014-01-31 16:18:54 -0800275void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276{
277 const size_t SIZE = 256;
278 char buffer[SIZE];
279 String8 result;
280
281 result.append("Clients:\n");
282 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800283 sp<Client> client = mClients.valueAt(i).promote();
284 if (client != 0) {
285 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
286 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 }
288 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700289
Eric Laurentd1b28d42013-09-18 18:47:13 -0700290 result.append("Notification Clients:\n");
291 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
292 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
293 result.append(buffer);
294 }
295
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700296 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800297 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700298 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
299 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800300 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700301 result.append(buffer);
302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304}
305
306
Glenn Kasten0f11b512014-01-31 16:18:54 -0800307void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700308{
309 const size_t SIZE = 256;
310 char buffer[SIZE];
311 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800312 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313
John Grossman4ff14ba2012-02-08 16:37:41 -0800314 snprintf(buffer, SIZE, "Hardware status: %d\n"
315 "Standby Time mSec: %u\n",
316 hardwareStatus,
317 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700318 result.append(buffer);
319 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320}
321
Glenn Kasten0f11b512014-01-31 16:18:54 -0800322void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700323{
324 const size_t SIZE = 256;
325 char buffer[SIZE];
326 String8 result;
327 snprintf(buffer, SIZE, "Permission Denial: "
328 "can't dump AudioFlinger from pid=%d, uid=%d\n",
329 IPCThreadState::self()->getCallingPid(),
330 IPCThreadState::self()->getCallingUid());
331 result.append(buffer);
332 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333}
334
Eric Laurent81784c32012-11-19 14:55:58 -0800335bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336{
337 bool locked = false;
338 for (int i = 0; i < kDumpLockRetries; ++i) {
339 if (mutex.tryLock() == NO_ERROR) {
340 locked = true;
341 break;
342 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800343 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344 }
345 return locked;
346}
347
348status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
349{
Glenn Kasten44deb052012-02-05 18:09:08 -0800350 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351 dumpPermissionDenial(fd, args);
352 } else {
353 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800354 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355 if (!hardwareLocked) {
356 String8 result(kHardwareLockedString);
357 write(fd, result.string(), result.size());
358 } else {
359 mHardwareLock.unlock();
360 }
361
Eric Laurent81784c32012-11-19 14:55:58 -0800362 bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363
364 // failed to lock - AudioFlinger is probably deadlocked
365 if (!locked) {
366 String8 result(kDeadlockedString);
367 write(fd, result.string(), result.size());
368 }
369
Eric Laurent021cf962014-05-13 10:18:14 -0700370 bool clientLocked = dumpTryLock(mClientLock);
371 if (!clientLocked) {
372 String8 result(kClientLockedString);
373 write(fd, result.string(), result.size());
374 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700375
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700376 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700377 mEffectsFactoryHal->dumpEffects(fd);
378 } else {
379 String8 result(kNoEffectsFactory);
380 write(fd, result.string(), result.size());
381 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700382
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700384 if (clientLocked) {
385 mClientLock.unlock();
386 }
387
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 dumpInternals(fd, args);
389
390 // dump playback threads
391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
392 mPlaybackThreads.valueAt(i)->dump(fd, args);
393 }
394
395 // dump record threads
396 for (size_t i = 0; i < mRecordThreads.size(); i++) {
397 mRecordThreads.valueAt(i)->dump(fd, args);
398 }
399
Eric Laurentaaa44472014-09-12 17:41:50 -0700400 // dump orphan effect chains
401 if (mOrphanEffectChains.size() != 0) {
402 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
403 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
404 mOrphanEffectChains.valueAt(i)->dump(fd, args);
405 }
406 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 // dump all hardware devs
408 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700409 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
410 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700412
Glenn Kasten46909e72013-02-26 09:20:22 -0800413#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -0700414 // dump the serially shared record tee sink
415 if (mRecordTeeSource != 0) {
416 dumpTee(fd, mRecordTeeSource);
417 }
Glenn Kasten46909e72013-02-26 09:20:22 -0800418#endif
Glenn Kastend06785b2012-09-30 12:29:28 -0700419
rago3bd1c872016-09-26 12:58:14 -0700420 BUFLOG_RESET;
421
Glenn Kastend65d73c2012-06-22 17:21:07 -0700422 if (locked) {
423 mLock.unlock();
424 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800425
426 // append a copy of media.log here by forwarding fd to it, but don't attempt
427 // to lookup the service if it's not running, as it will block for a second
428 if (mLogMemoryDealer != 0) {
429 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
430 if (binder != 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700431 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten9e58b552013-01-18 15:09:48 -0800432 Vector<String16> args;
433 binder->dump(fd, args);
434 }
435 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700436
437 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700438 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700439 bool unreachableMemory = false;
440 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700441 if (arg == String16("-m")) {
442 dumpMem = true;
443 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700444 unreachableMemory = true;
445 }
446 }
447
Andy Hung07b745e2016-05-23 16:21:07 -0700448 if (dumpMem) {
449 dprintf(fd, "\nDumping memory:\n");
450 std::string s = dumpMemoryAddresses(100 /* limit */);
451 write(fd, s.c_str(), s.size());
452 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700453 if (unreachableMemory) {
454 dprintf(fd, "\nDumping unreachable memory:\n");
455 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700456 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700457 write(fd, s.c_str(), s.size());
458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 }
460 return NO_ERROR;
461}
462
Eric Laurent021cf962014-05-13 10:18:14 -0700463sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800464{
Eric Laurent021cf962014-05-13 10:18:14 -0700465 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800466 // If pid is already in the mClients wp<> map, then use that entry
467 // (for which promote() is always != 0), otherwise create a new entry and Client.
468 sp<Client> client = mClients.valueFor(pid).promote();
469 if (client == 0) {
470 client = new Client(this, pid);
471 mClients.add(pid, client);
472 }
473
474 return client;
475}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476
Glenn Kasten9e58b552013-01-18 15:09:48 -0800477sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
478{
Glenn Kasten481fb672013-09-30 14:39:28 -0700479 // If there is no memory allocated for logs, return a dummy writer that does nothing
Glenn Kasten9e58b552013-01-18 15:09:48 -0800480 if (mLogMemoryDealer == 0) {
481 return new NBLog::Writer();
482 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800483 sp<IBinder> binder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten481fb672013-09-30 14:39:28 -0700484 // Similarly if we can't contact the media.log service, also return a dummy writer
485 if (binder == 0) {
486 return new NBLog::Writer();
Glenn Kasten9e58b552013-01-18 15:09:48 -0800487 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700488 sp<IMediaLogService> mediaLogService(interface_cast<IMediaLogService>(binder));
489 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
490 // If allocation fails, consult the vector of previously unregistered writers
491 // and garbage-collect one or more them until an allocation succeeds
492 if (shared == 0) {
493 Mutex::Autolock _l(mUnregisteredWritersLock);
494 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
495 {
496 // Pick the oldest stale writer to garbage-collect
497 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
498 mUnregisteredWriters.removeAt(0);
499 mediaLogService->unregisterWriter(iMemory);
500 // Now the media.log remote reference to IMemory is gone. When our last local
501 // reference to IMemory also drops to zero at end of this block,
502 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
503 }
504 // Re-attempt the allocation
505 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
506 if (shared != 0) {
507 goto success;
508 }
509 }
510 // Even after garbage-collecting all old writers, there is still not enough memory,
511 // so return a dummy writer
512 return new NBLog::Writer();
513 }
514success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800515 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
516 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
517 // explicit destructor not needed since it is POD
Glenn Kasten481fb672013-09-30 14:39:28 -0700518 mediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800519 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800520}
521
522void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
523{
Glenn Kasten685ef092013-02-04 08:15:34 -0800524 if (writer == 0) {
525 return;
526 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800527 sp<IMemory> iMemory(writer->getIMemory());
528 if (iMemory == 0) {
529 return;
530 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700531 // Rather than removing the writer immediately, append it to a queue of old writers to
532 // be garbage-collected later. This allows us to continue to view old logs for a while.
533 Mutex::Autolock _l(mUnregisteredWritersLock);
534 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800535}
536
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537// IAudioFlinger interface
538
539
540sp<IAudioTrack> AudioFlinger::createTrack(
Glenn Kastenfff6d712012-01-12 16:38:12 -0800541 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800543 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700544 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -0800545 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -0700546 audio_output_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800548 audio_io_handle_t output,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700549 pid_t pid,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800550 pid_t tid,
Glenn Kastend848eb42016-03-08 13:42:11 -0800551 audio_session_t *sessionId,
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800552 int clientUid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800553 status_t *status,
554 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555{
556 sp<PlaybackThread::Track> track;
557 sp<TrackHandle> trackHandle;
558 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -0800560 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700562 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
563 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
564 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
565 ALOGW_IF(pid != -1 && pid != callingPid,
566 "%s uid %d pid %d tried to pass itself off as pid %d",
567 __func__, callingUid, callingPid, pid);
568 pid = callingPid;
569 }
570
Glenn Kasten263709e2012-01-06 08:40:01 -0800571 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
572 // but if someone uses binder directly they could bypass that and cause us to crash
573 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000574 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 lStatus = BAD_VALUE;
576 goto Exit;
577 }
578
Glenn Kasten53b5d092014-02-05 10:00:23 -0800579 // further sample rate checks are performed by createTrack_l() depending on the thread type
580 if (sampleRate == 0) {
581 ALOGE("createTrack() invalid sample rate %u", sampleRate);
582 lStatus = BAD_VALUE;
583 goto Exit;
584 }
585
586 // further channel mask checks are performed by createTrack_l() depending on the thread type
587 if (!audio_is_output_channel(channelMask)) {
588 ALOGE("createTrack() invalid channel mask %#x", channelMask);
589 lStatus = BAD_VALUE;
590 goto Exit;
591 }
592
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700593 // further format checks are performed by createTrack_l() depending on the thread type
594 if (!audio_is_valid_format(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -0800595 ALOGE("createTrack() invalid format %#x", format);
Glenn Kasten60a83922012-06-21 12:56:37 -0700596 lStatus = BAD_VALUE;
597 goto Exit;
598 }
599
Glenn Kasten663c2242013-09-24 11:52:37 -0700600 if (sharedBuffer != 0 && sharedBuffer->pointer() == NULL) {
601 ALOGE("createTrack() sharedBuffer is non-0 but has NULL pointer()");
602 lStatus = BAD_VALUE;
603 goto Exit;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 {
607 Mutex::Autolock _l(mLock);
608 PlaybackThread *thread = checkPlaybackThread_l(output);
609 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800610 ALOGE("no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 lStatus = BAD_VALUE;
612 goto Exit;
613 }
614
Eric Laurent021cf962014-05-13 10:18:14 -0700615 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616
Glenn Kastene848bd92014-03-13 15:00:32 -0700617 PlaybackThread *effectThread = NULL;
Glenn Kastenaea7ea02013-06-26 09:25:47 -0700618 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -0800619 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
620 ALOGE("createTrack() invalid session ID %d", *sessionId);
621 lStatus = BAD_VALUE;
622 goto Exit;
623 }
Glenn Kasten570f6332014-03-13 15:01:06 -0700624 lSessionId = *sessionId;
Eric Laurentf436fdc2012-05-24 11:07:14 -0700625 // check if an effect chain with the same session ID is present on another
626 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700627 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700628 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
629 if (mPlaybackThreads.keyAt(i) != output) {
Glenn Kasten570f6332014-03-13 15:01:06 -0700630 uint32_t sessions = t->hasAudioSession(lSessionId);
Eric Laurent4c415062016-06-17 16:14:16 -0700631 if (sessions & ThreadBase::EFFECT_SESSION) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700632 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700633 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700634 }
Eric Laurentde070132010-07-13 04:45:46 -0700635 }
636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700638 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -0800639 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 if (sessionId != NULL) {
641 *sessionId = lSessionId;
642 }
643 }
Steve Block3856b092011-10-20 11:56:00 +0100644 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645
646 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800647 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid,
648 clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800649 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700650 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700651
652 // move effect chain to this output thread if an effect on same session was waiting
653 // for a track to be created
654 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700655 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700656 Mutex::Autolock _dl(thread->mLock);
657 Mutex::Autolock _sl(effectThread->mLock);
658 moveEffectChain_l(lSessionId, effectThread, thread, true);
659 }
Eric Laurenta011e352012-03-29 15:51:43 -0700660
661 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700662 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurenta011e352012-03-29 15:51:43 -0700663 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
664 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700665 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700666 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700667 } else {
668 mPendingSyncEvents[i]->cancel();
669 }
Eric Laurenta011e352012-03-29 15:51:43 -0700670 mPendingSyncEvents.removeAt(i);
671 i--;
672 }
673 }
674 }
Glenn Kastene198c362013-08-13 09:13:36 -0700675
Glenn Kastend848eb42016-03-08 13:42:11 -0800676 setAudioHwSyncForSession_l(thread, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677 }
Glenn Kastene198c362013-08-13 09:13:36 -0700678
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700679 if (lStatus != NO_ERROR) {
680 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700681 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700682 // Don't hold mClientLock when releasing the reference on the track as the
683 // destructor will acquire it.
684 {
685 Mutex::Autolock _cl(mClientLock);
686 client.clear();
687 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700689 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 }
691
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700692 // return handle to client
693 trackHandle = new TrackHandle(track);
694
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -0700696 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 return trackHandle;
698}
699
Glenn Kasten2c073da2016-02-26 09:14:08 -0800700uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701{
702 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800703 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800705 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 return 0;
707 }
708 return thread->sampleRate();
709}
710
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800711audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712{
713 Mutex::Autolock _l(mLock);
714 PlaybackThread *thread = checkPlaybackThread_l(output);
715 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000716 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800717 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 }
719 return thread->format();
720}
721
Glenn Kasten2c073da2016-02-26 09:14:08 -0800722size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723{
724 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800725 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700726 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800727 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700728 return 0;
729 }
Glenn Kasten58912562012-04-03 10:45:00 -0700730 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
731 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 return thread->frameCount();
733}
734
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700735size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
736{
737 Mutex::Autolock _l(mLock);
738 ThreadBase *thread = checkThread_l(ioHandle);
739 if (thread == NULL) {
740 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
741 return 0;
742 }
743 return thread->frameCountHAL();
744}
745
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800746uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747{
748 Mutex::Autolock _l(mLock);
749 PlaybackThread *thread = checkPlaybackThread_l(output);
750 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800751 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 return 0;
753 }
754 return thread->latency();
755}
756
757status_t AudioFlinger::setMasterVolume(float value)
758{
Eric Laurenta1884f92011-08-23 08:25:03 -0700759 status_t ret = initCheck();
760 if (ret != NO_ERROR) {
761 return ret;
762 }
763
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 // check calling permissions
765 if (!settingsAllowed()) {
766 return PERMISSION_DENIED;
767 }
768
Eric Laurenta4c5a552012-03-29 10:12:40 -0700769 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700770 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700771
John Grossmanee578c02012-07-23 17:05:46 -0700772 // Set master volume in the HALs which support it.
773 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
774 AutoMutex lock(mHardwareLock);
775 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800776
John Grossmanee578c02012-07-23 17:05:46 -0700777 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
778 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700779 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800780 }
John Grossmanee578c02012-07-23 17:05:46 -0700781 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783
John Grossmanee578c02012-07-23 17:05:46 -0700784 // Now set the master volume in each playback thread. Playback threads
785 // assigned to HALs which do not have master volume support will apply
786 // master volume during the mix operation. Threads with HALs which do
787 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700788 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
789 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
790 continue;
791 }
John Grossmanee578c02012-07-23 17:05:46 -0700792 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794
795 return NO_ERROR;
796}
797
Glenn Kastenf78aee72012-01-04 11:00:47 -0800798status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799{
Eric Laurenta1884f92011-08-23 08:25:03 -0700800 status_t ret = initCheck();
801 if (ret != NO_ERROR) {
802 return ret;
803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804
805 // check calling permissions
806 if (!settingsAllowed()) {
807 return PERMISSION_DENIED;
808 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800809 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000810 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 return BAD_VALUE;
812 }
813
814 { // scope for the lock
815 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700816 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700818 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 mHardwareStatus = AUDIO_HW_IDLE;
820 }
821
822 if (NO_ERROR == ret) {
823 Mutex::Autolock _l(mLock);
824 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800825 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700826 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827 }
828
829 return ret;
830}
831
832status_t AudioFlinger::setMicMute(bool state)
833{
Eric Laurenta1884f92011-08-23 08:25:03 -0700834 status_t ret = initCheck();
835 if (ret != NO_ERROR) {
836 return ret;
837 }
838
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 // check calling permissions
840 if (!settingsAllowed()) {
841 return PERMISSION_DENIED;
842 }
843
844 AutoMutex lock(mHardwareLock);
845 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -0700846 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700847 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
848 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -0700849 if (result != NO_ERROR) {
850 ret = result;
851 }
852 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 mHardwareStatus = AUDIO_HW_IDLE;
854 return ret;
855}
856
857bool AudioFlinger::getMicMute() const
858{
Eric Laurenta1884f92011-08-23 08:25:03 -0700859 status_t ret = initCheck();
860 if (ret != NO_ERROR) {
861 return false;
862 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800863 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -0700864 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800865 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800867 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700868 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
869 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800870 if (result == NO_ERROR) {
871 mute = mute && state;
872 }
873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -0800875
876 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700877}
878
879status_t AudioFlinger::setMasterMute(bool muted)
880{
John Grossmand8f178d2012-07-20 14:51:35 -0700881 status_t ret = initCheck();
882 if (ret != NO_ERROR) {
883 return ret;
884 }
885
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886 // check calling permissions
887 if (!settingsAllowed()) {
888 return PERMISSION_DENIED;
889 }
890
John Grossmanee578c02012-07-23 17:05:46 -0700891 Mutex::Autolock _l(mLock);
892 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700893
John Grossmanee578c02012-07-23 17:05:46 -0700894 // Set master mute in the HALs which support it.
895 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
896 AutoMutex lock(mHardwareLock);
897 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700898
John Grossmanee578c02012-07-23 17:05:46 -0700899 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
900 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700901 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700902 }
John Grossmanee578c02012-07-23 17:05:46 -0700903 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700904 }
905
John Grossmanee578c02012-07-23 17:05:46 -0700906 // Now set the master mute in each playback thread. Playback threads
907 // assigned to HALs which do not have master mute support will apply master
908 // mute during the mix operation. Threads with HALs which do support master
909 // mute will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700910 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
911 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
912 continue;
913 }
John Grossmanee578c02012-07-23 17:05:46 -0700914 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916
917 return NO_ERROR;
918}
919
920float AudioFlinger::masterVolume() const
921{
Glenn Kasten98067102011-12-13 11:47:54 -0800922 Mutex::Autolock _l(mLock);
923 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924}
925
926bool AudioFlinger::masterMute() const
927{
Glenn Kasten98067102011-12-13 11:47:54 -0800928 Mutex::Autolock _l(mLock);
929 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930}
931
John Grossman4ff14ba2012-02-08 16:37:41 -0800932float AudioFlinger::masterVolume_l() const
933{
John Grossman4ff14ba2012-02-08 16:37:41 -0800934 return mMasterVolume;
935}
936
John Grossmand8f178d2012-07-20 14:51:35 -0700937bool AudioFlinger::masterMute_l() const
938{
John Grossmanee578c02012-07-23 17:05:46 -0700939 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700940}
941
Eric Laurent223fd5c2014-11-11 13:43:36 -0800942status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
943{
944 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
945 ALOGW("setStreamVolume() invalid stream %d", stream);
946 return BAD_VALUE;
947 }
948 pid_t caller = IPCThreadState::self()->getCallingPid();
949 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && caller != getpid_cached) {
950 ALOGW("setStreamVolume() pid %d cannot use internal stream type %d", caller, stream);
951 return PERMISSION_DENIED;
952 }
953
954 return NO_ERROR;
955}
956
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800957status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
958 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959{
960 // check calling permissions
961 if (!settingsAllowed()) {
962 return PERMISSION_DENIED;
963 }
964
Eric Laurent223fd5c2014-11-11 13:43:36 -0800965 status_t status = checkStreamType(stream);
966 if (status != NO_ERROR) {
967 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700968 }
Eric Laurent223fd5c2014-11-11 13:43:36 -0800969 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970
971 AutoMutex lock(mLock);
972 PlaybackThread *thread = NULL;
Glenn Kasten142f5192014-03-25 17:44:59 -0700973 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 thread = checkPlaybackThread_l(output);
975 if (thread == NULL) {
976 return BAD_VALUE;
977 }
978 }
979
980 mStreamTypes[stream].volume = value;
981
982 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800983 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700984 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985 }
986 } else {
987 thread->setStreamVolume(stream, value);
988 }
989
990 return NO_ERROR;
991}
992
Glenn Kastenfff6d712012-01-12 16:38:12 -0800993status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994{
995 // check calling permissions
996 if (!settingsAllowed()) {
997 return PERMISSION_DENIED;
998 }
999
Eric Laurent223fd5c2014-11-11 13:43:36 -08001000 status_t status = checkStreamType(stream);
1001 if (status != NO_ERROR) {
1002 return status;
1003 }
1004 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1005
1006 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001007 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 return BAD_VALUE;
1009 }
1010
Eric Laurent93575202011-01-18 18:39:02 -08001011 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012 mStreamTypes[stream].mute = muted;
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001013 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001014 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015
1016 return NO_ERROR;
1017}
1018
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001019float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001021 status_t status = checkStreamType(stream);
1022 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 return 0.0f;
1024 }
1025
1026 AutoMutex lock(mLock);
1027 float volume;
Glenn Kasten142f5192014-03-25 17:44:59 -07001028 if (output != AUDIO_IO_HANDLE_NONE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029 PlaybackThread *thread = checkPlaybackThread_l(output);
1030 if (thread == NULL) {
1031 return 0.0f;
1032 }
1033 volume = thread->streamVolume(stream);
1034 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001035 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036 }
1037
1038 return volume;
1039}
1040
Glenn Kastenfff6d712012-01-12 16:38:12 -08001041bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001043 status_t status = checkStreamType(stream);
1044 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 return true;
1046 }
1047
Glenn Kasten6637baa2012-01-09 09:40:36 -08001048 AutoMutex lock(mLock);
1049 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050}
1051
Eric Laurent054d9d32015-04-24 08:48:48 -07001052
1053void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1054{
1055 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1056 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1057 }
1058}
1059
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001060status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001062 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d",
1063 ioHandle, keyValuePairs.string(), IPCThreadState::self()->getCallingPid());
Eric Laurent81784c32012-11-19 14:55:58 -08001064
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065 // check calling permissions
1066 if (!settingsAllowed()) {
1067 return PERMISSION_DENIED;
1068 }
1069
Glenn Kasten142f5192014-03-25 17:44:59 -07001070 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1071 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001072 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001073 // result will remain NO_INIT if no audio device is present
1074 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001075 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001076 AutoMutex lock(mHardwareLock);
1077 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1078 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001079 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1080 status_t result = dev->setParameters(keyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001081 // return success if at least one audio device accepts the parameters as not all
1082 // HALs are requested to support all parameters. If no audio device supports the
1083 // requested parameters, the last error is reported.
1084 if (final_result != NO_ERROR) {
1085 final_result = result;
1086 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001087 }
1088 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001089 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001090 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1091 AudioParameter param = AudioParameter(keyValuePairs);
1092 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001093 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1094 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentbee53372011-08-29 12:42:48 -07001095 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001096 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1097 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -07001098 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001099 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
1100 // collect all of the thread's session IDs
Glenn Kastend848eb42016-03-08 13:42:11 -08001101 KeyedVector<audio_session_t, bool> ids = thread->sessionIds();
Glenn Kasten510a3d62012-07-16 14:24:34 -07001102 // suspend effects associated with those session IDs
1103 for (size_t j = 0; j < ids.size(); ++j) {
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001105 thread->setEffectSuspended(FX_IID_AEC,
1106 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001107 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001108 thread->setEffectSuspended(FX_IID_NS,
1109 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -07001110 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001111 }
1112 }
Eric Laurentbee53372011-08-29 12:42:48 -07001113 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -07001114 }
1115 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001116 String8 screenState;
1117 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001118 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001119 if (isOff != (AudioFlinger::mScreenState & 1)) {
1120 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001121 }
1122 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001123 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 }
1125
1126 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1127 // and the thread is exited once the lock is released
1128 sp<ThreadBase> thread;
1129 {
1130 Mutex::Autolock _l(mLock);
1131 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001132 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001134 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001135 // indicate output device change to all input threads for pre processing
1136 AudioParameter param = AudioParameter(keyValuePairs);
1137 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001138 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1139 (value != 0)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07001140 broacastParametersToRecordThreads_l(keyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 }
1143 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001144 if (thread != 0) {
1145 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 }
1147 return BAD_VALUE;
1148}
1149
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001150String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001152 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1153 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154
Eric Laurenta4c5a552012-03-29 10:12:40 -07001155 Mutex::Autolock _l(mLock);
1156
Glenn Kasten142f5192014-03-25 17:44:59 -07001157 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001158 String8 out_s8;
1159
Dima Zavin799a70e2011-04-18 16:57:27 -07001160 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001161 String8 s;
1162 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001163 {
1164 AutoMutex lock(mHardwareLock);
1165 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001166 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1167 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001168 mHardwareStatus = AUDIO_HW_IDLE;
1169 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001170 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001171 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001172 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 }
1174
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1176 if (playbackThread != NULL) {
1177 return playbackThread->getParameters(keys);
1178 }
1179 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1180 if (recordThread != NULL) {
1181 return recordThread->getParameters(keys);
1182 }
1183 return String8("");
1184}
1185
Glenn Kastendd8104c2012-07-02 12:42:44 -07001186size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1187 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188{
Eric Laurenta1884f92011-08-23 08:25:03 -07001189 status_t ret = initCheck();
1190 if (ret != NO_ERROR) {
1191 return 0;
1192 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001193 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001194 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001195 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001196 return 0;
1197 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001198
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001199 AutoMutex lock(mHardwareLock);
1200 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001201 audio_config_t config, proposed;
1202 memset(&proposed, 0, sizeof(proposed));
1203 proposed.sample_rate = sampleRate;
1204 proposed.channel_mask = channelMask;
1205 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001206
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001207 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001208 size_t frames;
1209 for (;;) {
1210 // Note: config is currently a const parameter for get_input_buffer_size()
1211 // but we use a copy from proposed in case config changes from the call.
1212 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001213 status_t result = dev->getInputBufferSize(&config, &frames);
1214 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001215 break; // hal success, config is the result
1216 }
1217 // change one parameter of the configuration each iteration to a more "common" value
1218 // to see if the device will support it.
1219 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1220 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1221 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1222 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1223 } else {
1224 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1225 "format %#x, channelMask 0x%X",
1226 sampleRate, format, channelMask);
1227 break; // retries failed, break out of loop with frames == 0.
1228 }
1229 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001230 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001231 if (frames > 0 && config.sample_rate != sampleRate) {
1232 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1233 }
1234 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235}
1236
Glenn Kasten5f972c02014-01-13 09:59:31 -08001237uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 Mutex::Autolock _l(mLock);
1240
1241 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1242 if (recordThread != NULL) {
1243 return recordThread->getInputFramesLost();
1244 }
1245 return 0;
1246}
1247
1248status_t AudioFlinger::setVoiceVolume(float value)
1249{
Eric Laurenta1884f92011-08-23 08:25:03 -07001250 status_t ret = initCheck();
1251 if (ret != NO_ERROR) {
1252 return ret;
1253 }
1254
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 // check calling permissions
1256 if (!settingsAllowed()) {
1257 return PERMISSION_DENIED;
1258 }
1259
1260 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001261 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001262 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001263 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 mHardwareStatus = AUDIO_HW_IDLE;
1265
1266 return ret;
1267}
1268
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001269status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001270 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 Mutex::Autolock _l(mLock);
1273
1274 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1275 if (playbackThread != NULL) {
1276 return playbackThread->getRenderPosition(halFrames, dspFrames);
1277 }
1278
1279 return BAD_VALUE;
1280}
1281
1282void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1283{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001284 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001285 if (client == 0) {
1286 return;
1287 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001288 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001289 {
1290 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001291 if (mNotificationClients.indexOfKey(pid) < 0) {
1292 sp<NotificationClient> notificationClient = new NotificationClient(this,
1293 client,
1294 pid);
1295 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296
Eric Laurent021cf962014-05-13 10:18:14 -07001297 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298
Marco Nelissen06b46062014-11-14 07:58:25 -08001299 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001300 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001301 }
1302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303
Eric Laurent021cf962014-05-13 10:18:14 -07001304 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001305 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001306 // the config change is always sent from playback or record threads to avoid deadlock
1307 // with AudioSystem::gLock
1308 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1309 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_OPENED, pid);
1310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001312 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1313 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_OPENED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314 }
1315}
1316
1317void AudioFlinger::removeNotificationClient(pid_t pid)
1318{
1319 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001320 {
1321 Mutex::Autolock _cl(mClientLock);
1322 mNotificationClients.removeItem(pid);
1323 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001324
Steve Block3856b092011-10-20 11:56:00 +01001325 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001326 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001327 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001328 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001329 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001330 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001331 if (ref->mPid == pid) {
1332 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001333 mAudioSessionRefs.removeAt(i);
1334 delete ref;
1335 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001336 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001337 } else {
1338 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001339 }
1340 }
1341 if (removed) {
1342 purgeStaleEffects_l();
1343 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344}
1345
Eric Laurent73e26b62015-04-27 16:55:58 -07001346void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001347 const sp<AudioIoDescriptor>& ioDesc,
1348 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349{
Eric Laurent021cf962014-05-13 10:18:14 -07001350 Mutex::Autolock _l(mClientLock);
1351 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001353 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1354 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1355 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356 }
1357}
1358
Eric Laurent021cf962014-05-13 10:18:14 -07001359// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360void AudioFlinger::removeClient_l(pid_t pid)
1361{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001362 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001363 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364 mClients.removeItem(pid);
1365}
1366
Eric Laurent717e1282012-06-29 16:36:52 -07001367// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001368sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1369 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001370{
1371 sp<PlaybackThread> thread;
1372
1373 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1374 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1375 ALOG_ASSERT(thread == 0);
1376 thread = mPlaybackThreads.valueAt(i);
1377 }
1378 }
1379
1380 return thread;
1381}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384
1385// ----------------------------------------------------------------------------
1386
1387AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1388 : RefBase(),
1389 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001390 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391{
Sumit Bhattacharyacd64e0e2016-02-11 01:37:20 +05301392 size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
1393 heapSize *= 1024;
1394 if (!heapSize) {
1395 heapSize = kClientSharedHeapSizeBytes;
1396 // Increase heap size on non low ram devices to limit risk of reconnection failure for
1397 // invalidated tracks
1398 if (!audioFlinger->isLowRamDevice()) {
1399 heapSize *= kClientSharedHeapSizeMultiplier;
1400 }
Eric Laurentda73b6c2015-08-20 16:18:53 -07001401 }
1402 mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403}
1404
Eric Laurent021cf962014-05-13 10:18:14 -07001405// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406AudioFlinger::Client::~Client()
1407{
1408 mAudioFlinger->removeClient_l(mPid);
1409}
1410
Glenn Kasten435dbe62012-01-30 10:15:48 -08001411sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412{
1413 return mMemoryDealer;
1414}
1415
1416// ----------------------------------------------------------------------------
1417
1418AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1419 const sp<IAudioFlingerClient>& client,
1420 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001421 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422{
1423}
1424
1425AudioFlinger::NotificationClient::~NotificationClient()
1426{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427}
1428
Glenn Kasten0f11b512014-01-31 16:18:54 -08001429void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001430{
1431 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001432 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433}
1434
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435
1436// ----------------------------------------------------------------------------
1437
1438sp<IAudioRecord> AudioFlinger::openRecord(
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001439 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001441 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001442 audio_channel_mask_t channelMask,
Svet Ganovbe71aa22015-04-28 12:06:02 -07001443 const String16& opPackageName,
Glenn Kasten74935e42013-12-19 08:56:45 -08001444 size_t *frameCount,
Eric Laurent05067782016-06-01 18:27:28 -07001445 audio_input_flags_t *flags,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001446 pid_t pid,
Glenn Kasten1879fff2012-07-11 15:36:59 -07001447 pid_t tid,
Jean-Michel Trivi4cb66832015-05-01 18:34:17 -07001448 int clientUid,
Glenn Kastend848eb42016-03-08 13:42:11 -08001449 audio_session_t *sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001450 size_t *notificationFrames,
Glenn Kastend776ac62014-05-07 09:16:09 -07001451 sp<IMemory>& cblk,
1452 sp<IMemory>& buffers,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001453 status_t *status,
1454 audio_port_handle_t portId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455{
1456 sp<RecordThread::RecordTrack> recordTrack;
1457 sp<RecordHandle> recordHandle;
1458 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459 status_t lStatus;
Glenn Kastend848eb42016-03-08 13:42:11 -08001460 audio_session_t lSessionId;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001461
Glenn Kastend776ac62014-05-07 09:16:09 -07001462 cblk.clear();
1463 buffers.clear();
1464
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001465 bool updatePid = (pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001466 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1467 if (!isTrustedCallingUid(callingUid)) {
Andy Hung879db192016-01-05 16:00:34 -08001468 ALOGW_IF((uid_t)clientUid != callingUid,
Marco Nelissendcb346b2015-09-09 10:47:29 -07001469 "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
1470 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001471 updatePid = true;
1472 }
1473
1474 if (updatePid) {
1475 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
1476 ALOGW_IF(pid != -1 && pid != callingPid,
1477 "%s uid %d pid %d tried to pass itself off as pid %d",
1478 __func__, callingUid, callingPid, pid);
1479 pid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001480 }
1481
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 // check calling permissions
Marco Nelissendcb346b2015-09-09 10:47:29 -07001483 if (!recordingAllowed(opPackageName, tid, clientUid)) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001484 ALOGE("openRecord() permission denied: recording not allowed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 lStatus = PERMISSION_DENIED;
1486 goto Exit;
1487 }
1488
Glenn Kasten53b5d092014-02-05 10:00:23 -08001489 // further sample rate checks are performed by createRecordTrack_l()
1490 if (sampleRate == 0) {
1491 ALOGE("openRecord() invalid sample rate %u", sampleRate);
1492 lStatus = BAD_VALUE;
1493 goto Exit;
1494 }
1495
Andy Hung6770c6f2015-04-07 13:43:36 -07001496 // we don't yet support anything other than linear PCM
1497 if (!audio_is_valid_format(format) || !audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001498 ALOGE("openRecord() invalid format %#x", format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001499 lStatus = BAD_VALUE;
1500 goto Exit;
1501 }
1502
Glenn Kasten53b5d092014-02-05 10:00:23 -08001503 // further channel mask checks are performed by createRecordTrack_l()
1504 if (!audio_is_input_channel(channelMask)) {
1505 ALOGE("openRecord() invalid channel mask %#x", channelMask);
1506 lStatus = BAD_VALUE;
1507 goto Exit;
1508 }
1509
Glenn Kasten05997e22014-03-13 15:08:33 -07001510 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 Mutex::Autolock _l(mLock);
Glenn Kastene848bd92014-03-13 15:00:32 -07001512 RecordThread *thread = checkRecordThread_l(input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 if (thread == NULL) {
Glenn Kastene93cf2c2013-09-24 11:52:37 -07001514 ALOGE("openRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 lStatus = BAD_VALUE;
1516 goto Exit;
1517 }
1518
Eric Laurent021cf962014-05-13 10:18:14 -07001519 client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520
Glenn Kastenaea7ea02013-06-26 09:25:47 -07001521 if (sessionId != NULL && *sessionId != AUDIO_SESSION_ALLOCATE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001522 if (audio_unique_id_get_use(*sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1523 lStatus = BAD_VALUE;
1524 goto Exit;
1525 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 lSessionId = *sessionId;
1527 } else {
Glenn Kasten570f6332014-03-13 15:01:06 -07001528 // if no audio session id is provided, create one here
Glenn Kastend848eb42016-03-08 13:42:11 -08001529 lSessionId = (audio_session_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 if (sessionId != NULL) {
1531 *sessionId = lSessionId;
1532 }
1533 }
Eric Laurentaaa44472014-09-12 17:41:50 -07001534 ALOGV("openRecord() lSessionId: %d input %d", lSessionId, input);
Glenn Kasten570f6332014-03-13 15:01:06 -07001535
Glenn Kasten1879fff2012-07-11 15:36:59 -07001536 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07001537 frameCount, lSessionId, notificationFrames,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001538 clientUid, flags, tid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001539 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001540
1541 if (lStatus == NO_ERROR) {
1542 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1543 // session and move it to this thread.
Glenn Kastend848eb42016-03-08 13:42:11 -08001544 sp<EffectChain> chain = getOrphanEffectChain_l(lSessionId);
Eric Laurent1b928682014-10-02 19:41:47 -07001545 if (chain != 0) {
1546 Mutex::Autolock _l(thread->mLock);
1547 thread->addEffectChain_l(chain);
1548 }
1549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 }
Glenn Kastene198c362013-08-13 09:13:36 -07001551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001552 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001553 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001554 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001555 // Don't hold mClientLock when releasing the reference on the track as the
1556 // destructor will acquire it.
1557 {
1558 Mutex::Autolock _cl(mClientLock);
1559 client.clear();
1560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 goto Exit;
1563 }
1564
Glenn Kastend776ac62014-05-07 09:16:09 -07001565 cblk = recordTrack->getCblk();
1566 buffers = recordTrack->getBuffers();
1567
Glenn Kasten2fc14732013-08-05 14:58:14 -07001568 // return handle to client
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 recordHandle = new RecordHandle(recordTrack);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570
1571Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07001572 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 return recordHandle;
1574}
1575
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001576
1577
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578// ----------------------------------------------------------------------------
1579
Eric Laurenta4c5a552012-03-29 10:12:40 -07001580audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1581{
Eric Laurent44622db2014-08-01 19:00:33 -07001582 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001583 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001584 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001585 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001586 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001587 }
1588 Mutex::Autolock _l(mLock);
1589 return loadHwModule_l(name);
1590}
1591
1592// loadHwModule_l() must be called with AudioFlinger::mLock held
1593audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1594{
1595 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1596 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1597 ALOGW("loadHwModule() module %s already loaded", name);
1598 return mAudioHwDevs.keyAt(i);
1599 }
1600 }
1601
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001602 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001603
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001604 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001605 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001606 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001607 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001608 }
1609
1610 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001611 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001612 mHardwareStatus = AUDIO_HW_IDLE;
1613 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001614 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001615 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001616 }
1617
John Grossmanee578c02012-07-23 17:05:46 -07001618 // Check and cache this HAL's level of support for master mute and master
1619 // volume. If this is the first HAL opened, and it supports the get
1620 // methods, use the initial values provided by the HAL as the current
1621 // master mute and volume settings.
1622
1623 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1624 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001625 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001626
1627 if (0 == mAudioHwDevs.size()) {
1628 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001629 float mv;
1630 if (OK == dev->getMasterVolume(&mv)) {
1631 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001632 }
1633
1634 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001635 bool mm;
1636 if (OK == dev->getMasterMute(&mm)) {
1637 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001638 }
1639 }
1640
Eric Laurenta4c5a552012-03-29 10:12:40 -07001641 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001642 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001643 flags = static_cast<AudioHwDevice::Flags>(flags |
1644 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1645 }
1646
1647 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001648 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001649 flags = static_cast<AudioHwDevice::Flags>(flags |
1650 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1651 }
1652
Eric Laurenta4c5a552012-03-29 10:12:40 -07001653 mHardwareStatus = AUDIO_HW_IDLE;
1654 }
1655
Glenn Kastena13cde92016-03-28 15:26:02 -07001656 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001657 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001658
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001659 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001660
1661 return handle;
1662
1663}
1664
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001665// ----------------------------------------------------------------------------
1666
Glenn Kasten3b16c762012-11-14 08:44:39 -08001667uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001668{
1669 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001670 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001671 return thread != NULL ? thread->sampleRate() : 0;
1672}
1673
Glenn Kastene33054e2012-11-14 12:54:39 -08001674size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001675{
1676 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001677 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001678 return thread != NULL ? thread->frameCountHAL() : 0;
1679}
1680
1681// ----------------------------------------------------------------------------
1682
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001683status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice)
1684{
1685 uid_t uid = IPCThreadState::self()->getCallingUid();
1686 if (uid != AID_SYSTEM) {
1687 return PERMISSION_DENIED;
1688 }
1689 Mutex::Autolock _l(mLock);
1690 if (mIsDeviceTypeKnown) {
1691 return INVALID_OPERATION;
1692 }
1693 mIsLowRamDevice = isLowRamDevice;
1694 mIsDeviceTypeKnown = true;
1695 return NO_ERROR;
1696}
1697
Eric Laurent93c3d412014-08-01 14:48:35 -07001698audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
1699{
1700 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07001701
1702 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1703 if (index >= 0) {
1704 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
1705 mHwAvSyncIds.valueAt(index), sessionId);
1706 return mHwAvSyncIds.valueAt(index);
1707 }
1708
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001709 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07001710 if (dev == NULL) {
1711 return AUDIO_HW_SYNC_INVALID;
1712 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001713 String8 reply;
1714 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001715 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001716 param = AudioParameter(reply);
1717 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001718
1719 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001720 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001721 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
1722 return AUDIO_HW_SYNC_INVALID;
1723 }
1724
1725 // allow only one session for a given HW A/V sync ID.
1726 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
1727 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
1728 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
1729 value, mHwAvSyncIds.keyAt(i));
1730 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07001731 break;
1732 }
1733 }
Eric Laurentfa90e842014-10-17 18:12:31 -07001734
1735 mHwAvSyncIds.add(sessionId, value);
1736
1737 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1738 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
1739 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07001740 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07001741 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001742 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Eric Laurentfa90e842014-10-17 18:12:31 -07001743 thread->setParameters(param.toString());
1744 break;
1745 }
1746 }
1747
1748 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
1749 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07001750}
1751
Eric Laurent72e3f392015-05-20 14:43:50 -07001752status_t AudioFlinger::systemReady()
1753{
1754 Mutex::Autolock _l(mLock);
1755 ALOGI("%s", __FUNCTION__);
1756 if (mSystemReady) {
1757 ALOGW("%s called twice", __FUNCTION__);
1758 return NO_ERROR;
1759 }
1760 mSystemReady = true;
1761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1762 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
1763 thread->systemReady();
1764 }
1765 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1766 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
1767 thread->systemReady();
1768 }
1769 return NO_ERROR;
1770}
1771
Eric Laurentfa90e842014-10-17 18:12:31 -07001772// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
1773void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
1774{
1775 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
1776 if (index >= 0) {
1777 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
1778 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
1779 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07001780 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Eric Laurentfa90e842014-10-17 18:12:31 -07001781 thread->setParameters(param.toString());
1782 }
1783}
1784
1785
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001786// ----------------------------------------------------------------------------
1787
Eric Laurent83b88082014-06-20 18:31:16 -07001788
1789sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001790 audio_io_handle_t *output,
1791 audio_config_t *config,
1792 audio_devices_t devices,
1793 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07001794 audio_output_flags_t flags)
1795{
Eric Laurentcf2c0212014-07-25 16:20:43 -07001796 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07001797 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001798 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07001799 }
1800
Eric Laurentcf2c0212014-07-25 16:20:43 -07001801 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001802 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
1803 } else {
1804 // Audio Policy does not currently request a specific output handle.
1805 // If this is ever needed, see openInput_l() for example code.
1806 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
1807 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001808 }
Eric Laurent83b88082014-06-20 18:31:16 -07001809
1810 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
1811
Eric Laurent83b88082014-06-20 18:31:16 -07001812 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07001813 // This if statement allows overriding the audio policy settings
1814 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
1815 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
1816 // Check only for Normal Mixing mode
1817 if (kEnableExtendedPrecision) {
1818 // Specify format (uncomment one below to choose)
1819 //config->format = AUDIO_FORMAT_PCM_FLOAT;
1820 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
1821 //config->format = AUDIO_FORMAT_PCM_32_BIT;
1822 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001823 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07001824 }
1825 if (kEnableExtendedChannels) {
1826 // Specify channel mask (uncomment one below to choose)
1827 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
1828 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
1829 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
1830 }
Eric Laurent83b88082014-06-20 18:31:16 -07001831 }
1832
Phil Burk062e67a2015-02-11 13:40:50 -08001833 AudioStreamOut *outputStream = NULL;
1834 status_t status = outHwDev->openOutputStream(
1835 &outputStream,
1836 *output,
1837 devices,
1838 flags,
1839 config,
1840 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07001841
1842 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07001843
Phil Burk062e67a2015-02-11 13:40:50 -08001844 if (status == NO_ERROR) {
Eric Laurent83b88082014-06-20 18:31:16 -07001845
1846 PlaybackThread *thread;
1847 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Eric Laurente93cc032016-05-05 10:15:10 -07001848 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001849 ALOGV("openOutput_l() created offload output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001850 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
1851 || !isValidPcmSinkFormat(config->format)
Andy Hung9a592762014-07-21 21:56:01 -07001852 || !isValidPcmSinkChannelMask(config->channel_mask)) {
Eric Laurent72e3f392015-05-20 14:43:50 -07001853 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001854 ALOGV("openOutput_l() created direct output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001855 } else {
Eric Laurent72e3f392015-05-20 14:43:50 -07001856 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001857 ALOGV("openOutput_l() created mixer output: ID %d thread %p", *output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001858 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001859 mPlaybackThreads.add(*output, thread);
Eric Laurent83b88082014-06-20 18:31:16 -07001860 return thread;
1861 }
1862
1863 return 0;
1864}
1865
Eric Laurentcf2c0212014-07-25 16:20:43 -07001866status_t AudioFlinger::openOutput(audio_module_handle_t module,
1867 audio_io_handle_t *output,
1868 audio_config_t *config,
1869 audio_devices_t *devices,
1870 const String8& address,
1871 uint32_t *latencyMs,
1872 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873{
Phil Burk062e67a2015-02-11 13:40:50 -08001874 ALOGI("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",
Eric Laurenta4c5a552012-03-29 10:12:40 -07001875 module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001876 (devices != NULL) ? *devices : 0,
1877 config->sample_rate,
1878 config->format,
1879 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07001880 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 if (*devices == AUDIO_DEVICE_NONE) {
1883 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001885
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 Mutex::Autolock _l(mLock);
1887
Eric Laurentcf2c0212014-07-25 16:20:43 -07001888 sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07001889 if (thread != 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07001890 *latencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891
1892 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001893 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001894
1895 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07001896 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001897 ALOGI("Using module %d has the primary audio interface", module);
Eric Laurent83b88082014-06-20 18:31:16 -07001898 mPrimaryHardwareDev = thread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001899
1900 AutoMutex lock(mHardwareLock);
1901 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001902 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001903 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001904 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001905 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 }
1907
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909}
1910
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001911audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
1912 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913{
1914 Mutex::Autolock _l(mLock);
1915 MixerThread *thread1 = checkMixerThread_l(output1);
1916 MixerThread *thread2 = checkMixerThread_l(output2);
1917
1918 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001919 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
1920 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07001921 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 }
1923
Glenn Kasteneeecb982016-02-26 10:44:04 -08001924 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07001925 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 thread->addOutputTrack(thread2);
1927 mPlaybackThreads.add(id, thread);
1928 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07001929 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 return id;
1931}
1932
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001933status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934{
Glenn Kastend96c5722012-04-25 13:44:49 -07001935 return closeOutput_nonvirtual(output);
1936}
1937
1938status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
1939{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 // keep strong reference on the playback thread so that
1941 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001942 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 {
1944 Mutex::Autolock _l(mLock);
1945 thread = checkPlaybackThread_l(output);
1946 if (thread == NULL) {
1947 return BAD_VALUE;
1948 }
1949
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001952 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentf6870ae2015-05-08 10:50:03 -07001954 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001955 DuplicatingThread *dupThread =
1956 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurentbfb1b832013-01-07 09:53:42 -08001958 }
1959 }
1960 }
1961
1962
1963 mPlaybackThreads.removeItem(output);
1964 // save all effects to the default thread
1965 if (mPlaybackThreads.size()) {
1966 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
1967 if (dstThread != NULL) {
1968 // audioflinger lock is held here so the acquisition order of thread locks does not
1969 // matter
1970 Mutex::Autolock _dl(dstThread->mLock);
1971 Mutex::Autolock _sl(thread->mLock);
1972 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
1973 for (size_t i = 0; i < effectChains.size(); i ++) {
1974 moveEffectChain_l(effectChains[i]->sessionId(), thread.get(), dstThread, true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976 }
1977 }
Eric Laurent73e26b62015-04-27 16:55:58 -07001978 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
1979 ioDesc->mIoHandle = output;
1980 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 }
1982 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08001983 // The thread entity (active unit of execution) is no longer running here,
1984 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985
Eric Laurentf6870ae2015-05-08 10:50:03 -07001986 if (!thread->isDuplicating()) {
Eric Laurent83b88082014-06-20 18:31:16 -07001987 closeOutputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
Eric Laurent83b88082014-06-20 18:31:16 -07001989
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 return NO_ERROR;
1991}
1992
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001993void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07001994{
1995 AudioStreamOut *out = thread->clearOutput();
1996 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
1997 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07001998 delete out;
1999}
2000
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002001void AudioFlinger::closeOutputInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002002{
2003 mPlaybackThreads.removeItem(thread->mId);
2004 thread->exit();
2005 closeOutputFinish(thread);
2006}
2007
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002008status_t AudioFlinger::suspendOutput(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("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 thread->suspend();
2019
2020 return NO_ERROR;
2021}
2022
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002023status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024{
2025 Mutex::Autolock _l(mLock);
2026 PlaybackThread *thread = checkPlaybackThread_l(output);
2027
2028 if (thread == NULL) {
2029 return BAD_VALUE;
2030 }
2031
Steve Block3856b092011-10-20 11:56:00 +01002032 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033
2034 thread->restore();
2035
2036 return NO_ERROR;
2037}
2038
Eric Laurentcf2c0212014-07-25 16:20:43 -07002039status_t AudioFlinger::openInput(audio_module_handle_t module,
2040 audio_io_handle_t *input,
2041 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002042 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002043 const String8& address,
2044 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002045 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046{
Eric Laurent83b88082014-06-20 18:31:16 -07002047 Mutex::Autolock _l(mLock);
2048
Glenn Kastene7d66712015-03-05 13:46:52 -08002049 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002050 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002051 }
2052
Glenn Kastene7d66712015-03-05 13:46:52 -08002053 sp<RecordThread> thread = openInput_l(module, input, config, *devices, address, source, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002054
2055 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002056 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002057 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002058 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002060 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002061}
Dima Zavin799a70e2011-04-18 16:57:27 -07002062
Eric Laurent83b88082014-06-20 18:31:16 -07002063sp<AudioFlinger::RecordThread> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002064 audio_io_handle_t *input,
2065 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002066 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002067 const String8& address,
2068 audio_source_t source,
Eric Laurent83b88082014-06-20 18:31:16 -07002069 audio_input_flags_t flags)
2070{
Glenn Kastene7d66712015-03-05 13:46:52 -08002071 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002072 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002073 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002074 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002075 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002076
Glenn Kasteneeecb982016-02-26 10:44:04 -08002077 // Audio Policy can request a specific handle for hardware hotword.
2078 // The goal here is not to re-open an already opened input.
2079 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002080 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002081 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2082 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2083 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2084 return 0;
2085 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2086 // This should not happen in a transient state with current design.
2087 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2088 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002089 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002090
Eric Laurentcf2c0212014-07-25 16:20:43 -07002091 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002092 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002093 sp<StreamInHalInterface> inStream;
2094 status_t status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002095 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Mikhail Naganovf558e022016-11-14 17:45:17 -08002096 ALOGV("openInput_l() openInputStream returned input %p, devices %x, SamplingRate %d"
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002097 ", Format %#x, Channels %x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002098 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002099 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002100 halconfig.sample_rate,
2101 halconfig.format,
2102 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002103 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002104 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002106 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002107 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002108 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002109 audio_is_linear_pcm(config->format) &&
2110 audio_is_linear_pcm(halconfig.format) &&
2111 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002112 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2113 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002114 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002115 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002116 inStream.clear();
2117 status = inHwHal->openInputStream(
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002118 *input, devices, &halconfig, flags, address.string(), source, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002119 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 }
2121
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002122 if (status == NO_ERROR && inStream != 0) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002123
Glenn Kasten46909e72013-02-26 09:20:22 -08002124#ifdef TEE_SINK
Glenn Kastend06785b2012-09-30 12:29:28 -07002125 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
2126 // or (re-)create if current Pipe is idle and does not match the new format
2127 sp<NBAIO_Sink> teeSink;
Glenn Kastend06785b2012-09-30 12:29:28 -07002128 enum {
2129 TEE_SINK_NO, // don't copy input
2130 TEE_SINK_NEW, // copy input using a new pipe
2131 TEE_SINK_OLD, // copy input using an existing pipe
2132 } kind;
Glenn Kasten329f6512014-08-28 16:23:16 -07002133 NBAIO_Format format = Format_from_SR_C(halconfig.sample_rate,
2134 audio_channel_count_from_in_mask(halconfig.channel_mask), halconfig.format);
Glenn Kastenda6ef132013-01-10 12:31:01 -08002135 if (!mTeeSinkInputEnabled) {
2136 kind = TEE_SINK_NO;
Glenn Kasten6e0d67d2014-01-31 09:41:08 -08002137 } else if (!Format_isValid(format)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002138 kind = TEE_SINK_NO;
2139 } else if (mRecordTeeSink == 0) {
2140 kind = TEE_SINK_NEW;
2141 } else if (mRecordTeeSink->getStrongCount() != 1) {
2142 kind = TEE_SINK_NO;
Glenn Kastenf66b4222014-02-20 10:23:28 -08002143 } else if (Format_isEqual(format, mRecordTeeSink->format())) {
Glenn Kastend06785b2012-09-30 12:29:28 -07002144 kind = TEE_SINK_OLD;
2145 } else {
2146 kind = TEE_SINK_NEW;
2147 }
2148 switch (kind) {
2149 case TEE_SINK_NEW: {
Glenn Kastenda6ef132013-01-10 12:31:01 -08002150 Pipe *pipe = new Pipe(mTeeSinkInputFrames, format);
Glenn Kastend06785b2012-09-30 12:29:28 -07002151 size_t numCounterOffers = 0;
2152 const NBAIO_Format offers[1] = {format};
2153 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
2154 ALOG_ASSERT(index == 0);
2155 PipeReader *pipeReader = new PipeReader(*pipe);
2156 numCounterOffers = 0;
2157 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
2158 ALOG_ASSERT(index == 0);
2159 mRecordTeeSink = pipe;
2160 mRecordTeeSource = pipeReader;
2161 teeSink = pipe;
2162 }
2163 break;
2164 case TEE_SINK_OLD:
2165 teeSink = mRecordTeeSink;
2166 break;
2167 case TEE_SINK_NO:
2168 default:
2169 break;
2170 }
Glenn Kasten46909e72013-02-26 09:20:22 -08002171#endif
Glenn Kastenda6ef132013-01-10 12:31:01 -08002172
Eric Laurent05067782016-06-01 18:27:28 -07002173 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Dima Zavin799a70e2011-04-18 16:57:27 -07002174
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002175 // Start record thread
Glenn Kasten34af0262013-07-30 11:52:39 -07002176 // RecordThread requires both input and output device indication to forward to audio
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002177 // pre processing modules
Eric Laurent83b88082014-06-20 18:31:16 -07002178 sp<RecordThread> thread = new RecordThread(this,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002179 inputStream,
2180 *input,
Eric Laurentd3922f72013-02-01 17:57:04 -08002181 primaryOutputDevice_l(),
Eric Laurent72e3f392015-05-20 14:43:50 -07002182 devices,
2183 mSystemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08002184#ifdef TEE_SINK
2185 , teeSink
2186#endif
2187 );
Eric Laurentcf2c0212014-07-25 16:20:43 -07002188 mRecordThreads.add(*input, thread);
2189 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
Eric Laurent83b88082014-06-20 18:31:16 -07002190 return thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 }
2192
Eric Laurentcf2c0212014-07-25 16:20:43 -07002193 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 return 0;
2195}
2196
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002197status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198{
Glenn Kastend96c5722012-04-25 13:44:49 -07002199 return closeInput_nonvirtual(input);
2200}
2201
2202status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2203{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 // keep strong reference on the record thread so that
2205 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002206 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 {
2208 Mutex::Autolock _l(mLock);
2209 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002210 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 return BAD_VALUE;
2212 }
2213
Steve Block3856b092011-10-20 11:56:00 +01002214 ALOGV("closeInput() %d", input);
Eric Laurent1b928682014-10-02 19:41:47 -07002215
2216 // If we still have effect chains, it means that a client still holds a handle
2217 // on at least one effect. We must either move the chain to an existing thread with the
2218 // same session ID or put it aside in case a new record thread is opened for a
2219 // new capture on the same session
2220 sp<EffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07002221 {
Eric Laurentaaa44472014-09-12 17:41:50 -07002222 Mutex::Autolock _sl(thread->mLock);
2223 Vector< sp<EffectChain> > effectChains = thread->getEffectChains_l();
Eric Laurent1b928682014-10-02 19:41:47 -07002224 // Note: maximum one chain per record thread
2225 if (effectChains.size() != 0) {
2226 chain = effectChains[0];
2227 }
2228 }
2229 if (chain != 0) {
2230 // first check if a record thread is already opened with a client on the same session.
2231 // This should only happen in case of overlap between one thread tear down and the
2232 // creation of its replacement
2233 size_t i;
2234 for (i = 0; i < mRecordThreads.size(); i++) {
2235 sp<RecordThread> t = mRecordThreads.valueAt(i);
2236 if (t == thread) {
2237 continue;
2238 }
2239 if (t->hasAudioSession(chain->sessionId()) != 0) {
2240 Mutex::Autolock _l(t->mLock);
2241 ALOGV("closeInput() found thread %d for effect session %d",
2242 t->id(), chain->sessionId());
2243 t->addEffectChain_l(chain);
2244 break;
2245 }
2246 }
2247 // put the chain aside if we could not find a record thread with the same session id.
2248 if (i == mRecordThreads.size()) {
2249 putOrphanEffectChain_l(chain);
Eric Laurentaaa44472014-09-12 17:41:50 -07002250 }
2251 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002252 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2253 ioDesc->mIoHandle = input;
2254 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 mRecordThreads.removeItem(input);
2256 }
Eric Laurent83b88082014-06-20 18:31:16 -07002257 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2258 // we have a different lock for notification client
2259 closeInputFinish(thread);
2260 return NO_ERROR;
2261}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002263void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002264{
2265 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002266 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002267 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002268 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002269 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002270}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002272void AudioFlinger::closeInputInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002273{
2274 mRecordThreads.removeItem(thread->mId);
2275 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276}
2277
Glenn Kastend2304db2014-02-03 07:40:31 -08002278status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279{
2280 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002281 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282
2283 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2284 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002285 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287
2288 return NO_ERROR;
2289}
2290
2291
Glenn Kasteneeecb982016-02-26 10:44:04 -08002292audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293{
Glenn Kasten9d003132016-04-06 14:38:09 -07002294 // This is a binder API, so a malicious client could pass in a bad parameter.
2295 // Check for that before calling the internal API nextUniqueId().
2296 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2297 ALOGE("newAudioUniqueId invalid use %d", use);
2298 return AUDIO_UNIQUE_ID_ALLOCATE;
2299 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002300 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301}
2302
Glenn Kastend848eb42016-03-08 13:42:11 -08002303void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002304{
2305 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002306 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002307 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
2308 if (pid != -1 && (caller == getpid_cached)) {
2309 caller = pid;
2310 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002311
Eric Laurent021cf962014-05-13 10:18:14 -07002312 {
2313 Mutex::Autolock _cl(mClientLock);
2314 // Ignore requests received from processes not known as notification client. The request
2315 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2316 // called from a different pid leaving a stale session reference. Also we don't know how
2317 // to clear this reference if the client process dies.
2318 if (mNotificationClients.indexOfKey(caller) < 0) {
2319 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2320 return;
2321 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002322 }
2323
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002324 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002325 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002326 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002327 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2328 ref->mCnt++;
2329 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002330 return;
2331 }
2332 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002333 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2334 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002335}
2336
Glenn Kastend848eb42016-03-08 13:42:11 -08002337void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002338{
2339 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002340 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002341 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2342 if (pid != -1 && (caller == getpid_cached)) {
2343 caller = pid;
2344 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002345 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002346 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002347 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002348 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2349 ref->mCnt--;
2350 ALOGV(" decremented refcount to %d", ref->mCnt);
2351 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002352 mAudioSessionRefs.removeAt(i);
2353 delete ref;
2354 purgeStaleEffects_l();
2355 }
2356 return;
2357 }
2358 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002359 // If the caller is mediaserver it is likely that the session being released was acquired
2360 // on behalf of a process not in notification clients and we ignore the warning.
2361 ALOGW_IF(caller != getpid_cached, "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002362}
2363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002364bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2365{
2366 size_t num = mAudioSessionRefs.size();
2367 for (size_t i = 0; i < num; i++) {
2368 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2369 if (ref->mSessionid == audioSession) {
2370 return true;
2371 }
2372 }
2373 return false;
2374}
2375
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002376void AudioFlinger::purgeStaleEffects_l() {
2377
Steve Block3856b092011-10-20 11:56:00 +01002378 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002379
2380 Vector< sp<EffectChain> > chains;
2381
2382 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2383 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2384 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2385 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002386 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2387 chains.push(ec);
2388 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002389 }
2390 }
2391 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2392 sp<RecordThread> t = mRecordThreads.valueAt(i);
2393 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2394 sp<EffectChain> ec = t->mEffectChains[j];
2395 chains.push(ec);
2396 }
2397 }
2398
2399 for (size_t i = 0; i < chains.size(); i++) {
2400 sp<EffectChain> ec = chains[i];
2401 int sessionid = ec->sessionId();
2402 sp<ThreadBase> t = ec->mThread.promote();
2403 if (t == 0) {
2404 continue;
2405 }
2406 size_t numsessionrefs = mAudioSessionRefs.size();
2407 bool found = false;
2408 for (size_t k = 0; k < numsessionrefs; k++) {
2409 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002410 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002411 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002412 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002413 found = true;
2414 break;
2415 }
2416 }
2417 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002418 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002419 // remove all effects from the chain
2420 while (ec->mEffects.size()) {
2421 sp<EffectModule> effect = ec->mEffects[0];
2422 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002423 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002424 if (effect->purgeHandles()) {
2425 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002426 }
2427 AudioSystem::unregisterEffect(effect->id());
2428 }
2429 }
2430 }
2431 return;
2432}
2433
Glenn Kasteneeecb982016-02-26 10:44:04 -08002434// checkThread_l() must be called with AudioFlinger::mLock held
2435AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2436{
2437 ThreadBase *thread = NULL;
2438 switch (audio_unique_id_get_use(ioHandle)) {
2439 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2440 thread = checkPlaybackThread_l(ioHandle);
2441 break;
2442 case AUDIO_UNIQUE_ID_USE_INPUT:
2443 thread = checkRecordThread_l(ioHandle);
2444 break;
2445 default:
2446 break;
2447 }
2448 return thread;
2449}
2450
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002452AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453{
Glenn Kastena1117922012-01-26 10:53:32 -08002454 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455}
2456
2457// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002458AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459{
2460 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002461 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462}
2463
2464// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002465AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466{
Glenn Kastena1117922012-01-26 10:53:32 -08002467 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468}
2469
Glenn Kasteneeecb982016-02-26 10:44:04 -08002470audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471{
Glenn Kasten9d003132016-04-06 14:38:09 -07002472 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002473 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002474 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2475 for (int retry = 0; retry < maxRetries; retry++) {
2476 // The cast allows wraparound from max positive to min negative instead of abort
2477 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2478 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2479 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2480 // allow wrap by skipping 0 and -1 for session ids
2481 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2482 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2483 return (audio_unique_id_t) (base | use);
2484 }
2485 }
2486 // We have no way of recovering from wraparound
2487 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2488 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489}
2490
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002491AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002492{
2493 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2494 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002495 if(thread->isDuplicating()) {
2496 continue;
2497 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002498 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002499 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002500 return thread;
2501 }
2502 }
2503 return NULL;
2504}
2505
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002506audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002507{
2508 PlaybackThread *thread = primaryPlaybackThread_l();
2509
2510 if (thread == NULL) {
2511 return 0;
2512 }
2513
Eric Laurentf1c04f92012-08-28 14:26:53 -07002514 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002515}
2516
Glenn Kastena7335632016-06-09 17:09:53 -07002517AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2518{
2519 size_t minFrameCount = 0;
2520 PlaybackThread *minThread = NULL;
2521 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2522 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2523 if (!thread->isDuplicating()) {
2524 size_t frameCount = thread->frameCountHAL();
2525 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2526 (frameCount == minFrameCount && thread->hasFastMixer() &&
2527 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2528 minFrameCount = frameCount;
2529 minThread = thread;
2530 }
2531 }
2532 }
2533 return minThread;
2534}
2535
Eric Laurenta011e352012-03-29 15:51:43 -07002536sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002537 audio_session_t triggerSession,
2538 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002539 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002540 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002541{
2542 Mutex::Autolock _l(mLock);
2543
2544 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2545 status_t playStatus = NAME_NOT_FOUND;
2546 status_t recStatus = NAME_NOT_FOUND;
2547 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2548 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
2549 if (playStatus == NO_ERROR) {
2550 return event;
2551 }
2552 }
2553 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2554 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
2555 if (recStatus == NO_ERROR) {
2556 return event;
2557 }
2558 }
2559 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
2560 mPendingSyncEvents.add(event);
2561 } else {
2562 ALOGV("createSyncEvent() invalid event %d", event->type());
2563 event.clear();
2564 }
2565 return event;
2566}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002567
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568// ----------------------------------------------------------------------------
2569// Effect management
2570// ----------------------------------------------------------------------------
2571
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002572sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
2573 return mEffectsFactoryHal;
2574}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575
Glenn Kastenf587ba52012-01-26 16:25:10 -08002576status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577{
2578 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002579 if (mEffectsFactoryHal.get()) {
2580 return mEffectsFactoryHal->queryNumberEffects(numEffects);
2581 } else {
2582 return -ENODEV;
2583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584}
2585
Glenn Kastenf587ba52012-01-26 16:25:10 -08002586status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587{
2588 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002589 if (mEffectsFactoryHal.get()) {
2590 return mEffectsFactoryHal->getDescriptor(index, descriptor);
2591 } else {
2592 return -ENODEV;
2593 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594}
2595
Glenn Kasten5e92a782012-01-30 07:40:52 -08002596status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08002597 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598{
2599 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002600 if (mEffectsFactoryHal.get()) {
2601 return mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
2602 } else {
2603 return -ENODEV;
2604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605}
2606
2607
Glenn Kasten8d6cc842012-02-03 11:06:53 -08002608sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 effect_descriptor_t *pDesc,
2610 const sp<IEffectClient>& effectClient,
2611 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002612 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08002613 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07002614 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08002615 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 status_t *status,
2617 int *id,
2618 int *enabled)
2619{
2620 status_t lStatus = NO_ERROR;
2621 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623
Eric Laurentb6436272016-12-07 19:24:50 -08002624 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2625 if (pid == -1 || !isTrustedCallingUid(callingUid)) {
2626 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
2627 ALOGW_IF(pid != -1 && pid != callingPid,
2628 "%s uid %d pid %d tried to pass itself off as pid %d",
2629 __func__, callingUid, callingPid, pid);
2630 pid = callingPid;
2631 }
2632
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002633 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
2634 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635
2636 if (pDesc == NULL) {
2637 lStatus = BAD_VALUE;
2638 goto Exit;
2639 }
2640
Eric Laurent84e9a102010-09-23 16:10:16 -07002641 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07002642 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002643 lStatus = PERMISSION_DENIED;
2644 goto Exit;
2645 }
2646
Dima Zavinfce7a472011-04-19 22:30:36 -07002647 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07002648 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08002649 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07002650 lStatus = PERMISSION_DENIED;
2651 goto Exit;
2652 }
2653
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002654 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002655 lStatus = NO_INIT;
2656 goto Exit;
2657 }
2658
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002660 if (!EffectsFactoryHalInterface::isNullUuid(&pDesc->uuid)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 // if uuid is specified, request effect descriptor
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002662 lStatus = mEffectsFactoryHal->getDescriptor(&pDesc->uuid, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002664 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 goto Exit;
2666 }
2667 } else {
2668 // if uuid is not specified, look for an available implementation
2669 // of the required type in effect factory
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002670 if (EffectsFactoryHalInterface::isNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002671 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672 lStatus = BAD_VALUE;
2673 goto Exit;
2674 }
2675 uint32_t numEffects = 0;
2676 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002677 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07002678 bool found = false;
2679
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002680 lStatus = mEffectsFactoryHal->queryNumberEffects(&numEffects);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002682 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 goto Exit;
2684 }
2685 for (uint32_t i = 0; i < numEffects; i++) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07002686 lStatus = mEffectsFactoryHal->getDescriptor(i, &desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002688 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 continue;
2690 }
2691 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
2692 // If matching type found save effect descriptor. If the session is
2693 // 0 and the effect is not auxiliary, continue enumeration in case
2694 // an auxiliary version of this effect type is available
2695 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08002696 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07002697 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2699 break;
2700 }
2701 }
2702 }
2703 if (!found) {
2704 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00002705 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 goto Exit;
2707 }
2708 // For same effect type, chose auxiliary version over insert version if
2709 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07002710 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08002712 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 }
2714 }
2715
2716 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07002717 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2719 lStatus = INVALID_OPERATION;
2720 goto Exit;
2721 }
2722
Eric Laurent59255e42011-07-27 19:49:51 -07002723 // check recording permission for visualizer
2724 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Marco Nelissendcb346b2015-09-09 10:47:29 -07002725 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07002726 lStatus = PERMISSION_DENIED;
2727 goto Exit;
2728 }
2729
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08002731 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07002732 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002733 // if the output returned by getOutputForEffect() is removed before we lock the
2734 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
2735 // and we will exit safely
2736 io = AudioSystem::getOutputForEffect(&desc);
2737 ALOGV("createEffect got output %d", io);
2738 }
2739
2740 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741
2742 // If output is not specified try to find a matching audio session ID in one of the
2743 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07002744 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
2745 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002746 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07002747 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07002748 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
2749 // output must be specified by AudioPolicyManager when using session
2750 // AUDIO_SESSION_OUTPUT_STAGE
2751 lStatus = BAD_VALUE;
2752 goto Exit;
2753 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07002754 // look for the thread where the specified audio session is present
2755 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2756 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2757 io = mPlaybackThreads.keyAt(i);
2758 break;
2759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002761 if (io == 0) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07002762 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2763 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
2764 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002765 break;
2766 }
2767 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002768 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002769 // If no output thread contains the requested session ID, default to
2770 // first output. The effect chain will be moved to the correct output
2771 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07002772 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002773 io = mPlaybackThreads.keyAt(0);
2774 }
Steve Block3856b092011-10-20 11:56:00 +01002775 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002776 }
2777 ThreadBase *thread = checkRecordThread_l(io);
2778 if (thread == NULL) {
2779 thread = checkPlaybackThread_l(io);
2780 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00002781 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002782 lStatus = BAD_VALUE;
2783 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07002784 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002785 } else {
2786 // Check if one effect chain was awaiting for an effect to be created on this
2787 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08002788 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07002789 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07002790 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07002791 thread->addEffectChain_l(chain);
2792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 }
Eric Laurent84e9a102010-09-23 16:10:16 -07002794
Eric Laurent021cf962014-05-13 10:18:14 -07002795 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002797 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002798 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002799 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002800 &desc, enabled, &lStatus, pinned);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 if (handle != 0 && id != NULL) {
2802 *id = handle->id();
2803 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002804 if (handle == 0) {
2805 // remove local strong reference to Client with mClientLock held
2806 Mutex::Autolock _cl(mClientLock);
2807 client.clear();
2808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 }
2810
2811Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002812 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 return handle;
2814}
2815
Glenn Kastend848eb42016-03-08 13:42:11 -08002816status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002817 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07002818{
Steve Block3856b092011-10-20 11:56:00 +01002819 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07002820 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002821 Mutex::Autolock _l(mLock);
2822 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002823 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002824 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 }
Eric Laurentde070132010-07-13 04:45:46 -07002826 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
2827 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002828 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002829 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 }
Eric Laurentde070132010-07-13 04:45:46 -07002831 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
2832 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002833 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07002834 return BAD_VALUE;
2835 }
2836
2837 Mutex::Autolock _dl(dstThread->mLock);
2838 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002839 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840}
2841
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002842// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08002843status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07002844 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07002845 AudioFlinger::PlaybackThread *dstThread,
2846 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07002847{
Steve Block3856b092011-10-20 11:56:00 +01002848 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002849 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07002850
Eric Laurent59255e42011-07-27 19:49:51 -07002851 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07002852 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002853 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07002854 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07002855 return INVALID_OPERATION;
2856 }
2857
Eric Laurent4c415062016-06-17 16:14:16 -07002858 // Check whether the destination thread and all effects in the chain are compatible
2859 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07002860 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07002861 " destination thread %p is not compatible with effects in the chain",
2862 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07002863 return INVALID_OPERATION;
2864 }
2865
Eric Laurent39e94f82010-07-28 01:32:47 -07002866 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07002867 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07002868 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07002869 // removed.
2870 srcThread->removeEffectChain_l(chain);
2871
2872 // transfer all effects one by one so that new effect chain is created on new thread with
2873 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07002874 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002875 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07002876 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002877 Vector< sp<EffectModule> > removed;
2878 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07002879 while (effect != 0) {
2880 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002881 removed.add(effect);
2882 status = dstThread->addEffect_l(effect);
2883 if (status != NO_ERROR) {
2884 break;
2885 }
Eric Laurentec35a142011-10-05 17:42:25 -07002886 // removeEffect_l() has stopped the effect if it was active so it must be restarted
2887 if (effect->state() == EffectModule::ACTIVE ||
2888 effect->state() == EffectModule::STOPPING) {
2889 effect->start();
2890 }
Eric Laurent39e94f82010-07-28 01:32:47 -07002891 // if the move request is not received from audio policy manager, the effect must be
2892 // re-registered with the new strategy and output
2893 if (dstChain == 0) {
2894 dstChain = effect->chain().promote();
2895 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002896 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002897 status = NO_INIT;
2898 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07002899 }
2900 strategy = dstChain->strategy();
2901 }
2902 if (reRegister) {
2903 AudioSystem::unregisterEffect(effect->id());
2904 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07002905 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07002906 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07002907 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07002908 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002909 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07002910 }
Eric Laurentde070132010-07-13 04:45:46 -07002911 effect = chain->getEffectFromId_l(0);
2912 }
2913
Eric Laurent5baf2af2013-09-12 17:37:00 -07002914 if (status != NO_ERROR) {
2915 for (size_t i = 0; i < removed.size(); i++) {
2916 srcThread->addEffect_l(removed[i]);
2917 if (dstChain != 0 && reRegister) {
2918 AudioSystem::unregisterEffect(removed[i]->id());
2919 AudioSystem::registerEffect(&removed[i]->desc(),
2920 srcThread->id(),
2921 strategy,
2922 sessionId,
2923 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07002924 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07002925 }
2926 }
2927 }
2928
2929 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930}
2931
Eric Laurent5baf2af2013-09-12 17:37:00 -07002932bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07002933{
2934 if (mGlobalEffectEnableTime != 0 &&
2935 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
2936 return true;
2937 }
2938
2939 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2940 sp<EffectChain> ec =
2941 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07002942 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07002943 return true;
2944 }
2945 }
2946 return false;
2947}
2948
Eric Laurent5baf2af2013-09-12 17:37:00 -07002949void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07002950{
2951 Mutex::Autolock _l(mLock);
2952
2953 mGlobalEffectEnableTime = systemTime();
2954
2955 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2956 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
2957 if (t->mType == ThreadBase::OFFLOAD) {
2958 t->invalidateTracks(AUDIO_STREAM_MUSIC);
2959 }
2960 }
2961
2962}
2963
Eric Laurentaaa44472014-09-12 17:41:50 -07002964status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
2965{
Glenn Kastend848eb42016-03-08 13:42:11 -08002966 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002967 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002968 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002969 if (index >= 0) {
2970 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
2971 return ALREADY_EXISTS;
2972 }
2973 mOrphanEffectChains.add(session, chain);
2974 return NO_ERROR;
2975}
2976
2977sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
2978{
2979 sp<EffectChain> chain;
2980 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002981 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002982 if (index >= 0) {
2983 chain = mOrphanEffectChains.valueAt(index);
2984 mOrphanEffectChains.removeItemsAt(index);
2985 }
2986 return chain;
2987}
2988
2989bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
2990{
2991 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08002992 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07002993 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002994 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002995 if (index >= 0) {
2996 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002997 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002998 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07002999 mOrphanEffectChains.removeItemsAt(index);
3000 }
3001 return true;
3002 }
3003 return false;
3004}
3005
3006
Glenn Kastenda6ef132013-01-10 12:31:01 -08003007struct Entry {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003008#define TEE_MAX_FILENAME 32 // %Y%m%d%H%M%S_%d.wav = 4+2+2+2+2+2+1+1+4+1 = 21
3009 char mFileName[TEE_MAX_FILENAME];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003010};
3011
3012int comparEntry(const void *p1, const void *p2)
3013{
Glenn Kasten2f55e762015-03-05 16:05:08 -08003014 return strcmp(((const Entry *) p1)->mFileName, ((const Entry *) p2)->mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003015}
3016
Glenn Kasten46909e72013-02-26 09:20:22 -08003017#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003018void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019{
Eric Laurent81784c32012-11-19 14:55:58 -08003020 NBAIO_Source *teeSource = source.get();
3021 if (teeSource != NULL) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003022 // .wav rotation
3023 // There is a benign race condition if 2 threads call this simultaneously.
3024 // They would both traverse the directory, but the result would simply be
3025 // failures at unlink() which are ignored. It's also unlikely since
3026 // normally dumpsys is only done by bugreport or from the command line.
3027 char teePath[32+256];
Glenn Kasten9a003992016-02-23 15:24:34 -08003028 strcpy(teePath, "/data/misc/audioserver");
Glenn Kastenda6ef132013-01-10 12:31:01 -08003029 size_t teePathLen = strlen(teePath);
3030 DIR *dir = opendir(teePath);
3031 teePath[teePathLen++] = '/';
3032 if (dir != NULL) {
Glenn Kasten2f55e762015-03-05 16:05:08 -08003033#define TEE_MAX_SORT 20 // number of entries to sort
3034#define TEE_MAX_KEEP 10 // number of entries to keep
3035 struct Entry entries[TEE_MAX_SORT];
Glenn Kastenda6ef132013-01-10 12:31:01 -08003036 size_t entryCount = 0;
Glenn Kasten2f55e762015-03-05 16:05:08 -08003037 while (entryCount < TEE_MAX_SORT) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003038 struct dirent de;
3039 struct dirent *result = NULL;
3040 int rc = readdir_r(dir, &de, &result);
3041 if (rc != 0) {
3042 ALOGW("readdir_r failed %d", rc);
3043 break;
3044 }
3045 if (result == NULL) {
3046 break;
3047 }
3048 if (result != &de) {
3049 ALOGW("readdir_r returned unexpected result %p != %p", result, &de);
3050 break;
3051 }
3052 // ignore non .wav file entries
3053 size_t nameLen = strlen(de.d_name);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003054 if (nameLen <= 4 || nameLen >= TEE_MAX_FILENAME ||
Glenn Kastenda6ef132013-01-10 12:31:01 -08003055 strcmp(&de.d_name[nameLen - 4], ".wav")) {
3056 continue;
3057 }
Glenn Kasten2f55e762015-03-05 16:05:08 -08003058 strcpy(entries[entryCount++].mFileName, de.d_name);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003059 }
3060 (void) closedir(dir);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003061 if (entryCount > TEE_MAX_KEEP) {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003062 qsort(entries, entryCount, sizeof(Entry), comparEntry);
Glenn Kasten2f55e762015-03-05 16:05:08 -08003063 for (size_t i = 0; i < entryCount - TEE_MAX_KEEP; ++i) {
3064 strcpy(&teePath[teePathLen], entries[i].mFileName);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003065 (void) unlink(teePath);
3066 }
3067 }
3068 } else {
3069 if (fd >= 0) {
Glenn Kastenfbd87e82016-07-18 15:45:56 -07003070 dprintf(fd, "unable to rotate tees in %.*s: %s\n", (int) teePathLen, teePath,
Glenn Kasten9a003992016-02-23 15:24:34 -08003071 strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003072 }
3073 }
Eric Laurent81784c32012-11-19 14:55:58 -08003074 char teeTime[16];
3075 struct timeval tv;
3076 gettimeofday(&tv, NULL);
3077 struct tm tm;
3078 localtime_r(&tv.tv_sec, &tm);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003079 strftime(teeTime, sizeof(teeTime), "%Y%m%d%H%M%S", &tm);
3080 snprintf(&teePath[teePathLen], sizeof(teePath) - teePathLen, "%s_%d.wav", teeTime, id);
3081 // if 2 dumpsys are done within 1 second, and rotation didn't work, then discard 2nd
3082 int teeFd = open(teePath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, S_IRUSR | S_IWUSR);
Eric Laurent81784c32012-11-19 14:55:58 -08003083 if (teeFd >= 0) {
Glenn Kasten329f6512014-08-28 16:23:16 -07003084 // FIXME use libsndfile
Eric Laurent81784c32012-11-19 14:55:58 -08003085 char wavHeader[44];
3086 memcpy(wavHeader,
3087 "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",
3088 sizeof(wavHeader));
3089 NBAIO_Format format = teeSource->format();
3090 unsigned channelCount = Format_channelCount(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003091 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kasten329f6512014-08-28 16:23:16 -07003092 size_t frameSize = Format_frameSize(format);
Eric Laurent81784c32012-11-19 14:55:58 -08003093 wavHeader[22] = channelCount; // number of channels
3094 wavHeader[24] = sampleRate; // sample rate
3095 wavHeader[25] = sampleRate >> 8;
Glenn Kasten329f6512014-08-28 16:23:16 -07003096 wavHeader[32] = frameSize; // block alignment
3097 wavHeader[33] = frameSize >> 8;
Eric Laurent81784c32012-11-19 14:55:58 -08003098 write(teeFd, wavHeader, sizeof(wavHeader));
3099 size_t total = 0;
3100 bool firstRead = true;
Glenn Kasten329f6512014-08-28 16:23:16 -07003101#define TEE_SINK_READ 1024 // frames per I/O operation
3102 void *buffer = malloc(TEE_SINK_READ * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003103 for (;;) {
Eric Laurent81784c32012-11-19 14:55:58 -08003104 size_t count = TEE_SINK_READ;
Glenn Kastend79072e2016-01-06 08:41:20 -08003105 ssize_t actual = teeSource->read(buffer, count);
Eric Laurent81784c32012-11-19 14:55:58 -08003106 bool wasFirstRead = firstRead;
3107 firstRead = false;
3108 if (actual <= 0) {
3109 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3110 continue;
Eric Laurent59255e42011-07-27 19:49:51 -07003111 }
Eric Laurent81784c32012-11-19 14:55:58 -08003112 break;
Eric Laurent59255e42011-07-27 19:49:51 -07003113 }
Eric Laurent81784c32012-11-19 14:55:58 -08003114 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kasten329f6512014-08-28 16:23:16 -07003115 write(teeFd, buffer, actual * frameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003116 total += actual;
Eric Laurent59255e42011-07-27 19:49:51 -07003117 }
Glenn Kasten329f6512014-08-28 16:23:16 -07003118 free(buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003119 lseek(teeFd, (off_t) 4, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003120 uint32_t temp = 44 + total * frameSize - 8;
3121 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003122 write(teeFd, &temp, sizeof(temp));
3123 lseek(teeFd, (off_t) 40, SEEK_SET);
Glenn Kasten329f6512014-08-28 16:23:16 -07003124 temp = total * frameSize;
3125 // FIXME not big-endian safe
Eric Laurent81784c32012-11-19 14:55:58 -08003126 write(teeFd, &temp, sizeof(temp));
3127 close(teeFd);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003128 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003129 dprintf(fd, "tee copied to %s\n", teePath);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003130 }
Eric Laurent59255e42011-07-27 19:49:51 -07003131 } else {
Glenn Kastenda6ef132013-01-10 12:31:01 -08003132 if (fd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -07003133 dprintf(fd, "unable to create tee %s: %s\n", teePath, strerror(errno));
Glenn Kastenda6ef132013-01-10 12:31:01 -08003134 }
Eric Laurent59255e42011-07-27 19:49:51 -07003135 }
3136 }
3137}
Glenn Kasten46909e72013-02-26 09:20:22 -08003138#endif
Eric Laurent59255e42011-07-27 19:49:51 -07003139
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140// ----------------------------------------------------------------------------
3141
3142status_t AudioFlinger::onTransact(
3143 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3144{
3145 return BnAudioFlinger::onTransact(code, data, reply, flags);
3146}
3147
Glenn Kasten63238ef2015-03-02 15:50:29 -08003148} // namespace android