blob: bc990993d28252be3dec991a88805a50c3d75d9b [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>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <sys/time.h>
28#include <sys/resource.h>
29
jiabin57303cc2018-12-18 15:45:57 -080030#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080031#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <binder/IServiceManager.h>
33#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070034#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070036#include <media/audiohal/DeviceHalInterface.h>
37#include <media/audiohal/DevicesFactoryHalInterface.h>
38#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070039#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070040#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070041#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <utils/String16.h>
43#include <utils/threads.h>
44
Steven Morelandf0c02ce2018-02-23 14:53:55 -080045#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/properties.h>
47
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070051#include "NBAIO_Tee.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>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070068#include <mediautils/ServiceUtilities.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
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080074#include "TypedLogger.h"
75
Mathias Agopian65ab4712010-07-14 17:59:35 -070076// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070077
John Grossman1c345192012-03-27 14:00:17 -070078// Note: the following macro is used for extremely verbose logging message. In
79// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
80// 0; but one side effect of this is to turn all LOGV's as well. Some messages
81// are so verbose that we want to suppress them even when we have ALOG_ASSERT
82// turned on. Do not uncomment the #def below unless you really know what you
83// are doing and want to see all of the extremely verbose messages.
84//#define VERY_VERY_VERBOSE_LOGGING
85#ifdef VERY_VERY_VERBOSE_LOGGING
86#define ALOGVV ALOGV
87#else
88#define ALOGVV(a...) do { } while(0)
89#endif
Eric Laurentde070132010-07-13 04:45:46 -070090
Mathias Agopian65ab4712010-07-14 17:59:35 -070091namespace android {
92
Glenn Kastenec1d6b52011-12-12 09:04:45 -080093static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
94static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -070095static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -070096static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
Glenn Kasten58912562012-04-03 10:45:00 -070098
John Grossman4ff14ba2012-02-08 16:37:41 -080099nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700102
Eric Laurent813e2a72013-08-31 12:59:48 -0700103// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
104// we define a minimum time during which a global effect is considered enabled.
105static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
106
Eric Laurentfc235202016-12-20 18:48:17 -0800107Mutex gLock;
108wp<AudioFlinger> gAudioFlinger;
109
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700110// Keep a strong reference to media.log service around forever.
111// The service is within our parent process so it can never die in a way that we could observe.
112// These two variables are const after initialization.
113static sp<IBinder> sMediaLogServiceAsBinder;
114static sp<IMediaLogService> sMediaLogService;
115
116static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
117
118static void sMediaLogInit()
119{
120 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
121 if (sMediaLogServiceAsBinder != 0) {
122 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
123 }
124}
125
jiabin57303cc2018-12-18 15:45:57 -0800126// Keep a strong reference to external vibrator service
127static sp<os::IExternalVibratorService> sExternalVibratorService;
128
129static sp<os::IExternalVibratorService> getExternalVibratorService() {
130 if (sExternalVibratorService == 0) {
131 sp <IBinder> binder = defaultServiceManager()->getService(
132 String16("external_vibrator_service"));
133 if (binder != 0) {
134 sExternalVibratorService =
135 interface_cast<os::IExternalVibratorService>(binder);
136 }
137 }
138 return sExternalVibratorService;
139}
140
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141// ----------------------------------------------------------------------------
142
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700143std::string formatToString(audio_format_t format) {
144 std::string result;
145 FormatConverter::toString(format, result);
146 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800147}
148
Mathias Agopian65ab4712010-07-14 17:59:35 -0700149// ----------------------------------------------------------------------------
150
151AudioFlinger::AudioFlinger()
152 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800153 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800154 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800155 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700156 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800157 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800158 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700159 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800160 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700161 mBtNrecIsOff(false),
162 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700163 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800164 mTotalMemory(0),
165 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700166 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700167 mPatchPanel(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700168 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700170 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
171 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
172 // zero ID has a special meaning, so unavailable
173 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
174 }
175
Glenn Kastenae0cff12016-02-24 13:57:49 -0800176 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800177 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800178 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
179 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700180 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800181 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700182
Wei Jia3f273d12015-11-24 09:06:49 -0800183 // reset battery stats.
184 // if the audio service has crashed, battery stats could be left
185 // in bad state, reset the state upon service start.
186 BatteryNotifier::getInstance().noteResetAudio();
187
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700188 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700189 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
190
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800191 mMediaLogNotifier->run("MediaLogNotifier");
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192}
193
194void AudioFlinger::onFirstRef()
195{
Eric Laurent93575202011-01-18 18:39:02 -0800196 Mutex::Autolock _l(mLock);
197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800199 char val_str[PROPERTY_VALUE_MAX] = { 0 };
200 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
201 uint32_t int_val;
202 if (1 == sscanf(val_str, "%u", &int_val)) {
203 mStandbyTimeInNsecs = milliseconds(int_val);
204 ALOGI("Using %u mSec as standby time.", int_val);
205 } else {
206 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
207 ALOGI("Using default %u mSec as standby time.",
208 (uint32_t)(mStandbyTimeInNsecs / 1000000));
209 }
210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211
Eric Laurenta4c5a552012-03-29 10:12:40 -0700212 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800213
214 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215}
216
217AudioFlinger::~AudioFlinger()
218{
219 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700220 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700221 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222 }
223 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700224 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700225 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700226 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700227
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800228 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
229 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700230 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700232
233 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700234 if (sMediaLogService != 0) {
235 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
236 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
237 mUnregisteredWriters.pop();
238 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700239 }
240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241}
242
Eric Laurentfc235202016-12-20 18:48:17 -0800243//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800244__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800245status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
246 const audio_attributes_t *attr,
247 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700248 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800249 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800250 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800251 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700252 sp<MmapStreamInterface>& interface,
253 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800254{
255 sp<AudioFlinger> af;
256 {
257 Mutex::Autolock _l(gLock);
258 af = gAudioFlinger.promote();
259 }
260 status_t ret = NO_INIT;
261 if (af != 0) {
262 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800263 direction, attr, config, client, deviceId,
264 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800265 }
266 return ret;
267}
268
Eric Laurent6acd1d42017-01-04 14:23:29 -0800269status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
270 const audio_attributes_t *attr,
271 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700272 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800273 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800274 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800275 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700276 sp<MmapStreamInterface>& interface,
277 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800278{
279 status_t ret = initCheck();
280 if (ret != NO_ERROR) {
281 return ret;
282 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800283 audio_session_t actualSessionId = *sessionId;
284 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
285 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
286 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800287 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700288 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
290 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
291 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
292 fullConfig.sample_rate = config->sample_rate;
293 fullConfig.channel_mask = config->channel_mask;
294 fullConfig.format = config->format;
295 ret = AudioSystem::getOutputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800296 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200297 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800298 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800299 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
300 AUDIO_OUTPUT_FLAG_DIRECT),
Eric Laurent2ac76942017-06-22 17:17:09 -0700301 deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800302 } else {
303 ret = AudioSystem::getInputForAttr(attr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800304 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305 client.clientPid,
306 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800307 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800308 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700309 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800310 }
311 if (ret != NO_ERROR) {
312 return ret;
313 }
314
315 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
316 // audio policy manager and we can retrieve it
317 sp<MmapThread> thread = mMmapThreads.valueFor(io);
318 if (thread != 0) {
319 interface = new MmapThreadHandle(thread);
Phil Burk4e1af9f2018-01-03 15:54:35 -0800320 thread->configure(attr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700321 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 *sessionId = actualSessionId;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700324 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700325 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700326 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800327 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700328 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800329 ret = NO_INIT;
330 }
331
332 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
333
Eric Laurentfc235202016-12-20 18:48:17 -0800334 return ret;
335}
336
jiabin57303cc2018-12-18 15:45:57 -0800337/* static */
338int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
339 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
340 if (evs != 0) {
341 int32_t ret;
342 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
343 if (status.isOk()) {
344 return ret;
345 }
346 }
347 return AudioMixer::HAPTIC_SCALE_NONE;
348}
349
350/* static */
351void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
352 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
353 if (evs != 0) {
354 evs->onExternalVibrationStop(*externalVibration);
355 }
356}
357
Eric Laurenta4c5a552012-03-29 10:12:40 -0700358static const char * const audio_interfaces[] = {
359 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
360 AUDIO_HARDWARE_MODULE_ID_A2DP,
361 AUDIO_HARDWARE_MODULE_ID_USB,
362};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700363
Phil Burk062e67a2015-02-11 13:40:50 -0800364AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700365 audio_module_handle_t module,
366 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700367{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700368 // if module is 0, the request comes from an old policy manager and we should load
369 // well known modules
370 if (module == 0) {
371 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700372 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700373 loadHwModule_l(audio_interfaces[i]);
374 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700375 // then try to find a module supporting the requested device.
376 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
377 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700378 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
379 uint32_t supportedDevices;
380 if (dev->getSupportedDevices(&supportedDevices) == OK &&
381 (supportedDevices & devices) == devices) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700382 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700383 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700384 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385 } else {
386 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700387 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
388 if (audioHwDevice != NULL) {
389 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700390 }
391 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700392
Dima Zavin799a70e2011-04-18 16:57:27 -0700393 return NULL;
394}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395
Glenn Kasten0f11b512014-01-31 16:18:54 -0800396void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700397{
398 const size_t SIZE = 256;
399 char buffer[SIZE];
400 String8 result;
401
402 result.append("Clients:\n");
403 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800404 sp<Client> client = mClients.valueAt(i).promote();
405 if (client != 0) {
406 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
407 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408 }
409 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700410
Eric Laurentd1b28d42013-09-18 18:47:13 -0700411 result.append("Notification Clients:\n");
412 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
413 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
414 result.append(buffer);
415 }
416
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700417 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800418 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700419 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
420 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800421 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700422 result.append(buffer);
423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425}
426
427
Glenn Kasten0f11b512014-01-31 16:18:54 -0800428void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429{
430 const size_t SIZE = 256;
431 char buffer[SIZE];
432 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800433 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434
John Grossman4ff14ba2012-02-08 16:37:41 -0800435 snprintf(buffer, SIZE, "Hardware status: %d\n"
436 "Standby Time mSec: %u\n",
437 hardwareStatus,
438 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 result.append(buffer);
440 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441}
442
Glenn Kasten0f11b512014-01-31 16:18:54 -0800443void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444{
445 const size_t SIZE = 256;
446 char buffer[SIZE];
447 String8 result;
448 snprintf(buffer, SIZE, "Permission Denial: "
449 "can't dump AudioFlinger from pid=%d, uid=%d\n",
450 IPCThreadState::self()->getCallingPid(),
451 IPCThreadState::self()->getCallingUid());
452 result.append(buffer);
453 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454}
455
Eric Laurent81784c32012-11-19 14:55:58 -0800456bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457{
458 bool locked = false;
459 for (int i = 0; i < kDumpLockRetries; ++i) {
460 if (mutex.tryLock() == NO_ERROR) {
461 locked = true;
462 break;
463 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800464 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 }
466 return locked;
467}
468
469status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
470{
Glenn Kasten44deb052012-02-05 18:09:08 -0800471 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 dumpPermissionDenial(fd, args);
473 } else {
474 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800475 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 if (!hardwareLocked) {
477 String8 result(kHardwareLockedString);
478 write(fd, result.string(), result.size());
479 } else {
480 mHardwareLock.unlock();
481 }
482
Eric Tan7b651152018-07-13 10:17:19 -0700483 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484
485 // failed to lock - AudioFlinger is probably deadlocked
486 if (!locked) {
487 String8 result(kDeadlockedString);
488 write(fd, result.string(), result.size());
489 }
490
Eric Laurent021cf962014-05-13 10:18:14 -0700491 bool clientLocked = dumpTryLock(mClientLock);
492 if (!clientLocked) {
493 String8 result(kClientLockedString);
494 write(fd, result.string(), result.size());
495 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700496
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700497 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700498 mEffectsFactoryHal->dumpEffects(fd);
499 } else {
500 String8 result(kNoEffectsFactory);
501 write(fd, result.string(), result.size());
502 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700503
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700505 if (clientLocked) {
506 mClientLock.unlock();
507 }
508
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 dumpInternals(fd, args);
510
511 // dump playback threads
512 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
513 mPlaybackThreads.valueAt(i)->dump(fd, args);
514 }
515
516 // dump record threads
517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
518 mRecordThreads.valueAt(i)->dump(fd, args);
519 }
520
Eric Laurent6acd1d42017-01-04 14:23:29 -0800521 // dump mmap threads
522 for (size_t i = 0; i < mMmapThreads.size(); i++) {
523 mMmapThreads.valueAt(i)->dump(fd, args);
524 }
525
Eric Laurentaaa44472014-09-12 17:41:50 -0700526 // dump orphan effect chains
527 if (mOrphanEffectChains.size() != 0) {
528 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
529 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
530 mOrphanEffectChains.valueAt(i)->dump(fd, args);
531 }
532 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700533 // dump all hardware devs
534 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700535 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
536 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700538
Mikhail Naganov201369b2018-05-16 16:52:32 -0700539 mPatchPanel.dump(fd);
540
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700541 // dump external setParameters
542 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
543 dprintf(fd, "\n%s setParameters:\n", name);
544 logger.dump(fd, " " /* prefix */);
545 };
546 dumpLogger(mRejectedSetParameterLog, "Rejected");
547 dumpLogger(mAppSetParameterLog, "App");
548 dumpLogger(mSystemSetParameterLog, "System");
549
Andy Hunga8115dc2018-08-24 15:51:59 -0700550 // dump historical threads in the last 10 seconds
551 const std::string threadLog = mThreadLog.dumpToString(
552 "Historical Thread Log ", 0 /* lines */,
553 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
554 write(fd, threadLog.c_str(), threadLog.size());
555
rago3bd1c872016-09-26 12:58:14 -0700556 BUFLOG_RESET;
557
Glenn Kastend65d73c2012-06-22 17:21:07 -0700558 if (locked) {
559 mLock.unlock();
560 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800561
Andy Hung8946a282018-04-19 20:04:56 -0700562#ifdef TEE_SINK
563 // NBAIO_Tee dump is safe to call outside of AF lock.
564 NBAIO_Tee::dumpAll(fd, "_DUMP");
565#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800566 // append a copy of media.log here by forwarding fd to it, but don't attempt
567 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700568 if (sMediaLogServiceAsBinder != 0) {
569 dprintf(fd, "\nmedia.log:\n");
570 Vector<String16> args;
571 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800572 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700573
574 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700575 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700576 bool unreachableMemory = false;
577 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700578 if (arg == String16("-m")) {
579 dumpMem = true;
580 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700581 unreachableMemory = true;
582 }
583 }
584
Andy Hung07b745e2016-05-23 16:21:07 -0700585 if (dumpMem) {
586 dprintf(fd, "\nDumping memory:\n");
587 std::string s = dumpMemoryAddresses(100 /* limit */);
588 write(fd, s.c_str(), s.size());
589 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700590 if (unreachableMemory) {
591 dprintf(fd, "\nDumping unreachable memory:\n");
592 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700593 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700594 write(fd, s.c_str(), s.size());
595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
597 return NO_ERROR;
598}
599
Eric Laurent021cf962014-05-13 10:18:14 -0700600sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800601{
Eric Laurent021cf962014-05-13 10:18:14 -0700602 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800603 // If pid is already in the mClients wp<> map, then use that entry
604 // (for which promote() is always != 0), otherwise create a new entry and Client.
605 sp<Client> client = mClients.valueFor(pid).promote();
606 if (client == 0) {
607 client = new Client(this, pid);
608 mClients.add(pid, client);
609 }
610
611 return client;
612}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613
Glenn Kasten9e58b552013-01-18 15:09:48 -0800614sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
615{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700616 // If there is no memory allocated for logs, return a dummy writer that does nothing.
617 // Similarly if we can't contact the media.log service, also return a dummy writer.
618 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800619 return new NBLog::Writer();
620 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700621 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
622 // If allocation fails, consult the vector of previously unregistered writers
623 // and garbage-collect one or more them until an allocation succeeds
624 if (shared == 0) {
625 Mutex::Autolock _l(mUnregisteredWritersLock);
626 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
627 {
628 // Pick the oldest stale writer to garbage-collect
629 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
630 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700631 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700632 // Now the media.log remote reference to IMemory is gone. When our last local
633 // reference to IMemory also drops to zero at end of this block,
634 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
635 }
636 // Re-attempt the allocation
637 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
638 if (shared != 0) {
639 goto success;
640 }
641 }
642 // Even after garbage-collecting all old writers, there is still not enough memory,
643 // so return a dummy writer
644 return new NBLog::Writer();
645 }
646success:
Glenn Kasten535e1612016-12-05 12:19:36 -0800647 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->pointer();
648 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
649 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700650 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800651 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800652}
653
654void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
655{
Glenn Kasten685ef092013-02-04 08:15:34 -0800656 if (writer == 0) {
657 return;
658 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800659 sp<IMemory> iMemory(writer->getIMemory());
660 if (iMemory == 0) {
661 return;
662 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700663 // Rather than removing the writer immediately, append it to a queue of old writers to
664 // be garbage-collected later. This allows us to continue to view old logs for a while.
665 Mutex::Autolock _l(mUnregisteredWritersLock);
666 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800667}
668
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669// IAudioFlinger interface
670
Eric Laurent21da6472017-11-09 16:29:26 -0800671sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
672 CreateTrackOutput& output,
673 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700674{
675 sp<PlaybackThread::Track> track;
676 sp<TrackHandle> trackHandle;
677 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800679 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800680 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681
Eric Laurent21da6472017-11-09 16:29:26 -0800682 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700683 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800684 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700685 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800686 ALOGW_IF(clientUid != callingUid,
687 "%s uid %d tried to pass itself off as %d",
688 __FUNCTION__, callingUid, clientUid);
689 clientUid = callingUid;
690 updatePid = true;
691 }
692 pid_t clientPid = input.clientInfo.clientPid;
693 if (updatePid) {
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700694 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800695 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700696 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800697 __func__, callingUid, callingPid, clientPid);
698 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700699 }
700
Eric Laurent21da6472017-11-09 16:29:26 -0800701 audio_session_t sessionId = input.sessionId;
702 if (sessionId == AUDIO_SESSION_ALLOCATE) {
703 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800704 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
705 lStatus = BAD_VALUE;
706 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800707 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800708
Eric Laurent21da6472017-11-09 16:29:26 -0800709 output.sessionId = sessionId;
710 output.outputId = AUDIO_IO_HANDLE_NONE;
711 output.selectedDeviceId = input.selectedDeviceId;
712
713 lStatus = AudioSystem::getOutputForAttr(&input.attr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200714 clientPid, clientUid, &input.config, input.flags,
Eric Laurent21da6472017-11-09 16:29:26 -0800715 &output.selectedDeviceId, &portId);
716
717 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
718 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
719 goto Exit;
720 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800721 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
722 // but if someone uses binder directly they could bypass that and cause us to crash
723 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000724 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725 lStatus = BAD_VALUE;
726 goto Exit;
727 }
728
Glenn Kasten53b5d092014-02-05 10:00:23 -0800729 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800730 if (!audio_is_output_channel(input.config.channel_mask)) {
731 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800732 lStatus = BAD_VALUE;
733 goto Exit;
734 }
735
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700736 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800737 if (!audio_is_valid_format(input.config.format)) {
738 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700739 lStatus = BAD_VALUE;
740 goto Exit;
741 }
742
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 {
744 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800745 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800747 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 lStatus = BAD_VALUE;
749 goto Exit;
750 }
751
Eric Laurent21da6472017-11-09 16:29:26 -0800752 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753
Glenn Kastene848bd92014-03-13 15:00:32 -0700754 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800755 // check if an effect chain with the same session ID is present on another
756 // output thread and move it here.
757 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
758 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
759 if (mPlaybackThreads.keyAt(i) != output.outputId) {
760 uint32_t sessions = t->hasAudioSession(sessionId);
761 if (sessions & ThreadBase::EFFECT_SESSION) {
762 effectThread = t.get();
763 break;
Eric Laurentde070132010-07-13 04:45:46 -0700764 }
765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 }
Eric Laurent21da6472017-11-09 16:29:26 -0800767 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768
Eric Laurent21da6472017-11-09 16:29:26 -0800769 output.sampleRate = input.config.sample_rate;
770 output.frameCount = input.frameCount;
771 output.notificationFrameCount = input.notificationFrameCount;
772 output.flags = input.flags;
773
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700774 track = thread->createTrack_l(client, streamType, input.attr, &output.sampleRate,
775 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800776 &output.frameCount, &output.notificationFrameCount,
777 input.notificationsPerBuffer, input.speed,
778 input.sharedBuffer, sessionId, &output.flags,
779 input.clientInfo.clientTid, clientUid, &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800780 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700781 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700782
Eric Laurent21da6472017-11-09 16:29:26 -0800783 output.afFrameCount = thread->frameCount();
784 output.afSampleRate = thread->sampleRate();
785 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800786 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800787
Eric Laurent39e94f82010-07-28 01:32:47 -0700788 // move effect chain to this output thread if an effect on same session was waiting
789 // for a track to be created
790 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700791 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700792 Mutex::Autolock _dl(thread->mLock);
793 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800794 moveEffectChain_l(sessionId, effectThread, thread, true);
Eric Laurent39e94f82010-07-28 01:32:47 -0700795 }
Eric Laurenta011e352012-03-29 15:51:43 -0700796
797 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700798 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800799 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700800 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700801 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700802 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700803 } else {
804 mPendingSyncEvents[i]->cancel();
805 }
Eric Laurenta011e352012-03-29 15:51:43 -0700806 mPendingSyncEvents.removeAt(i);
807 i--;
808 }
809 }
810 }
Glenn Kastene198c362013-08-13 09:13:36 -0700811
Eric Laurent21da6472017-11-09 16:29:26 -0800812 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
Glenn Kastene198c362013-08-13 09:13:36 -0700814
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700815 if (lStatus != NO_ERROR) {
816 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700817 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700818 // Don't hold mClientLock when releasing the reference on the track as the
819 // destructor will acquire it.
820 {
821 Mutex::Autolock _cl(mClientLock);
822 client.clear();
823 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700825 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 }
827
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700828 // return handle to client
829 trackHandle = new TrackHandle(track);
830
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800832 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700833 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800834 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700835 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return trackHandle;
837}
838
Glenn Kasten2c073da2016-02-26 09:14:08 -0800839uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840{
841 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800842 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800844 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0;
846 }
847 return thread->sampleRate();
848}
849
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800850audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851{
852 Mutex::Autolock _l(mLock);
853 PlaybackThread *thread = checkPlaybackThread_l(output);
854 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000855 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800856 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 }
858 return thread->format();
859}
860
Glenn Kasten2c073da2016-02-26 09:14:08 -0800861size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862{
863 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800864 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800866 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 return 0;
868 }
Glenn Kasten58912562012-04-03 10:45:00 -0700869 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
870 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 return thread->frameCount();
872}
873
Glenn Kasten4a8308b2016-04-18 14:10:01 -0700874size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
875{
876 Mutex::Autolock _l(mLock);
877 ThreadBase *thread = checkThread_l(ioHandle);
878 if (thread == NULL) {
879 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
880 return 0;
881 }
882 return thread->frameCountHAL();
883}
884
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800885uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700886{
887 Mutex::Autolock _l(mLock);
888 PlaybackThread *thread = checkPlaybackThread_l(output);
889 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800890 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 return 0;
892 }
893 return thread->latency();
894}
895
896status_t AudioFlinger::setMasterVolume(float value)
897{
Eric Laurenta1884f92011-08-23 08:25:03 -0700898 status_t ret = initCheck();
899 if (ret != NO_ERROR) {
900 return ret;
901 }
902
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903 // check calling permissions
904 if (!settingsAllowed()) {
905 return PERMISSION_DENIED;
906 }
907
Eric Laurenta4c5a552012-03-29 10:12:40 -0700908 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700909 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700910
John Grossmanee578c02012-07-23 17:05:46 -0700911 // Set master volume in the HALs which support it.
912 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
913 AutoMutex lock(mHardwareLock);
914 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800915
John Grossmanee578c02012-07-23 17:05:46 -0700916 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
917 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700918 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -0800919 }
John Grossmanee578c02012-07-23 17:05:46 -0700920 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922
John Grossmanee578c02012-07-23 17:05:46 -0700923 // Now set the master volume in each playback thread. Playback threads
924 // assigned to HALs which do not have master volume support will apply
925 // master volume during the mix operation. Threads with HALs which do
926 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -0700927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
929 continue;
930 }
John Grossmanee578c02012-07-23 17:05:46 -0700931 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -0700932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933
934 return NO_ERROR;
935}
936
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100937status_t AudioFlinger::setMasterBalance(float balance)
938{
939 status_t ret = initCheck();
940 if (ret != NO_ERROR) {
941 return ret;
942 }
943
944 // check calling permissions
945 if (!settingsAllowed()) {
946 return PERMISSION_DENIED;
947 }
948
949 // check range
950 if (isnan(balance) || fabs(balance) > 1.f) {
951 return BAD_VALUE;
952 }
953
954 Mutex::Autolock _l(mLock);
955
956 // short cut.
957 if (mMasterBalance == balance) return NO_ERROR;
958
959 mMasterBalance = balance;
960
961 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
962 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
963 continue;
964 }
965 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
966 }
967
968 return NO_ERROR;
969}
970
Glenn Kastenf78aee72012-01-04 11:00:47 -0800971status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972{
Eric Laurenta1884f92011-08-23 08:25:03 -0700973 status_t ret = initCheck();
974 if (ret != NO_ERROR) {
975 return ret;
976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977
978 // check calling permissions
979 if (!settingsAllowed()) {
980 return PERMISSION_DENIED;
981 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800982 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000983 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 return BAD_VALUE;
985 }
986
987 { // scope for the lock
988 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700989 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700991 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992 mHardwareStatus = AUDIO_HW_IDLE;
993 }
994
995 if (NO_ERROR == ret) {
996 Mutex::Autolock _l(mLock);
997 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800998 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700999 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 }
1001
1002 return ret;
1003}
1004
1005status_t AudioFlinger::setMicMute(bool state)
1006{
Eric Laurenta1884f92011-08-23 08:25:03 -07001007 status_t ret = initCheck();
1008 if (ret != NO_ERROR) {
1009 return ret;
1010 }
1011
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012 // check calling permissions
1013 if (!settingsAllowed()) {
1014 return PERMISSION_DENIED;
1015 }
1016
1017 AutoMutex lock(mHardwareLock);
1018 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001019 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001020 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1021 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001022 if (result != NO_ERROR) {
1023 ret = result;
1024 }
1025 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 mHardwareStatus = AUDIO_HW_IDLE;
1027 return ret;
1028}
1029
1030bool AudioFlinger::getMicMute() const
1031{
Eric Laurenta1884f92011-08-23 08:25:03 -07001032 status_t ret = initCheck();
1033 if (ret != NO_ERROR) {
1034 return false;
1035 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001036 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001037 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001038 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001040 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001041 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1042 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001043 if (result == NO_ERROR) {
1044 mute = mute && state;
1045 }
1046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001048
1049 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050}
1051
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001052void AudioFlinger::setRecordSilenced(uid_t uid, bool silenced)
1053{
1054 ALOGV("AudioFlinger::setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
1055
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001056 AutoMutex lock(mLock);
1057 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent331679c2018-04-16 17:03:16 -07001058 mRecordThreads[i]->setRecordSilenced(uid, silenced);
1059 }
1060 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1061 mMmapThreads[i]->setRecordSilenced(uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001062 }
1063}
1064
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065status_t AudioFlinger::setMasterMute(bool muted)
1066{
John Grossmand8f178d2012-07-20 14:51:35 -07001067 status_t ret = initCheck();
1068 if (ret != NO_ERROR) {
1069 return ret;
1070 }
1071
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 // check calling permissions
1073 if (!settingsAllowed()) {
1074 return PERMISSION_DENIED;
1075 }
1076
John Grossmanee578c02012-07-23 17:05:46 -07001077 Mutex::Autolock _l(mLock);
1078 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001079
John Grossmanee578c02012-07-23 17:05:46 -07001080 // Set master mute in the HALs which support it.
1081 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1082 AutoMutex lock(mHardwareLock);
1083 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001084
John Grossmanee578c02012-07-23 17:05:46 -07001085 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1086 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001087 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001088 }
John Grossmanee578c02012-07-23 17:05:46 -07001089 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001090 }
1091
John Grossmanee578c02012-07-23 17:05:46 -07001092 // Now set the master mute in each playback thread. Playback threads
1093 // assigned to HALs which do not have master mute support will apply master
1094 // mute during the mix operation. Threads with HALs which do support master
1095 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001096 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1097 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1098 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100
1101 return NO_ERROR;
1102}
1103
1104float AudioFlinger::masterVolume() const
1105{
Glenn Kasten98067102011-12-13 11:47:54 -08001106 Mutex::Autolock _l(mLock);
1107 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108}
1109
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001110status_t AudioFlinger::getMasterBalance(float *balance) const
1111{
1112 Mutex::Autolock _l(mLock);
1113 *balance = getMasterBalance_l();
1114 return NO_ERROR; // if called through binder, may return a transactional error
1115}
1116
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117bool AudioFlinger::masterMute() const
1118{
Glenn Kasten98067102011-12-13 11:47:54 -08001119 Mutex::Autolock _l(mLock);
1120 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121}
1122
John Grossman4ff14ba2012-02-08 16:37:41 -08001123float AudioFlinger::masterVolume_l() const
1124{
John Grossman4ff14ba2012-02-08 16:37:41 -08001125 return mMasterVolume;
1126}
1127
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001128float AudioFlinger::getMasterBalance_l() const
1129{
1130 return mMasterBalance;
1131}
1132
John Grossmand8f178d2012-07-20 14:51:35 -07001133bool AudioFlinger::masterMute_l() const
1134{
John Grossmanee578c02012-07-23 17:05:46 -07001135 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001136}
1137
Eric Laurent223fd5c2014-11-11 13:43:36 -08001138status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1139{
1140 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001141 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001142 return BAD_VALUE;
1143 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001144 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1145 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1146 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001147 return PERMISSION_DENIED;
1148 }
1149
1150 return NO_ERROR;
1151}
1152
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001153status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1154 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155{
1156 // check calling permissions
1157 if (!settingsAllowed()) {
1158 return PERMISSION_DENIED;
1159 }
1160
Eric Laurent223fd5c2014-11-11 13:43:36 -08001161 status_t status = checkStreamType(stream);
1162 if (status != NO_ERROR) {
1163 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164 }
Eric Laurent98e38192018-02-15 18:31:53 -08001165 if (output == AUDIO_IO_HANDLE_NONE) {
1166 return BAD_VALUE;
1167 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001168 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to change AUDIO_STREAM_PATCH volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169
1170 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001171 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1172 if (volumeInterface == NULL) {
1173 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 }
Eric Laurent98e38192018-02-15 18:31:53 -08001175 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176
1177 return NO_ERROR;
1178}
1179
Glenn Kastenfff6d712012-01-12 16:38:12 -08001180status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181{
1182 // check calling permissions
1183 if (!settingsAllowed()) {
1184 return PERMISSION_DENIED;
1185 }
1186
Eric Laurent223fd5c2014-11-11 13:43:36 -08001187 status_t status = checkStreamType(stream);
1188 if (status != NO_ERROR) {
1189 return status;
1190 }
1191 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1192
1193 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001194 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 return BAD_VALUE;
1196 }
1197
Eric Laurent93575202011-01-18 18:39:02 -08001198 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001200 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1201 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1202 volumeInterfaces[i]->setStreamMute(stream, muted);
1203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204
1205 return NO_ERROR;
1206}
1207
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001208float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001210 status_t status = checkStreamType(stream);
1211 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001212 return 0.0f;
1213 }
Eric Laurent98e38192018-02-15 18:31:53 -08001214 if (output == AUDIO_IO_HANDLE_NONE) {
1215 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 }
1217
Eric Laurent98e38192018-02-15 18:31:53 -08001218 AutoMutex lock(mLock);
1219 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1220 if (volumeInterface == NULL) {
1221 return 0.0f;
1222 }
1223
1224 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225}
1226
Glenn Kastenfff6d712012-01-12 16:38:12 -08001227bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001229 status_t status = checkStreamType(stream);
1230 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 return true;
1232 }
1233
Glenn Kasten6637baa2012-01-09 09:40:36 -08001234 AutoMutex lock(mLock);
1235 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236}
1237
Eric Laurent054d9d32015-04-24 08:48:48 -07001238
1239void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1240{
1241 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1242 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1243 }
1244}
1245
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001246// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1247void AudioFlinger::forwardParametersToDownstreamPatches_l(
1248 audio_io_handle_t upStream, const String8& keyValuePairs,
1249 std::function<bool(const sp<PlaybackThread>&)> useThread)
1250{
1251 std::vector<PatchPanel::SoftwarePatch> swPatches;
1252 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1253 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1254 __func__, swPatches.size(), upStream);
1255 for (const auto& swPatch : swPatches) {
1256 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1257 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1258 downStream->setParameters(keyValuePairs);
1259 }
1260 }
1261}
1262
Eric Laurentf1047e82018-04-16 19:18:20 -07001263// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1264// Some keys are used for audio routing and audio path configuration and should be reserved for use
1265// by audio policy and audio flinger for functional, privacy and security reasons.
1266void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1267{
1268 static const String8 kReservedParameters[] = {
1269 String8(AudioParameter::keyRouting),
1270 String8(AudioParameter::keySamplingRate),
1271 String8(AudioParameter::keyFormat),
1272 String8(AudioParameter::keyChannels),
1273 String8(AudioParameter::keyFrameCount),
1274 String8(AudioParameter::keyInputSource),
1275 String8(AudioParameter::keyMonoOutput),
1276 String8(AudioParameter::keyStreamConnect),
1277 String8(AudioParameter::keyStreamDisconnect),
1278 String8(AudioParameter::keyStreamSupportedFormats),
1279 String8(AudioParameter::keyStreamSupportedChannels),
1280 String8(AudioParameter::keyStreamSupportedSamplingRates),
1281 };
1282
Andy Hung4ef19fa2018-05-15 19:35:29 -07001283 if (isAudioServerUid(callingUid)) {
1284 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001285 }
1286
1287 AudioParameter param = AudioParameter(keyValuePairs);
1288 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001289 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001290 for (auto& key : kReservedParameters) {
1291 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001292 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001293 param.remove(key);
1294 }
1295 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001296 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1297 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001298 keyValuePairs = param.toString();
1299}
1300
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001301void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1302 size_t rejectedKVPSize, const String8& rejectedKVPs,
1303 uid_t callingUid) {
1304 auto prefix = String8::format("UID %5d", callingUid);
1305 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1306 if (rejectedKVPSize != 0) {
1307 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1308 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1309 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1310 } else {
1311 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1312 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1313 }
1314}
1315
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001316status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317{
Eric Laurentf1047e82018-04-16 19:18:20 -07001318 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1319 ioHandle, keyValuePairs.string(),
1320 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001321
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 // check calling permissions
1323 if (!settingsAllowed()) {
1324 return PERMISSION_DENIED;
1325 }
1326
Eric Laurentf1047e82018-04-16 19:18:20 -07001327 String8 filteredKeyValuePairs = keyValuePairs;
1328 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1329
1330 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1331
Glenn Kasten142f5192014-03-25 17:44:59 -07001332 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1333 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001334 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001335 // result will remain NO_INIT if no audio device is present
1336 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001337 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001338 AutoMutex lock(mHardwareLock);
1339 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1340 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001341 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001342 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001343 // return success if at least one audio device accepts the parameters as not all
1344 // HALs are requested to support all parameters. If no audio device supports the
1345 // requested parameters, the last error is reported.
1346 if (final_result != NO_ERROR) {
1347 final_result = result;
1348 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001349 }
1350 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001351 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001352 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001353 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001354 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001355 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1356 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001357 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001358 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001359 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001360 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001361 }
1362 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001363 String8 screenState;
1364 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001365 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001366 if (isOff != (AudioFlinger::mScreenState & 1)) {
1367 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001368 }
1369 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001370 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371 }
1372
1373 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1374 // and the thread is exited once the lock is released
1375 sp<ThreadBase> thread;
1376 {
1377 Mutex::Autolock _l(mLock);
1378 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001379 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001381 if (thread == 0) {
1382 thread = checkMmapThread_l(ioHandle);
1383 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001384 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001385 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001386 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001387 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001388 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1389 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001390 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 }
1393 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001394 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001395 status_t result = thread->setParameters(filteredKeyValuePairs);
1396 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1397 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398 }
1399 return BAD_VALUE;
1400}
1401
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001402String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001404 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1405 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406
Eric Laurenta4c5a552012-03-29 10:12:40 -07001407 Mutex::Autolock _l(mLock);
1408
Glenn Kasten142f5192014-03-25 17:44:59 -07001409 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001410 String8 out_s8;
1411
Dima Zavin799a70e2011-04-18 16:57:27 -07001412 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001413 String8 s;
1414 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001415 {
1416 AutoMutex lock(mHardwareLock);
1417 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001418 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1419 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001420 mHardwareStatus = AUDIO_HW_IDLE;
1421 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001422 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001423 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001424 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425 }
1426
Eric Laurent6acd1d42017-01-04 14:23:29 -08001427 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1428 if (thread == NULL) {
1429 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1430 if (thread == NULL) {
1431 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1432 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001433 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001434 }
1435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001437 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001438}
1439
Glenn Kastendd8104c2012-07-02 12:42:44 -07001440size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1441 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442{
Eric Laurenta1884f92011-08-23 08:25:03 -07001443 status_t ret = initCheck();
1444 if (ret != NO_ERROR) {
1445 return 0;
1446 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001447 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001448 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001449 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001450 return 0;
1451 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001452
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001453 AutoMutex lock(mHardwareLock);
1454 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001455 audio_config_t config, proposed;
1456 memset(&proposed, 0, sizeof(proposed));
1457 proposed.sample_rate = sampleRate;
1458 proposed.channel_mask = channelMask;
1459 proposed.format = format;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001460
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001461 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Andy Hung6770c6f2015-04-07 13:43:36 -07001462 size_t frames;
1463 for (;;) {
1464 // Note: config is currently a const parameter for get_input_buffer_size()
1465 // but we use a copy from proposed in case config changes from the call.
1466 config = proposed;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001467 status_t result = dev->getInputBufferSize(&config, &frames);
1468 if (result == OK && frames != 0) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001469 break; // hal success, config is the result
1470 }
1471 // change one parameter of the configuration each iteration to a more "common" value
1472 // to see if the device will support it.
1473 if (proposed.format != AUDIO_FORMAT_PCM_16_BIT) {
1474 proposed.format = AUDIO_FORMAT_PCM_16_BIT;
1475 } else if (proposed.sample_rate != 44100) { // 44.1 is claimed as must in CDD as well as
1476 proposed.sample_rate = 44100; // legacy AudioRecord.java. TODO: Query hw?
1477 } else {
1478 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1479 "format %#x, channelMask 0x%X",
1480 sampleRate, format, channelMask);
1481 break; // retries failed, break out of loop with frames == 0.
1482 }
1483 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001484 mHardwareStatus = AUDIO_HW_IDLE;
Andy Hung6770c6f2015-04-07 13:43:36 -07001485 if (frames > 0 && config.sample_rate != sampleRate) {
1486 frames = destinationFramesPossible(frames, sampleRate, config.sample_rate);
1487 }
1488 return frames; // may be converted to bytes at the Java level.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489}
1490
Glenn Kasten5f972c02014-01-13 09:59:31 -08001491uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 Mutex::Autolock _l(mLock);
1494
1495 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1496 if (recordThread != NULL) {
1497 return recordThread->getInputFramesLost();
1498 }
1499 return 0;
1500}
1501
1502status_t AudioFlinger::setVoiceVolume(float value)
1503{
Eric Laurenta1884f92011-08-23 08:25:03 -07001504 status_t ret = initCheck();
1505 if (ret != NO_ERROR) {
1506 return ret;
1507 }
1508
Mathias Agopian65ab4712010-07-14 17:59:35 -07001509 // check calling permissions
1510 if (!settingsAllowed()) {
1511 return PERMISSION_DENIED;
1512 }
1513
1514 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001515 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001516 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001517 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 mHardwareStatus = AUDIO_HW_IDLE;
1519
1520 return ret;
1521}
1522
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001523status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001524 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 Mutex::Autolock _l(mLock);
1527
1528 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1529 if (playbackThread != NULL) {
1530 return playbackThread->getRenderPosition(halFrames, dspFrames);
1531 }
1532
1533 return BAD_VALUE;
1534}
1535
1536void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1537{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001539 if (client == 0) {
1540 return;
1541 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001542 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001543 {
1544 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001545 if (mNotificationClients.indexOfKey(pid) < 0) {
1546 sp<NotificationClient> notificationClient = new NotificationClient(this,
1547 client,
1548 pid);
1549 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550
Eric Laurent021cf962014-05-13 10:18:14 -07001551 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552
Marco Nelissen06b46062014-11-14 07:58:25 -08001553 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001554 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001555 }
1556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557
Eric Laurent021cf962014-05-13 10:18:14 -07001558 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001559 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001560 // the config change is always sent from playback or record threads to avoid deadlock
1561 // with AudioSystem::gLock
1562 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001563 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001566 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001567 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569}
1570
1571void AudioFlinger::removeNotificationClient(pid_t pid)
1572{
1573 Mutex::Autolock _l(mLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001574 {
1575 Mutex::Autolock _cl(mClientLock);
1576 mNotificationClients.removeItem(pid);
1577 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001578
Steve Block3856b092011-10-20 11:56:00 +01001579 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001580 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001581 bool removed = false;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001582 for (size_t i = 0; i < num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001583 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001584 ALOGV(" pid %d @ %zu", ref->mPid, i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001585 if (ref->mPid == pid) {
1586 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001587 mAudioSessionRefs.removeAt(i);
1588 delete ref;
1589 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001590 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001591 } else {
1592 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001593 }
1594 }
1595 if (removed) {
1596 purgeStaleEffects_l();
1597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598}
1599
Eric Laurent73e26b62015-04-27 16:55:58 -07001600void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001601 const sp<AudioIoDescriptor>& ioDesc,
1602 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603{
Eric Laurent021cf962014-05-13 10:18:14 -07001604 Mutex::Autolock _l(mClientLock);
1605 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001607 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1608 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 }
1611}
1612
Eric Laurent021cf962014-05-13 10:18:14 -07001613// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614void AudioFlinger::removeClient_l(pid_t pid)
1615{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001616 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001617 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 mClients.removeItem(pid);
1619}
1620
Eric Laurent717e1282012-06-29 16:36:52 -07001621// getEffectThread_l() must be called with AudioFlinger::mLock held
Glenn Kastend848eb42016-03-08 13:42:11 -08001622sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1623 int EffectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001624{
1625 sp<PlaybackThread> thread;
1626
1627 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1628 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1629 ALOG_ASSERT(thread == 0);
1630 thread = mPlaybackThreads.valueAt(i);
1631 }
1632 }
1633
1634 return thread;
1635}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638
1639// ----------------------------------------------------------------------------
1640
1641AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1642 : RefBase(),
1643 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001644 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645{
Andy Hung6f248bb2018-01-23 14:04:37 -08001646 mMemoryDealer = new MemoryDealer(
1647 audioFlinger->getClientSharedHeapSize(),
1648 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649}
1650
Eric Laurent021cf962014-05-13 10:18:14 -07001651// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652AudioFlinger::Client::~Client()
1653{
1654 mAudioFlinger->removeClient_l(mPid);
1655}
1656
Glenn Kasten435dbe62012-01-30 10:15:48 -08001657sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658{
1659 return mMemoryDealer;
1660}
1661
1662// ----------------------------------------------------------------------------
1663
1664AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1665 const sp<IAudioFlingerClient>& client,
1666 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001667 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668{
1669}
1670
1671AudioFlinger::NotificationClient::~NotificationClient()
1672{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673}
1674
Glenn Kasten0f11b512014-01-31 16:18:54 -08001675void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676{
1677 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001678 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679}
1680
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001681// ----------------------------------------------------------------------------
1682AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1683 : mPendingRequests(false) {}
1684
1685
1686void AudioFlinger::MediaLogNotifier::requestMerge() {
1687 AutoMutex _l(mMutex);
1688 mPendingRequests = true;
1689 mCond.signal();
1690}
1691
1692bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001693 // Should already have been checked, but just in case
1694 if (sMediaLogService == 0) {
1695 return false;
1696 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001697 // Wait until there are pending requests
1698 {
1699 AutoMutex _l(mMutex);
1700 mPendingRequests = false; // to ignore past requests
1701 while (!mPendingRequests) {
1702 mCond.wait(mMutex);
1703 // TODO may also need an exitPending check
1704 }
1705 mPendingRequests = false;
1706 }
1707 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001708 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001709 usleep(kPostTriggerSleepPeriod);
1710 return true;
1711}
1712
1713void AudioFlinger::requestLogMerge() {
1714 mMediaLogNotifier->requestMerge();
1715}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716
1717// ----------------------------------------------------------------------------
1718
Eric Laurentf14db3c2017-12-08 14:20:36 -08001719sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1720 CreateRecordOutput& output,
1721 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722{
1723 sp<RecordThread::RecordTrack> recordTrack;
1724 sp<RecordHandle> recordHandle;
1725 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001727 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001728 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729
Eric Laurentf14db3c2017-12-08 14:20:36 -08001730 output.cblk.clear();
1731 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001732 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001733
Eric Laurentf14db3c2017-12-08 14:20:36 -08001734 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001735 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001736 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001737 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001738 ALOGW_IF(clientUid != callingUid,
1739 "%s uid %d tried to pass itself off as %d",
1740 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001741 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001742 updatePid = true;
1743 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001744 pid_t clientPid = input.clientInfo.clientPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001745 if (updatePid) {
1746 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001747 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001748 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001749 __func__, callingUid, callingPid, clientPid);
1750 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001751 }
1752
Andy Hung6770c6f2015-04-07 13:43:36 -07001753 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001754 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1755 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001756 lStatus = BAD_VALUE;
1757 goto Exit;
1758 }
1759
Glenn Kasten53b5d092014-02-05 10:00:23 -08001760 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001761 if (!audio_is_input_channel(input.config.channel_mask)) {
1762 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001763 lStatus = BAD_VALUE;
1764 goto Exit;
1765 }
1766
Eric Laurentf14db3c2017-12-08 14:20:36 -08001767 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1768 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1769 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1770 lStatus = BAD_VALUE;
1771 goto Exit;
1772 }
1773
1774 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001775 output.selectedDeviceId = input.selectedDeviceId;
1776 output.flags = input.flags;
1777
1778 client = registerPid(clientPid);
1779
1780 // Not a conventional loop, but a retry loop for at most two iterations total.
1781 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1782 // Exits loop via break on no error of got exit on error
1783 // The sp<> references will be dropped when re-entering scope.
1784 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1785 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001786 // release previously opened input if retrying.
1787 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1788 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001789 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001790 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001791 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001792 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001793 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001794 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
1795 sessionId,
1796 // FIXME compare to AudioTrack
1797 clientPid,
1798 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001799 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001800 &input.config,
1801 output.flags, &output.selectedDeviceId, &portId);
1802
Glenn Kasten05997e22014-03-13 15:08:33 -07001803 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001805 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 if (thread == NULL) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001807 ALOGE("createRecord() checkRecordThread_l failed");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 lStatus = BAD_VALUE;
1809 goto Exit;
1810 }
1811
Eric Laurentf14db3c2017-12-08 14:20:36 -08001812 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813
Eric Laurentf14db3c2017-12-08 14:20:36 -08001814 output.sampleRate = input.config.sample_rate;
1815 output.frameCount = input.frameCount;
1816 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07001817
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001818 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001819 input.config.format, input.config.channel_mask,
1820 &output.frameCount, sessionId,
1821 &output.notificationFrameCount,
1822 clientUid, &output.flags,
1823 input.clientInfo.clientTid,
1824 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001825 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07001826
Eric Laurentf14db3c2017-12-08 14:20:36 -08001827 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
1828 // audio policy manager without FAST constraint
1829 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001830 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07001831 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001832
1833 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001834 goto Exit;
1835 }
1836
1837 // Check if one effect chain was awaiting for an AudioRecord to be created on this
1838 // session and move it to this thread.
1839 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
1840 if (chain != 0) {
1841 Mutex::Autolock _l(thread->mLock);
1842 thread->addEffectChain_l(chain);
1843 }
1844 break;
1845 }
1846 // End of retry loop.
1847 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 }
Glenn Kastene198c362013-08-13 09:13:36 -07001849
Eric Laurentf14db3c2017-12-08 14:20:36 -08001850 output.cblk = recordTrack->getCblk();
1851 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08001852 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001853
1854 // return handle to client
1855 recordHandle = new RecordHandle(recordTrack);
1856
1857Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001858 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001859 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001860 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001861 // Don't hold mClientLock when releasing the reference on the track as the
1862 // destructor will acquire it.
1863 {
1864 Mutex::Autolock _cl(mClientLock);
1865 client.clear();
1866 }
Eric Laurent896c9672017-12-08 14:08:45 -08001867 recordTrack.clear();
1868 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08001869 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 }
1872
Glenn Kasten9156ef32013-08-06 15:39:08 -07001873 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 return recordHandle;
1875}
1876
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001877
1878
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879// ----------------------------------------------------------------------------
1880
Eric Laurenta4c5a552012-03-29 10:12:40 -07001881audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1882{
Eric Laurent44622db2014-08-01 19:00:33 -07001883 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001884 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07001885 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001886 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07001887 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001888 }
1889 Mutex::Autolock _l(mLock);
1890 return loadHwModule_l(name);
1891}
1892
1893// loadHwModule_l() must be called with AudioFlinger::mLock held
1894audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1895{
1896 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1897 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
1898 ALOGW("loadHwModule() module %s already loaded", name);
1899 return mAudioHwDevs.keyAt(i);
1900 }
1901 }
1902
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001903 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001904
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001905 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001906 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001907 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001908 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001909 }
1910
1911 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001912 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07001913 mHardwareStatus = AUDIO_HW_IDLE;
1914 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001915 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07001916 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001917 }
1918
John Grossmanee578c02012-07-23 17:05:46 -07001919 // Check and cache this HAL's level of support for master mute and master
1920 // volume. If this is the first HAL opened, and it supports the get
1921 // methods, use the initial values provided by the HAL as the current
1922 // master mute and volume settings.
1923
1924 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
1925 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07001926 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001927
1928 if (0 == mAudioHwDevs.size()) {
1929 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001930 float mv;
1931 if (OK == dev->getMasterVolume(&mv)) {
1932 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07001933 }
1934
1935 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001936 bool mm;
1937 if (OK == dev->getMasterMute(&mm)) {
1938 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07001939 }
1940 }
1941
Eric Laurenta4c5a552012-03-29 10:12:40 -07001942 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001943 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07001944 flags = static_cast<AudioHwDevice::Flags>(flags |
1945 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
1946 }
1947
1948 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001949 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07001950 flags = static_cast<AudioHwDevice::Flags>(flags |
1951 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
1952 }
1953
Eric Laurenta4c5a552012-03-29 10:12:40 -07001954 mHardwareStatus = AUDIO_HW_IDLE;
1955 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07001956 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07001957 // An MSD module is inserted before hardware modules in order to mix encoded streams.
1958 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
1959 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001960
Glenn Kastena13cde92016-03-28 15:26:02 -07001961 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07001962 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07001963
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001964 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07001965
1966 return handle;
1967
1968}
1969
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001970// ----------------------------------------------------------------------------
1971
Glenn Kasten3b16c762012-11-14 08:44:39 -08001972uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001973{
1974 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001975 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001976 return thread != NULL ? thread->sampleRate() : 0;
1977}
1978
Glenn Kastene33054e2012-11-14 12:54:39 -08001979size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001980{
1981 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07001982 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07001983 return thread != NULL ? thread->frameCountHAL() : 0;
1984}
1985
1986// ----------------------------------------------------------------------------
1987
Andy Hung6f248bb2018-01-23 14:04:37 -08001988status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001989{
1990 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07001991 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07001992 return PERMISSION_DENIED;
1993 }
1994 Mutex::Autolock _l(mLock);
1995 if (mIsDeviceTypeKnown) {
1996 return INVALID_OPERATION;
1997 }
1998 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08001999 mTotalMemory = totalMemory;
2000 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2001 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2002 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2003 // though actual setting is determined through device configuration.
2004 constexpr int64_t GB = 1024 * 1024 * 1024;
2005 mClientSharedHeapSize =
2006 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2007 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2008 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2009 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2010 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002011 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002012
2013 // TODO: Cache the client shared heap size in a persistent property.
2014 // It's possible that a native process or Java service or app accesses audioserver
2015 // after it is registered by system server, but before AudioService updates
2016 // the memory info. This would occur immediately after boot or an audioserver
2017 // crash and restore. Before update from AudioService, the client would get the
2018 // minimum heap size.
2019
2020 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2021 (isLowRamDevice ? "true" : "false"),
2022 (long long)mTotalMemory,
2023 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002024 return NO_ERROR;
2025}
2026
Andy Hung6f248bb2018-01-23 14:04:37 -08002027size_t AudioFlinger::getClientSharedHeapSize() const
2028{
2029 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2030 if (heapSizeInBytes != 0) { // read-only property overrides all.
2031 return heapSizeInBytes;
2032 }
2033 return mClientSharedHeapSize;
2034}
2035
Mikhail Naganovdea53042018-04-26 13:10:21 -07002036status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2037{
2038 ALOGV(__func__);
2039
2040 audio_module_handle_t module;
2041 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2042 module = config->ext.device.hw_module;
2043 } else {
2044 module = config->ext.mix.hw_module;
2045 }
2046
2047 Mutex::Autolock _l(mLock);
2048 ssize_t index = mAudioHwDevs.indexOfKey(module);
2049 if (index < 0) {
2050 ALOGW("%s() bad hw module %d", __func__, module);
2051 return BAD_VALUE;
2052 }
2053
2054 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2055 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2056}
2057
Eric Laurent93c3d412014-08-01 14:48:35 -07002058audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2059{
2060 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002061
2062 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2063 if (index >= 0) {
2064 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2065 mHwAvSyncIds.valueAt(index), sessionId);
2066 return mHwAvSyncIds.valueAt(index);
2067 }
2068
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002069 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002070 if (dev == NULL) {
2071 return AUDIO_HW_SYNC_INVALID;
2072 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002073 String8 reply;
2074 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002075 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002076 param = AudioParameter(reply);
2077 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002078
2079 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002080 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002081 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2082 return AUDIO_HW_SYNC_INVALID;
2083 }
2084
2085 // allow only one session for a given HW A/V sync ID.
2086 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2087 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2088 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2089 value, mHwAvSyncIds.keyAt(i));
2090 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002091 break;
2092 }
2093 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002094
2095 mHwAvSyncIds.add(sessionId, value);
2096
2097 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2098 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2099 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002100 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002101 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002102 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002103 String8 keyValuePairs = param.toString();
2104 thread->setParameters(keyValuePairs);
2105 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2106 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002107 break;
2108 }
2109 }
2110
2111 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2112 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002113}
2114
Eric Laurent72e3f392015-05-20 14:43:50 -07002115status_t AudioFlinger::systemReady()
2116{
2117 Mutex::Autolock _l(mLock);
2118 ALOGI("%s", __FUNCTION__);
2119 if (mSystemReady) {
2120 ALOGW("%s called twice", __FUNCTION__);
2121 return NO_ERROR;
2122 }
2123 mSystemReady = true;
2124 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2125 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2126 thread->systemReady();
2127 }
2128 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2129 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2130 thread->systemReady();
2131 }
2132 return NO_ERROR;
2133}
2134
jiabin46a76fa2018-01-05 10:18:21 -08002135status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2136{
jiabin9ff780e2018-03-19 18:19:52 -07002137 AutoMutex lock(mHardwareLock);
2138 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2139 status_t status = dev->getMicrophones(microphones);
2140 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002141}
2142
Eric Laurentfa90e842014-10-17 18:12:31 -07002143// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2144void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2145{
2146 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2147 if (index >= 0) {
2148 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2149 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2150 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002151 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002152 String8 keyValuePairs = param.toString();
2153 thread->setParameters(keyValuePairs);
2154 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2155 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002156 }
2157}
2158
2159
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002160// ----------------------------------------------------------------------------
2161
Eric Laurent83b88082014-06-20 18:31:16 -07002162
Eric Laurent6acd1d42017-01-04 14:23:29 -08002163sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002164 audio_io_handle_t *output,
2165 audio_config_t *config,
2166 audio_devices_t devices,
2167 const String8& address,
Eric Laurent83b88082014-06-20 18:31:16 -07002168 audio_output_flags_t flags)
2169{
Eric Laurentcf2c0212014-07-25 16:20:43 -07002170 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
Eric Laurent83b88082014-06-20 18:31:16 -07002171 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002172 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002173 }
2174
Eric Laurentcf2c0212014-07-25 16:20:43 -07002175 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002176 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2177 } else {
2178 // Audio Policy does not currently request a specific output handle.
2179 // If this is ever needed, see openInput_l() for example code.
2180 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2181 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002182 }
Eric Laurent83b88082014-06-20 18:31:16 -07002183
2184 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2185
Eric Laurent83b88082014-06-20 18:31:16 -07002186 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002187 // This if statement allows overriding the audio policy settings
2188 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2189 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2190 // Check only for Normal Mixing mode
2191 if (kEnableExtendedPrecision) {
2192 // Specify format (uncomment one below to choose)
2193 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2194 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2195 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2196 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002197 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002198 }
2199 if (kEnableExtendedChannels) {
2200 // Specify channel mask (uncomment one below to choose)
2201 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2202 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2203 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2204 }
Eric Laurent83b88082014-06-20 18:31:16 -07002205 }
2206
Phil Burk062e67a2015-02-11 13:40:50 -08002207 AudioStreamOut *outputStream = NULL;
2208 status_t status = outHwDev->openOutputStream(
2209 &outputStream,
2210 *output,
2211 devices,
2212 flags,
2213 config,
2214 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002215
2216 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002217
Phil Burk062e67a2015-02-11 13:40:50 -08002218 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002219 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2220 sp<MmapPlaybackThread> thread =
2221 new MmapPlaybackThread(this, *output, outHwDev, outputStream,
2222 devices, AUDIO_DEVICE_NONE, mSystemReady);
2223 mMmapThreads.add(*output, thread);
2224 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2225 *output, thread.get());
2226 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002227 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002228 sp<PlaybackThread> thread;
2229 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2230 thread = new OffloadThread(this, outputStream, *output, devices, mSystemReady);
2231 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2232 *output, thread.get());
2233 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2234 || !isValidPcmSinkFormat(config->format)
2235 || !isValidPcmSinkChannelMask(config->channel_mask)) {
2236 thread = new DirectOutputThread(this, outputStream, *output, devices, mSystemReady);
2237 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2238 *output, thread.get());
2239 } else {
2240 thread = new MixerThread(this, outputStream, *output, devices, mSystemReady);
2241 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2242 *output, thread.get());
2243 }
2244 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002245 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002246 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002247 }
Eric Laurent83b88082014-06-20 18:31:16 -07002248 }
2249
2250 return 0;
2251}
2252
Eric Laurentcf2c0212014-07-25 16:20:43 -07002253status_t AudioFlinger::openOutput(audio_module_handle_t module,
2254 audio_io_handle_t *output,
2255 audio_config_t *config,
2256 audio_devices_t *devices,
2257 const String8& address,
2258 uint32_t *latencyMs,
2259 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002261 ALOGI("openOutput() this %p, module %d Device %#x, SamplingRate %d, Format %#08x, "
2262 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002263 this, module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002264 (devices != NULL) ? *devices : 0,
2265 config->sample_rate,
2266 config->format,
2267 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002268 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269
Yunlian Jiang32ba9862017-01-31 15:55:00 -08002270 if (devices == NULL || *devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002271 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002273
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 Mutex::Autolock _l(mLock);
2275
Eric Laurent6acd1d42017-01-04 14:23:29 -08002276 sp<ThreadBase> thread = openOutput_l(module, output, config, *devices, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002277 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002278 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2279 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2280 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281
Eric Laurent6acd1d42017-01-04 14:23:29 -08002282 // notify client processes of the new output creation
2283 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002284
Eric Laurent6acd1d42017-01-04 14:23:29 -08002285 // the first primary output opened designates the primary hw device
2286 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002287 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002288 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002289
Eric Laurent6acd1d42017-01-04 14:23:29 -08002290 AutoMutex lock(mHardwareLock);
2291 mHardwareStatus = AUDIO_HW_SET_MODE;
2292 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2293 mHardwareStatus = AUDIO_HW_IDLE;
2294 }
2295 } else {
2296 MmapThread *mmapThread = (MmapThread *)thread.get();
2297 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002298 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002299 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 }
2301
Eric Laurentcf2c0212014-07-25 16:20:43 -07002302 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303}
2304
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002305audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2306 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307{
2308 Mutex::Autolock _l(mLock);
2309 MixerThread *thread1 = checkMixerThread_l(output1);
2310 MixerThread *thread2 = checkMixerThread_l(output2);
2311
2312 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002313 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2314 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002315 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 }
2317
Glenn Kasteneeecb982016-02-26 10:44:04 -08002318 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002319 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 thread->addOutputTrack(thread2);
2321 mPlaybackThreads.add(id, thread);
2322 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002323 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 return id;
2325}
2326
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002327status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328{
Glenn Kastend96c5722012-04-25 13:44:49 -07002329 return closeOutput_nonvirtual(output);
2330}
2331
2332status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2333{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 // keep strong reference on the playback thread so that
2335 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002336 sp<PlaybackThread> playbackThread;
2337 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 {
2339 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002340 playbackThread = checkPlaybackThread_l(output);
2341 if (playbackThread != NULL) {
2342 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343
Andy Hungdc099c22018-09-18 13:46:39 -07002344 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002345
Eric Laurent6acd1d42017-01-04 14:23:29 -08002346 if (playbackThread->type() == ThreadBase::MIXER) {
2347 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2348 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2349 DuplicatingThread *dupThread =
2350 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2351 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2352 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 }
2354 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355
2356
Eric Laurent6acd1d42017-01-04 14:23:29 -08002357 mPlaybackThreads.removeItem(output);
2358 // save all effects to the default thread
2359 if (mPlaybackThreads.size()) {
2360 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2361 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002362 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002363 Mutex::Autolock _dl(dstThread->mLock);
2364 Mutex::Autolock _sl(playbackThread->mLock);
2365 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2366 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002367 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
2368 dstThread, true);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 }
2371 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002372 } else {
2373 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2374 if (mmapThread == 0) {
2375 return BAD_VALUE;
2376 }
Andy Hungdc099c22018-09-18 13:46:39 -07002377 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002378 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002379 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002381 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2382 ioDesc->mIoHandle = output;
2383 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002384 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002386 // The thread entity (active unit of execution) is no longer running here,
2387 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388
Eric Laurent6acd1d42017-01-04 14:23:29 -08002389 if (playbackThread != 0) {
2390 playbackThread->exit();
2391 if (!playbackThread->isDuplicating()) {
2392 closeOutputFinish(playbackThread);
2393 }
2394 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002395 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002396 mmapThread->exit();
2397 AudioStreamOut *out = mmapThread->clearOutput();
2398 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2399 // from now on thread->mOutput is NULL
2400 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 }
2402 return NO_ERROR;
2403}
2404
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002405void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002406{
2407 AudioStreamOut *out = thread->clearOutput();
2408 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2409 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002410 delete out;
2411}
2412
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002413void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002414{
2415 mPlaybackThreads.removeItem(thread->mId);
2416 thread->exit();
2417 closeOutputFinish(thread);
2418}
2419
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002420status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421{
2422 Mutex::Autolock _l(mLock);
2423 PlaybackThread *thread = checkPlaybackThread_l(output);
2424
2425 if (thread == NULL) {
2426 return BAD_VALUE;
2427 }
2428
Steve Block3856b092011-10-20 11:56:00 +01002429 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 thread->suspend();
2431
2432 return NO_ERROR;
2433}
2434
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002435status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436{
2437 Mutex::Autolock _l(mLock);
2438 PlaybackThread *thread = checkPlaybackThread_l(output);
2439
2440 if (thread == NULL) {
2441 return BAD_VALUE;
2442 }
2443
Steve Block3856b092011-10-20 11:56:00 +01002444 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445
2446 thread->restore();
2447
2448 return NO_ERROR;
2449}
2450
Eric Laurentcf2c0212014-07-25 16:20:43 -07002451status_t AudioFlinger::openInput(audio_module_handle_t module,
2452 audio_io_handle_t *input,
2453 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002454 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002455 const String8& address,
2456 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002457 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458{
Eric Laurent83b88082014-06-20 18:31:16 -07002459 Mutex::Autolock _l(mLock);
2460
Glenn Kastene7d66712015-03-05 13:46:52 -08002461 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002463 }
2464
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002465 sp<ThreadBase> thread = openInput_l(
2466 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002467
2468 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002469 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002470 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002471 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002473 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002474}
Dima Zavin799a70e2011-04-18 16:57:27 -07002475
Eric Laurent6acd1d42017-01-04 14:23:29 -08002476sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002477 audio_io_handle_t *input,
2478 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002479 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002480 const String8& address,
2481 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002482 audio_input_flags_t flags,
2483 audio_devices_t outputDevice,
2484 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002485{
Glenn Kastene7d66712015-03-05 13:46:52 -08002486 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002487 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002488 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002489 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002490 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002491
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07002492 // Some flags are specific to framework and must not leak to the HAL.
2493 flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FRAMEWORK_FLAGS);
2494
Glenn Kasteneeecb982016-02-26 10:44:04 -08002495 // Audio Policy can request a specific handle for hardware hotword.
2496 // The goal here is not to re-open an already opened input.
2497 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002498 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002499 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2500 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2501 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2502 return 0;
2503 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2504 // This should not happen in a transient state with current design.
2505 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2506 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002507 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002508
Eric Laurentcf2c0212014-07-25 16:20:43 -07002509 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002510 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002511 sp<StreamInHalInterface> inStream;
2512 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002513 *input, devices, &halconfig, flags, address.string(), source,
2514 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002515 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2516 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002517 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002518 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002519 halconfig.sample_rate,
2520 halconfig.format,
2521 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002522 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002523 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002524
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002525 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002526 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002527 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002528 audio_is_linear_pcm(config->format) &&
2529 audio_is_linear_pcm(halconfig.format) &&
2530 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002531 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2532 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002533 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002534 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 inStream.clear();
2536 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002537 *input, devices, &halconfig, flags, address.string(), source,
2538 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002539 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 }
2541
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002542 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002543 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002544 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2545 sp<MmapCaptureThread> thread =
2546 new MmapCaptureThread(this, *input,
2547 inHwDev, inputStream,
2548 primaryOutputDevice_l(), devices, mSystemReady);
2549 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002550 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2551 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002552 return thread;
2553 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002554 // Start record thread
2555 // RecordThread requires both input and output device indication to forward to audio
2556 // pre processing modules
2557 sp<RecordThread> thread = new RecordThread(this,
2558 inputStream,
2559 *input,
2560 primaryOutputDevice_l(),
2561 devices,
2562 mSystemReady
Eric Laurent6acd1d42017-01-04 14:23:29 -08002563 );
2564 mRecordThreads.add(*input, thread);
2565 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2566 return thread;
2567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 }
2569
Eric Laurentcf2c0212014-07-25 16:20:43 -07002570 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 return 0;
2572}
2573
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002574status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575{
Glenn Kastend96c5722012-04-25 13:44:49 -07002576 return closeInput_nonvirtual(input);
2577}
2578
2579status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2580{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 // keep strong reference on the record thread so that
2582 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 sp<RecordThread> recordThread;
2584 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 {
2586 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002587 recordThread = checkRecordThread_l(input);
2588 if (recordThread != 0) {
2589 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590
Andy Hungdc099c22018-09-18 13:46:39 -07002591 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002592
Eric Laurent6acd1d42017-01-04 14:23:29 -08002593 // If we still have effect chains, it means that a client still holds a handle
2594 // on at least one effect. We must either move the chain to an existing thread with the
2595 // same session ID or put it aside in case a new record thread is opened for a
2596 // new capture on the same session
2597 sp<EffectChain> chain;
2598 {
2599 Mutex::Autolock _sl(recordThread->mLock);
2600 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2601 // Note: maximum one chain per record thread
2602 if (effectChains.size() != 0) {
2603 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002604 }
2605 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002606 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002607 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002608 // This should only happen in case of overlap between one thread tear down and the
2609 // creation of its replacement
2610 size_t i;
2611 for (i = 0; i < mRecordThreads.size(); i++) {
2612 sp<RecordThread> t = mRecordThreads.valueAt(i);
2613 if (t == recordThread) {
2614 continue;
2615 }
2616 if (t->hasAudioSession(chain->sessionId()) != 0) {
2617 Mutex::Autolock _l(t->mLock);
2618 ALOGV("closeInput() found thread %d for effect session %d",
2619 t->id(), chain->sessionId());
2620 t->addEffectChain_l(chain);
2621 break;
2622 }
2623 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002624 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002625 if (i == mRecordThreads.size()) {
2626 putOrphanEffectChain_l(chain);
2627 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002628 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002629 mRecordThreads.removeItem(input);
2630 } else {
2631 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2632 if (mmapThread == 0) {
2633 return BAD_VALUE;
2634 }
Andy Hungdc099c22018-09-18 13:46:39 -07002635 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002636 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002637 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002638 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2639 ioDesc->mIoHandle = input;
2640 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 }
Eric Laurent83b88082014-06-20 18:31:16 -07002642 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2643 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002644 if (recordThread != 0) {
2645 closeInputFinish(recordThread);
2646 } else if (mmapThread != 0) {
2647 mmapThread->exit();
2648 AudioStreamIn *in = mmapThread->clearInput();
2649 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2650 // from now on thread->mInput is NULL
2651 delete in;
2652 }
Eric Laurent83b88082014-06-20 18:31:16 -07002653 return NO_ERROR;
2654}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002656void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002657{
2658 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002659 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002660 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002661 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002662 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002663}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002665void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002666{
2667 mRecordThreads.removeItem(thread->mId);
2668 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669}
2670
Glenn Kastend2304db2014-02-03 07:40:31 -08002671status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002672{
2673 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002674 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002675
2676 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2677 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002678 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002679 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002680 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2681 mMmapThreads[i]->invalidateTracks(stream);
2682 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 return NO_ERROR;
2684}
2685
2686
Glenn Kasteneeecb982016-02-26 10:44:04 -08002687audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688{
Glenn Kasten9d003132016-04-06 14:38:09 -07002689 // This is a binder API, so a malicious client could pass in a bad parameter.
2690 // Check for that before calling the internal API nextUniqueId().
2691 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2692 ALOGE("newAudioUniqueId invalid use %d", use);
2693 return AUDIO_UNIQUE_ID_ALLOCATE;
2694 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002695 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696}
2697
Glenn Kastend848eb42016-03-08 13:42:11 -08002698void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002699{
2700 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002701 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002702 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002703 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2704 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002705 caller = pid;
2706 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002707
Eric Laurent021cf962014-05-13 10:18:14 -07002708 {
2709 Mutex::Autolock _cl(mClientLock);
2710 // Ignore requests received from processes not known as notification client. The request
2711 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2712 // called from a different pid leaving a stale session reference. Also we don't know how
2713 // to clear this reference if the client process dies.
2714 if (mNotificationClients.indexOfKey(caller) < 0) {
2715 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2716 return;
2717 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002718 }
2719
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002720 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002721 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002722 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002723 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2724 ref->mCnt++;
2725 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002726 return;
2727 }
2728 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002729 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2730 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002731}
2732
Glenn Kastend848eb42016-03-08 13:42:11 -08002733void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002734{
2735 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002736 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002737 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002738 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2739 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002740 caller = pid;
2741 }
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002742 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002743 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002744 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002745 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2746 ref->mCnt--;
2747 ALOGV(" decremented refcount to %d", ref->mCnt);
2748 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002749 mAudioSessionRefs.removeAt(i);
2750 delete ref;
2751 purgeStaleEffects_l();
2752 }
2753 return;
2754 }
2755 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07002756 // If the caller is audioserver it is likely that the session being released was acquired
Eric Laurentd1b28d42013-09-18 18:47:13 -07002757 // on behalf of a process not in notification clients and we ignore the warning.
Andy Hung4ef19fa2018-05-15 19:35:29 -07002758 ALOGW_IF(!isAudioServerUid(callerUid),
2759 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002760}
2761
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002762bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2763{
2764 size_t num = mAudioSessionRefs.size();
2765 for (size_t i = 0; i < num; i++) {
2766 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2767 if (ref->mSessionid == audioSession) {
2768 return true;
2769 }
2770 }
2771 return false;
2772}
2773
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002774void AudioFlinger::purgeStaleEffects_l() {
2775
Steve Block3856b092011-10-20 11:56:00 +01002776 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002777
2778 Vector< sp<EffectChain> > chains;
2779
2780 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2781 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002782 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002783 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2784 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07002785 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
2786 chains.push(ec);
2787 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002788 }
2789 }
2790 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2791 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002792 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002793 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2794 sp<EffectChain> ec = t->mEffectChains[j];
2795 chains.push(ec);
2796 }
2797 }
2798
2799 for (size_t i = 0; i < chains.size(); i++) {
2800 sp<EffectChain> ec = chains[i];
2801 int sessionid = ec->sessionId();
2802 sp<ThreadBase> t = ec->mThread.promote();
2803 if (t == 0) {
2804 continue;
2805 }
2806 size_t numsessionrefs = mAudioSessionRefs.size();
2807 bool found = false;
2808 for (size_t k = 0; k < numsessionrefs; k++) {
2809 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002810 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01002811 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07002812 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002813 found = true;
2814 break;
2815 }
2816 }
2817 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07002818 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002819 // remove all effects from the chain
2820 while (ec->mEffects.size()) {
2821 sp<EffectModule> effect = ec->mEffects[0];
2822 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07002823 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07002824 if (effect->purgeHandles()) {
2825 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002826 }
2827 AudioSystem::unregisterEffect(effect->id());
2828 }
2829 }
2830 }
2831 return;
2832}
2833
Andy Hungdc099c22018-09-18 13:46:39 -07002834// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
2835void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
2836{
2837 audio_utils::FdToString fdToString;
2838 const int fd = fdToString.fd();
2839 if (fd >= 0) {
2840 thread->dump(fd, {} /* args */);
2841 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
2842 }
2843}
2844
Glenn Kasteneeecb982016-02-26 10:44:04 -08002845// checkThread_l() must be called with AudioFlinger::mLock held
2846AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
2847{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002848 ThreadBase *thread = checkMmapThread_l(ioHandle);
2849 if (thread == 0) {
2850 switch (audio_unique_id_get_use(ioHandle)) {
2851 case AUDIO_UNIQUE_ID_USE_OUTPUT:
2852 thread = checkPlaybackThread_l(ioHandle);
2853 break;
2854 case AUDIO_UNIQUE_ID_USE_INPUT:
2855 thread = checkRecordThread_l(ioHandle);
2856 break;
2857 default:
2858 break;
2859 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002860 }
2861 return thread;
2862}
2863
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002865AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866{
Glenn Kastena1117922012-01-26 10:53:32 -08002867 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868}
2869
2870// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002871AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872{
2873 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08002874 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875}
2876
2877// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002878AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879{
Glenn Kastena1117922012-01-26 10:53:32 -08002880 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881}
2882
Eric Laurent6acd1d42017-01-04 14:23:29 -08002883// checkMmapThread_l() must be called with AudioFlinger::mLock held
2884AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
2885{
2886 return mMmapThreads.valueFor(io).get();
2887}
2888
2889
2890// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
2891AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
2892{
Eric Laurent7459b902017-04-19 18:10:41 -07002893 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002894 if (volumeInterface == nullptr) {
2895 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
2896 if (mmapThread != nullptr) {
2897 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002898 MmapPlaybackThread *mmapPlaybackThread =
2899 static_cast<MmapPlaybackThread *>(mmapThread);
2900 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08002901 }
2902 }
2903 }
2904 return volumeInterface;
2905}
2906
2907Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
2908{
2909 Vector <VolumeInterface *> volumeInterfaces;
2910 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07002911 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002912 }
2913 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2914 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07002915 MmapPlaybackThread *mmapPlaybackThread =
2916 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
2917 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002918 }
2919 }
2920 return volumeInterfaces;
2921}
2922
Glenn Kasteneeecb982016-02-26 10:44:04 -08002923audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924{
Glenn Kasten9d003132016-04-06 14:38:09 -07002925 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08002926 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07002927 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
2928 for (int retry = 0; retry < maxRetries; retry++) {
2929 // The cast allows wraparound from max positive to min negative instead of abort
2930 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
2931 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
2932 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
2933 // allow wrap by skipping 0 and -1 for session ids
2934 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
2935 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
2936 return (audio_unique_id_t) (base | use);
2937 }
2938 }
2939 // We have no way of recovering from wraparound
2940 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
2941 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942}
2943
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08002944AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002945{
2946 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2947 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07002948 if(thread->isDuplicating()) {
2949 continue;
2950 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002951 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07002952 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002953 return thread;
2954 }
2955 }
2956 return NULL;
2957}
2958
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002959audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002960{
2961 PlaybackThread *thread = primaryPlaybackThread_l();
2962
2963 if (thread == NULL) {
2964 return 0;
2965 }
2966
Eric Laurentf1c04f92012-08-28 14:26:53 -07002967 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002968}
2969
Glenn Kastena7335632016-06-09 17:09:53 -07002970AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
2971{
2972 size_t minFrameCount = 0;
2973 PlaybackThread *minThread = NULL;
2974 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2975 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
2976 if (!thread->isDuplicating()) {
2977 size_t frameCount = thread->frameCountHAL();
2978 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
2979 (frameCount == minFrameCount && thread->hasFastMixer() &&
2980 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
2981 minFrameCount = frameCount;
2982 minThread = thread;
2983 }
2984 }
2985 }
2986 return minThread;
2987}
2988
Eric Laurenta011e352012-03-29 15:51:43 -07002989sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08002990 audio_session_t triggerSession,
2991 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07002992 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002993 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07002994{
2995 Mutex::Autolock _l(mLock);
2996
2997 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
2998 status_t playStatus = NAME_NOT_FOUND;
2999 status_t recStatus = NAME_NOT_FOUND;
3000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3001 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3002 if (playStatus == NO_ERROR) {
3003 return event;
3004 }
3005 }
3006 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3007 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3008 if (recStatus == NO_ERROR) {
3009 return event;
3010 }
3011 }
3012 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3013 mPendingSyncEvents.add(event);
3014 } else {
3015 ALOGV("createSyncEvent() invalid event %d", event->type());
3016 event.clear();
3017 }
3018 return event;
3019}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003020
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021// ----------------------------------------------------------------------------
3022// Effect management
3023// ----------------------------------------------------------------------------
3024
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003025sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3026 return mEffectsFactoryHal;
3027}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028
Glenn Kastenf587ba52012-01-26 16:25:10 -08003029status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030{
3031 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003032 if (mEffectsFactoryHal.get()) {
3033 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3034 } else {
3035 return -ENODEV;
3036 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037}
3038
Glenn Kastenf587ba52012-01-26 16:25:10 -08003039status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040{
3041 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003042 if (mEffectsFactoryHal.get()) {
3043 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3044 } else {
3045 return -ENODEV;
3046 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047}
3048
Glenn Kasten5e92a782012-01-30 07:40:52 -08003049status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003050 const effect_uuid_t *pTypeUuid,
3051 uint32_t preferredTypeFlag,
3052 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003054 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3055 return BAD_VALUE;
3056 }
3057
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003059
3060 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003061 return -ENODEV;
3062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003064 status_t status = NO_ERROR;
3065 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3066 // If uuid is specified, request effect descriptor from that.
3067 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3068 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3069 // If uuid is not specified, look for an available implementation
3070 // of the required type instead.
3071
3072 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3073 effect_descriptor_t desc;
3074 desc.flags = 0; // prevent compiler warning
3075
3076 uint32_t numEffects = 0;
3077 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3078 if (status < 0) {
3079 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3080 return status;
3081 }
3082
3083 bool found = false;
3084 for (uint32_t i = 0; i < numEffects; i++) {
3085 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3086 if (status < 0) {
3087 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3088 continue;
3089 }
3090 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3091 // If matching type found save effect descriptor.
3092 found = true;
3093 *descriptor = desc;
3094
3095 // If there's no preferred flag or this descriptor matches the preferred
3096 // flag, success! If this descriptor doesn't match the preferred
3097 // flag, continue enumeration in case a better matching version of this
3098 // effect type is available. Note that this means if no effect with a
3099 // correct flag is found, the descriptor returned will correspond to the
3100 // last effect that at least had a matching type uuid (if any).
3101 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3102 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3103 break;
3104 }
3105 }
3106 }
3107
3108 if (!found) {
3109 status = NAME_NOT_FOUND;
3110 ALOGW("getEffectDescriptor(): Effect not found by type.");
3111 }
3112 } else {
3113 status = BAD_VALUE;
3114 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3115 }
3116 return status;
3117}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003119sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 effect_descriptor_t *pDesc,
3121 const sp<IEffectClient>& effectClient,
3122 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003123 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003124 audio_session_t sessionId,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003125 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003126 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 status_t *status,
3128 int *id,
3129 int *enabled)
3130{
3131 status_t lStatus = NO_ERROR;
3132 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134
Eric Laurentb6436272016-12-07 19:24:50 -08003135 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003136 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003137 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3138 ALOGW_IF(pid != -1 && pid != callingPid,
3139 "%s uid %d pid %d tried to pass itself off as pid %d",
3140 __func__, callingUid, callingPid, pid);
3141 pid = callingPid;
3142 }
3143
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003144 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3145 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146
3147 if (pDesc == NULL) {
3148 lStatus = BAD_VALUE;
3149 goto Exit;
3150 }
3151
Eric Laurent84e9a102010-09-23 16:10:16 -07003152 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07003153 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003154 lStatus = PERMISSION_DENIED;
3155 goto Exit;
3156 }
3157
Dima Zavinfce7a472011-04-19 22:30:36 -07003158 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Andy Hung4ef19fa2018-05-15 19:35:29 -07003159 // that can only be created by audio policy manager
3160 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && !isAudioServerUid(callingUid)) {
Eric Laurent84e9a102010-09-23 16:10:16 -07003161 lStatus = PERMISSION_DENIED;
3162 goto Exit;
3163 }
3164
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003165 if (mEffectsFactoryHal == 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003166 lStatus = NO_INIT;
3167 goto Exit;
3168 }
3169
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003171 // Get the full effect descriptor from the uuid/type.
3172 // If the session is the output mix, prefer an auxiliary effect,
3173 // otherwise no preference.
3174 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3175 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3176 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3177 if (lStatus < 0) {
3178 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3179 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 }
3181
3182 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003183 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3185 lStatus = INVALID_OPERATION;
3186 goto Exit;
3187 }
3188
Eric Laurent59255e42011-07-27 19:49:51 -07003189 // check recording permission for visualizer
3190 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003191 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Marco Nelissendcb346b2015-09-09 10:47:29 -07003192 !recordingAllowed(opPackageName, pid, IPCThreadState::self()->getCallingUid())) {
Eric Laurent59255e42011-07-27 19:49:51 -07003193 lStatus = PERMISSION_DENIED;
3194 goto Exit;
3195 }
3196
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003198 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003199 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003200 // if the output returned by getOutputForEffect() is removed before we lock the
3201 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3202 // and we will exit safely
3203 io = AudioSystem::getOutputForEffect(&desc);
3204 ALOGV("createEffect got output %d", io);
3205 }
3206
3207 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208
3209 // If output is not specified try to find a matching audio session ID in one of the
3210 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003211 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3212 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003213 // Note: io is never 0 when creating an effect on an input
Glenn Kasten142f5192014-03-25 17:44:59 -07003214 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurent5baf2af2013-09-12 17:37:00 -07003215 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3216 // output must be specified by AudioPolicyManager when using session
3217 // AUDIO_SESSION_OUTPUT_STAGE
3218 lStatus = BAD_VALUE;
3219 goto Exit;
3220 }
Eric Laurenteb3c3372013-09-25 12:25:29 -07003221 // look for the thread where the specified audio session is present
3222 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3223 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3224 io = mPlaybackThreads.keyAt(i);
3225 break;
3226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003228 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003229 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3230 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3231 io = mRecordThreads.keyAt(i);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003232 break;
3233 }
3234 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003235 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003236 if (io == AUDIO_IO_HANDLE_NONE) {
3237 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3238 if (mMmapThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
3239 io = mMmapThreads.keyAt(i);
3240 break;
3241 }
3242 }
3243 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003244 // If no output thread contains the requested session ID, default to
3245 // first output. The effect chain will be moved to the correct output
3246 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003247 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003248 io = mPlaybackThreads.keyAt(0);
3249 }
Steve Block3856b092011-10-20 11:56:00 +01003250 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003251 }
3252 ThreadBase *thread = checkRecordThread_l(io);
3253 if (thread == NULL) {
3254 thread = checkPlaybackThread_l(io);
3255 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003256 thread = checkMmapThread_l(io);
3257 if (thread == NULL) {
3258 ALOGE("createEffect() unknown output thread");
3259 lStatus = BAD_VALUE;
3260 goto Exit;
3261 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003262 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003263 } else {
3264 // Check if one effect chain was awaiting for an effect to be created on this
3265 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003266 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003267 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003268 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003269 thread->addEffectChain_l(chain);
3270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003272
Eric Laurent021cf962014-05-13 10:18:14 -07003273 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003275 // create effect on selected output thread
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003276 bool pinned = (sessionId > AUDIO_SESSION_OUTPUT_MIX) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003277 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003278 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003279 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003280 // remove local strong reference to Client with mClientLock held
3281 Mutex::Autolock _cl(mClientLock);
3282 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003283 } else {
3284 // handle must be valid here, but check again to be safe.
3285 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 }
3288
haobo101735295ff7b0d2017-03-17 17:44:03 +08003289 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3290 // handle must be cleared outside lock.
3291 handle.clear();
3292 }
3293
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003295 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 return handle;
3297}
3298
Glenn Kastend848eb42016-03-08 13:42:11 -08003299status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003300 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003301{
Steve Block3856b092011-10-20 11:56:00 +01003302 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003303 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003304 Mutex::Autolock _l(mLock);
3305 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003306 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003307 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 }
Eric Laurentde070132010-07-13 04:45:46 -07003309 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3310 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003311 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003312 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 }
Eric Laurentde070132010-07-13 04:45:46 -07003314 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3315 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003316 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003317 return BAD_VALUE;
3318 }
3319
3320 Mutex::Autolock _dl(dstThread->mLock);
3321 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003322 return moveEffectChain_l(sessionId, srcThread, dstThread, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323}
3324
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003325// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003326status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003327 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07003328 AudioFlinger::PlaybackThread *dstThread,
3329 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07003330{
Steve Block3856b092011-10-20 11:56:00 +01003331 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003332 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003333
Eric Laurent59255e42011-07-27 19:49:51 -07003334 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003335 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003336 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003337 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003338 return INVALID_OPERATION;
3339 }
3340
Eric Laurent4c415062016-06-17 16:14:16 -07003341 // Check whether the destination thread and all effects in the chain are compatible
3342 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003343 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003344 " destination thread %p is not compatible with effects in the chain",
3345 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003346 return INVALID_OPERATION;
3347 }
3348
Eric Laurent39e94f82010-07-28 01:32:47 -07003349 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003350 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003351 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003352 // removed.
3353 srcThread->removeEffectChain_l(chain);
3354
3355 // transfer all effects one by one so that new effect chain is created on new thread with
3356 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003357 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003358 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003359 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003360 Vector< sp<EffectModule> > removed;
3361 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003362 while (effect != 0) {
3363 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003364 removed.add(effect);
3365 status = dstThread->addEffect_l(effect);
3366 if (status != NO_ERROR) {
3367 break;
3368 }
Eric Laurentec35a142011-10-05 17:42:25 -07003369 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3370 if (effect->state() == EffectModule::ACTIVE ||
3371 effect->state() == EffectModule::STOPPING) {
3372 effect->start();
3373 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003374 // if the move request is not received from audio policy manager, the effect must be
3375 // re-registered with the new strategy and output
3376 if (dstChain == 0) {
3377 dstChain = effect->chain().promote();
3378 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003379 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003380 status = NO_INIT;
3381 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003382 }
3383 strategy = dstChain->strategy();
3384 }
3385 if (reRegister) {
3386 AudioSystem::unregisterEffect(effect->id());
3387 AudioSystem::registerEffect(&effect->desc(),
Eric Laurent5baf2af2013-09-12 17:37:00 -07003388 dstThread->id(),
Eric Laurent39e94f82010-07-28 01:32:47 -07003389 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07003390 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07003391 effect->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003392 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent39e94f82010-07-28 01:32:47 -07003393 }
Eric Laurentde070132010-07-13 04:45:46 -07003394 effect = chain->getEffectFromId_l(0);
3395 }
3396
Eric Laurent5baf2af2013-09-12 17:37:00 -07003397 if (status != NO_ERROR) {
3398 for (size_t i = 0; i < removed.size(); i++) {
3399 srcThread->addEffect_l(removed[i]);
3400 if (dstChain != 0 && reRegister) {
3401 AudioSystem::unregisterEffect(removed[i]->id());
3402 AudioSystem::registerEffect(&removed[i]->desc(),
3403 srcThread->id(),
3404 strategy,
3405 sessionId,
3406 removed[i]->id());
Eric Laurentd72b7c02013-10-12 16:17:46 -07003407 AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003408 }
3409 }
3410 }
3411
3412 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413}
3414
Eric Laurent5baf2af2013-09-12 17:37:00 -07003415bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003416{
3417 if (mGlobalEffectEnableTime != 0 &&
3418 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3419 return true;
3420 }
3421
3422 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3423 sp<EffectChain> ec =
3424 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003425 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003426 return true;
3427 }
3428 }
3429 return false;
3430}
3431
Eric Laurent5baf2af2013-09-12 17:37:00 -07003432void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003433{
3434 Mutex::Autolock _l(mLock);
3435
3436 mGlobalEffectEnableTime = systemTime();
3437
3438 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3439 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3440 if (t->mType == ThreadBase::OFFLOAD) {
3441 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3442 }
3443 }
3444
3445}
3446
Eric Laurentaaa44472014-09-12 17:41:50 -07003447status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3448{
Eric Laurentd8365c52017-07-16 15:27:05 -07003449 // clear possible suspended state before parking the chain so that it starts in default state
3450 // when attached to a new record thread
3451 chain->setEffectSuspended_l(FX_IID_AEC, false);
3452 chain->setEffectSuspended_l(FX_IID_NS, false);
3453
Glenn Kastend848eb42016-03-08 13:42:11 -08003454 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003455 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003456 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003457 if (index >= 0) {
3458 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3459 return ALREADY_EXISTS;
3460 }
3461 mOrphanEffectChains.add(session, chain);
3462 return NO_ERROR;
3463}
3464
3465sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3466{
3467 sp<EffectChain> chain;
3468 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003469 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003470 if (index >= 0) {
3471 chain = mOrphanEffectChains.valueAt(index);
3472 mOrphanEffectChains.removeItemsAt(index);
3473 }
3474 return chain;
3475}
3476
3477bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3478{
3479 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003480 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003481 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003482 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003483 if (index >= 0) {
3484 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003485 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003486 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003487 mOrphanEffectChains.removeItemsAt(index);
3488 }
3489 return true;
3490 }
3491 return false;
3492}
3493
3494
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495// ----------------------------------------------------------------------------
3496
3497status_t AudioFlinger::onTransact(
3498 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3499{
3500 return BnAudioFlinger::onTransact(code, data, reply, flags);
3501}
3502
Glenn Kasten63238ef2015-03-02 15:50:29 -08003503} // namespace android