blob: ee4c5baf222b0aa3f52864aa1f70ac9c7f6a9536 [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
jiabina392a552019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
32
jiabin57303cc2018-12-18 15:45:57 -080033#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080034#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035#include <binder/IServiceManager.h>
36#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070037#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070039#include <media/audiohal/DeviceHalInterface.h>
40#include <media/audiohal/DevicesFactoryHalInterface.h>
41#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070042#include <media/AudioParameter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070043#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070044#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <utils/String16.h>
46#include <utils/threads.h>
47
Steven Morelandf0c02ce2018-02-23 14:53:55 -080048#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <cutils/properties.h>
50
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070052#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070055#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Andy Hung6770c6f2015-04-07 13:43:36 -070057#include <media/AudioResamplerPublic.h>
58
Mikhail Naganov9fe94012016-10-14 14:57:40 -070059#include <system/audio_effects/effect_visualizer.h>
60#include <system/audio_effects/effect_ns.h>
61#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten9e58b552013-01-18 15:09:48 -080067#include <media/IMediaLogService.h>
Andy Hung07b745e2016-05-23 16:21:07 -070068#include <media/MemoryLeakTrackUtil.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080069#include <media/nbaio/Pipe.h>
70#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080071#include <mediautils/BatteryNotifier.h>
Andy Hungab7ef302018-05-15 19:35:29 -070072#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070073#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070074#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080075
rago3bd1c872016-09-26 12:58:14 -070076//#define BUFLOG_NDEBUG 0
77#include <BufLog.h>
78
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080079#include "TypedLogger.h"
80
Mathias Agopian65ab4712010-07-14 17:59:35 -070081// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
John Grossman1c345192012-03-27 14:00:17 -070083// Note: the following macro is used for extremely verbose logging message. In
84// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
85// 0; but one side effect of this is to turn all LOGV's as well. Some messages
86// are so verbose that we want to suppress them even when we have ALOG_ASSERT
87// turned on. Do not uncomment the #def below unless you really know what you
88// are doing and want to see all of the extremely verbose messages.
89//#define VERY_VERY_VERBOSE_LOGGING
90#ifdef VERY_VERY_VERBOSE_LOGGING
91#define ALOGVV ALOGV
92#else
93#define ALOGVV(a...) do { } while(0)
94#endif
Eric Laurentde070132010-07-13 04:45:46 -070095
Mathias Agopian65ab4712010-07-14 17:59:35 -070096namespace android {
97
Glenn Kastenec1d6b52011-12-12 09:04:45 -080098static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
99static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700100static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700101static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102
Glenn Kasten58912562012-04-03 10:45:00 -0700103
John Grossman4ff14ba2012-02-08 16:37:41 -0800104nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800105
Eric Laurent81784c32012-11-19 14:55:58 -0800106uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700107
Eric Laurent813e2a72013-08-31 12:59:48 -0700108// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
109// we define a minimum time during which a global effect is considered enabled.
110static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
111
Eric Laurentfc235202016-12-20 18:48:17 -0800112Mutex gLock;
113wp<AudioFlinger> gAudioFlinger;
114
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700115// Keep a strong reference to media.log service around forever.
116// The service is within our parent process so it can never die in a way that we could observe.
117// These two variables are const after initialization.
118static sp<IBinder> sMediaLogServiceAsBinder;
119static sp<IMediaLogService> sMediaLogService;
120
121static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
122
123static void sMediaLogInit()
124{
125 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
126 if (sMediaLogServiceAsBinder != 0) {
127 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
128 }
129}
130
jiabin57303cc2018-12-18 15:45:57 -0800131// Keep a strong reference to external vibrator service
132static sp<os::IExternalVibratorService> sExternalVibratorService;
133
134static sp<os::IExternalVibratorService> getExternalVibratorService() {
135 if (sExternalVibratorService == 0) {
136 sp <IBinder> binder = defaultServiceManager()->getService(
137 String16("external_vibrator_service"));
138 if (binder != 0) {
139 sExternalVibratorService =
140 interface_cast<os::IExternalVibratorService>(binder);
141 }
142 }
143 return sExternalVibratorService;
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700148std::string formatToString(audio_format_t format) {
149 std::string result;
150 FormatConverter::toString(format, result);
151 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800152}
153
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154// ----------------------------------------------------------------------------
155
156AudioFlinger::AudioFlinger()
157 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800158 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800159 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800160 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700161 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800162 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800163 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700164 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800165 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700166 mBtNrecIsOff(false),
167 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700168 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800169 mTotalMemory(0),
170 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700171 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700172 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800173 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700174 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700176 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
177 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
178 // zero ID has a special meaning, so unavailable
179 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
180 }
181
Glenn Kastenae0cff12016-02-24 13:57:49 -0800182 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800183 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800184 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
185 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700186 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800187 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700188
Wei Jia3f273d12015-11-24 09:06:49 -0800189 // reset battery stats.
190 // if the audio service has crashed, battery stats could be left
191 // in bad state, reset the state upon service start.
192 BatteryNotifier::getInstance().noteResetAudio();
193
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700194 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700195 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
196
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800197 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700198 std::vector<pid_t> halPids;
199 mDevicesFactoryHal->getHalPids(&halPids);
200 TimeCheck::setAudioHalPids(halPids);
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700201}
202
203void AudioFlinger::onFirstRef()
204{
Eric Laurent93575202011-01-18 18:39:02 -0800205 Mutex::Autolock _l(mLock);
206
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800208 char val_str[PROPERTY_VALUE_MAX] = { 0 };
209 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
210 uint32_t int_val;
211 if (1 == sscanf(val_str, "%u", &int_val)) {
212 mStandbyTimeInNsecs = milliseconds(int_val);
213 ALOGI("Using %u mSec as standby time.", int_val);
214 } else {
215 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
216 ALOGI("Using default %u mSec as standby time.",
217 (uint32_t)(mStandbyTimeInNsecs / 1000000));
218 }
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220
Eric Laurenta4c5a552012-03-29 10:12:40 -0700221 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800222
223 gAudioFlinger = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224}
225
Eric Laurent42896a02019-09-27 15:40:33 -0700226status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
227 TimeCheck::setAudioHalPids(pids);
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
233 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700234 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700235 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700236 }
237 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700238 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700239 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240 }
Andy Hungb4946b62019-03-14 11:19:28 -0700241 while (!mMmapThreads.isEmpty()) {
242 const audio_io_handle_t io = mMmapThreads.keyAt(0);
243 if (mMmapThreads.valueAt(0)->isOutput()) {
244 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
245 } else {
246 closeInput_nonvirtual(io); // removes entry from mMmapThreads
247 }
248 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700249
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700252 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700254
255 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700256 if (sMediaLogService != 0) {
257 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
258 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
259 mUnregisteredWriters.pop();
260 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700261 }
262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263}
264
Eric Laurentfc235202016-12-20 18:48:17 -0800265//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800266__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800267status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
268 const audio_attributes_t *attr,
269 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700270 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800271 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800272 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800273 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700274 sp<MmapStreamInterface>& interface,
275 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800276{
277 sp<AudioFlinger> af;
278 {
279 Mutex::Autolock _l(gLock);
280 af = gAudioFlinger.promote();
281 }
282 status_t ret = NO_INIT;
283 if (af != 0) {
284 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800285 direction, attr, config, client, deviceId,
286 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800287 }
288 return ret;
289}
290
Eric Laurent6acd1d42017-01-04 14:23:29 -0800291status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
292 const audio_attributes_t *attr,
293 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700294 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800295 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800296 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800297 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700298 sp<MmapStreamInterface>& interface,
299 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800300{
301 status_t ret = initCheck();
302 if (ret != NO_ERROR) {
303 return ret;
304 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800305 audio_session_t actualSessionId = *sessionId;
306 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
307 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
308 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800309 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700310 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800311 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700312 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800313 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
314 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
315 fullConfig.sample_rate = config->sample_rate;
316 fullConfig.channel_mask = config->channel_mask;
317 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800318 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700319
320 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800321 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200322 &streamType, client.clientPid, client.clientUid,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800323 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800324 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
325 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800326 deviceId, &portId, &secondaryOutputs);
327 ALOGW_IF(!secondaryOutputs.empty(),
328 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800329 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700330 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700331 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800332 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800333 client.clientPid,
334 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800335 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800336 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700337 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800338 }
339 if (ret != NO_ERROR) {
340 return ret;
341 }
342
343 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
344 // audio policy manager and we can retrieve it
345 sp<MmapThread> thread = mMmapThreads.valueFor(io);
346 if (thread != 0) {
347 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700348 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700349 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800350 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800351 config->sample_rate = thread->sampleRate();
352 config->channel_mask = thread->channelMask();
353 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800354 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700355 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700356 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700357 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800358 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700359 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800360 ret = NO_INIT;
361 }
362
363 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
364
Eric Laurentfc235202016-12-20 18:48:17 -0800365 return ret;
366}
367
jiabin57303cc2018-12-18 15:45:57 -0800368/* static */
369int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
370 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
371 if (evs != 0) {
372 int32_t ret;
373 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
374 if (status.isOk()) {
375 return ret;
376 }
377 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800378 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800379}
380
381/* static */
382void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
383 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
384 if (evs != 0) {
385 evs->onExternalVibrationStop(*externalVibration);
386 }
387}
388
Eric Laurentb82e6b72019-11-22 17:25:04 -0800389status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
390 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
391 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
392 if (audioHwDevice == nullptr) {
393 return NO_INIT;
394 }
395 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
396}
397
398status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
399 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
400 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
401 if (audioHwDevice == nullptr) {
402 return NO_INIT;
403 }
404 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
405}
406
Eric Laurenta4c5a552012-03-29 10:12:40 -0700407static const char * const audio_interfaces[] = {
408 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
409 AUDIO_HARDWARE_MODULE_ID_A2DP,
410 AUDIO_HARDWARE_MODULE_ID_USB,
411};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700412
Phil Burk062e67a2015-02-11 13:40:50 -0800413AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700414 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700415 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700416{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 // if module is 0, the request comes from an old policy manager and we should load
418 // well known modules
419 if (module == 0) {
420 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700421 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700422 loadHwModule_l(audio_interfaces[i]);
423 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700424 // then try to find a module supporting the requested device.
425 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
426 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700427 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
428 uint32_t supportedDevices;
429 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700430 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700431 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700432 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700433 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700434 } else {
435 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700436 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
437 if (audioHwDevice != NULL) {
438 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700439 }
440 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700441
Dima Zavin799a70e2011-04-18 16:57:27 -0700442 return NULL;
443}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444
Glenn Kasten0f11b512014-01-31 16:18:54 -0800445void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 String8 result;
448
449 result.append("Clients:\n");
450 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800451 sp<Client> client = mClients.valueAt(i).promote();
452 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800453 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 }
455 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700456
Eric Laurentd1b28d42013-09-18 18:47:13 -0700457 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800458 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700459 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800460 const pid_t pid = mNotificationClients[i]->getPid();
461 const uid_t uid = mNotificationClients[i]->getUid();
462 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
463 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700464 }
465
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700466 result.append("Global session refs:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800467 result.append(" session cnt pid\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700468 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
469 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung5bdc5352019-12-23 14:36:31 -0800470 result.appendFormat(" %7d %4d %7d\n", r->mSessionid, r->mCnt, r->mPid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700471 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473}
474
475
Glenn Kasten0f11b512014-01-31 16:18:54 -0800476void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477{
478 const size_t SIZE = 256;
479 char buffer[SIZE];
480 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800481 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482
John Grossman4ff14ba2012-02-08 16:37:41 -0800483 snprintf(buffer, SIZE, "Hardware status: %d\n"
484 "Standby Time mSec: %u\n",
485 hardwareStatus,
486 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 result.append(buffer);
488 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489}
490
Glenn Kasten0f11b512014-01-31 16:18:54 -0800491void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700492{
493 const size_t SIZE = 256;
494 char buffer[SIZE];
495 String8 result;
496 snprintf(buffer, SIZE, "Permission Denial: "
497 "can't dump AudioFlinger from pid=%d, uid=%d\n",
498 IPCThreadState::self()->getCallingPid(),
499 IPCThreadState::self()->getCallingUid());
500 result.append(buffer);
501 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502}
503
Eric Laurent81784c32012-11-19 14:55:58 -0800504bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700506 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
507 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508}
509
510status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
511{
Glenn Kasten44deb052012-02-05 18:09:08 -0800512 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700513 dumpPermissionDenial(fd, args);
514 } else {
515 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800516 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517 if (!hardwareLocked) {
518 String8 result(kHardwareLockedString);
519 write(fd, result.string(), result.size());
520 } else {
521 mHardwareLock.unlock();
522 }
523
Eric Tan7b651152018-07-13 10:17:19 -0700524 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525
526 // failed to lock - AudioFlinger is probably deadlocked
527 if (!locked) {
528 String8 result(kDeadlockedString);
529 write(fd, result.string(), result.size());
530 }
531
Eric Laurent021cf962014-05-13 10:18:14 -0700532 bool clientLocked = dumpTryLock(mClientLock);
533 if (!clientLocked) {
534 String8 result(kClientLockedString);
535 write(fd, result.string(), result.size());
536 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700537
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700538 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700539 mEffectsFactoryHal->dumpEffects(fd);
540 } else {
541 String8 result(kNoEffectsFactory);
542 write(fd, result.string(), result.size());
543 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700544
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700546 if (clientLocked) {
547 mClientLock.unlock();
548 }
549
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 dumpInternals(fd, args);
551
552 // dump playback threads
553 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
554 mPlaybackThreads.valueAt(i)->dump(fd, args);
555 }
556
557 // dump record threads
558 for (size_t i = 0; i < mRecordThreads.size(); i++) {
559 mRecordThreads.valueAt(i)->dump(fd, args);
560 }
561
Eric Laurent6acd1d42017-01-04 14:23:29 -0800562 // dump mmap threads
563 for (size_t i = 0; i < mMmapThreads.size(); i++) {
564 mMmapThreads.valueAt(i)->dump(fd, args);
565 }
566
Eric Laurentaaa44472014-09-12 17:41:50 -0700567 // dump orphan effect chains
568 if (mOrphanEffectChains.size() != 0) {
569 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
570 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
571 mOrphanEffectChains.valueAt(i)->dump(fd, args);
572 }
573 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700574 // dump all hardware devs
575 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700576 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
577 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700579
Mikhail Naganov201369b2018-05-16 16:52:32 -0700580 mPatchPanel.dump(fd);
581
Eric Laurentb82e6b72019-11-22 17:25:04 -0800582 mDeviceEffectManager.dump(fd);
583
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700584 // dump external setParameters
585 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
586 dprintf(fd, "\n%s setParameters:\n", name);
587 logger.dump(fd, " " /* prefix */);
588 };
589 dumpLogger(mRejectedSetParameterLog, "Rejected");
590 dumpLogger(mAppSetParameterLog, "App");
591 dumpLogger(mSystemSetParameterLog, "System");
592
Andy Hunga8115dc2018-08-24 15:51:59 -0700593 // dump historical threads in the last 10 seconds
594 const std::string threadLog = mThreadLog.dumpToString(
595 "Historical Thread Log ", 0 /* lines */,
596 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
597 write(fd, threadLog.c_str(), threadLog.size());
598
rago3bd1c872016-09-26 12:58:14 -0700599 BUFLOG_RESET;
600
Glenn Kastend65d73c2012-06-22 17:21:07 -0700601 if (locked) {
602 mLock.unlock();
603 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800604
Andy Hung8946a282018-04-19 20:04:56 -0700605#ifdef TEE_SINK
606 // NBAIO_Tee dump is safe to call outside of AF lock.
607 NBAIO_Tee::dumpAll(fd, "_DUMP");
608#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800609 // append a copy of media.log here by forwarding fd to it, but don't attempt
610 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700611 if (sMediaLogServiceAsBinder != 0) {
612 dprintf(fd, "\nmedia.log:\n");
613 Vector<String16> args;
614 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800615 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700616
617 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700618 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700619 bool unreachableMemory = false;
620 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700621 if (arg == String16("-m")) {
622 dumpMem = true;
623 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700624 unreachableMemory = true;
625 }
626 }
627
Andy Hung07b745e2016-05-23 16:21:07 -0700628 if (dumpMem) {
629 dprintf(fd, "\nDumping memory:\n");
630 std::string s = dumpMemoryAddresses(100 /* limit */);
631 write(fd, s.c_str(), s.size());
632 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700633 if (unreachableMemory) {
634 dprintf(fd, "\nDumping unreachable memory:\n");
635 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700636 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700637 write(fd, s.c_str(), s.size());
638 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639 }
640 return NO_ERROR;
641}
642
Eric Laurent021cf962014-05-13 10:18:14 -0700643sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800644{
Eric Laurent021cf962014-05-13 10:18:14 -0700645 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800646 // If pid is already in the mClients wp<> map, then use that entry
647 // (for which promote() is always != 0), otherwise create a new entry and Client.
648 sp<Client> client = mClients.valueFor(pid).promote();
649 if (client == 0) {
650 client = new Client(this, pid);
651 mClients.add(pid, client);
652 }
653
654 return client;
655}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656
Glenn Kasten9e58b552013-01-18 15:09:48 -0800657sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
658{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700659 // If there is no memory allocated for logs, return a dummy writer that does nothing.
660 // Similarly if we can't contact the media.log service, also return a dummy writer.
661 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800662 return new NBLog::Writer();
663 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700664 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
665 // If allocation fails, consult the vector of previously unregistered writers
666 // and garbage-collect one or more them until an allocation succeeds
667 if (shared == 0) {
668 Mutex::Autolock _l(mUnregisteredWritersLock);
669 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
670 {
671 // Pick the oldest stale writer to garbage-collect
672 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
673 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700674 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700675 // Now the media.log remote reference to IMemory is gone. When our last local
676 // reference to IMemory also drops to zero at end of this block,
677 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
678 }
679 // Re-attempt the allocation
680 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
681 if (shared != 0) {
682 goto success;
683 }
684 }
685 // Even after garbage-collecting all old writers, there is still not enough memory,
686 // so return a dummy writer
687 return new NBLog::Writer();
688 }
689success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700690 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800691 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
692 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700693 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800694 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800695}
696
697void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
698{
Glenn Kasten685ef092013-02-04 08:15:34 -0800699 if (writer == 0) {
700 return;
701 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800702 sp<IMemory> iMemory(writer->getIMemory());
703 if (iMemory == 0) {
704 return;
705 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700706 // Rather than removing the writer immediately, append it to a queue of old writers to
707 // be garbage-collected later. This allows us to continue to view old logs for a while.
708 Mutex::Autolock _l(mUnregisteredWritersLock);
709 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800710}
711
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712// IAudioFlinger interface
713
Eric Laurent21da6472017-11-09 16:29:26 -0800714sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
715 CreateTrackOutput& output,
716 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717{
718 sp<PlaybackThread::Track> track;
719 sp<TrackHandle> trackHandle;
720 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800722 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800723 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800724 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700725
Eric Laurent21da6472017-11-09 16:29:26 -0800726 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700727 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800728 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700729 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
730 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700731 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700732
Andy Hung4ef19fa2018-05-15 19:35:29 -0700733 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800734 ALOGW_IF(clientUid != callingUid,
735 "%s uid %d tried to pass itself off as %d",
736 __FUNCTION__, callingUid, clientUid);
737 clientUid = callingUid;
738 updatePid = true;
739 }
740 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700741 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800742 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800743 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700744 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800745 __func__, callingUid, callingPid, clientPid);
746 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700747 }
748
Eric Laurent21da6472017-11-09 16:29:26 -0800749 audio_session_t sessionId = input.sessionId;
750 if (sessionId == AUDIO_SESSION_ALLOCATE) {
751 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800752 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
753 lStatus = BAD_VALUE;
754 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800755 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800756
Eric Laurent21da6472017-11-09 16:29:26 -0800757 output.sessionId = sessionId;
758 output.outputId = AUDIO_IO_HANDLE_NONE;
759 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700760 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200761 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800762 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800763
764 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
765 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
766 goto Exit;
767 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800768 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
769 // but if someone uses binder directly they could bypass that and cause us to crash
770 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000771 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772 lStatus = BAD_VALUE;
773 goto Exit;
774 }
775
Glenn Kasten53b5d092014-02-05 10:00:23 -0800776 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800777 if (!audio_is_output_channel(input.config.channel_mask)) {
778 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800779 lStatus = BAD_VALUE;
780 goto Exit;
781 }
782
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700783 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800784 if (!audio_is_valid_format(input.config.format)) {
785 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700786 lStatus = BAD_VALUE;
787 goto Exit;
788 }
789
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 {
791 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800792 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800794 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 lStatus = BAD_VALUE;
796 goto Exit;
797 }
798
Eric Laurent21da6472017-11-09 16:29:26 -0800799 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800
Glenn Kastene848bd92014-03-13 15:00:32 -0700801 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800802 // check if an effect chain with the same session ID is present on another
803 // output thread and move it here.
804 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
805 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
806 if (mPlaybackThreads.keyAt(i) != output.outputId) {
807 uint32_t sessions = t->hasAudioSession(sessionId);
808 if (sessions & ThreadBase::EFFECT_SESSION) {
809 effectThread = t.get();
810 break;
Eric Laurentde070132010-07-13 04:45:46 -0700811 }
812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
Eric Laurent21da6472017-11-09 16:29:26 -0800814 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815
Eric Laurent21da6472017-11-09 16:29:26 -0800816 output.sampleRate = input.config.sample_rate;
817 output.frameCount = input.frameCount;
818 output.notificationFrameCount = input.notificationFrameCount;
819 output.flags = input.flags;
820
Eric Laurent42984412019-05-09 17:57:03 -0700821 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700822 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800823 &output.frameCount, &output.notificationFrameCount,
824 input.notificationsPerBuffer, input.speed,
825 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700826 callingPid, input.clientInfo.clientTid, clientUid,
827 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800828 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700829 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700830
Eric Laurent21da6472017-11-09 16:29:26 -0800831 output.afFrameCount = thread->frameCount();
832 output.afSampleRate = thread->sampleRate();
833 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800834 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800835
Kevin Rocard153f92d2018-12-18 18:33:28 -0800836 if (lStatus == NO_ERROR) {
837 // Connect secondary outputs. Failure on a secondary output must not imped the primary
838 // Any secondary output setup failure will lead to a desync between the AP and AF until
839 // the track is destroyed.
840 TeePatches teePatches;
841 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
842 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
843 if (secondaryThread == NULL) {
844 ALOGE("no playback thread found for secondary output %d", output.outputId);
845 continue;
846 }
847
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100848 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
849 / thread->sampleRate();
850 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
851 / secondaryThread->sampleRate();
852 // If the secondary output has just been opened, the first secondaryThread write
853 // will not block as it will fill the empty startup buffer of the HAL,
854 // so a second sink buffer needs to be ready for the immediate next blocking write.
855 // Additionally, have a margin of one main thread buffer as the scheduling jitter
856 // can reorder the writes (eg if thread A&B have the same write intervale,
857 // the scheduler could schedule AB...BA)
858 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
859 // Total secondary output buffer must be at least as the read frames plus
860 // the margin of a few buffers on both sides in case the
861 // threads scheduling has some jitter.
862 // That value should not impact latency as the secondary track is started before
863 // its buffer is full, see frameCountToBeReady.
864 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
865 // The frameCount should also not be smaller than the secondary thread min frame
866 // count
867 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
868 [&] { Mutex::Autolock _l(secondaryThread->mLock);
869 return secondaryThread->latency_l(); }(),
870 secondaryThread->mNormalFrameCount,
871 secondaryThread->mSampleRate,
872 output.sampleRate,
873 input.speed);
874 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800875
876 using namespace std::chrono_literals;
877 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
878 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
879 output.sampleRate,
880 inChannelMask,
881 input.config.format,
882 frameCount,
883 NULL /* buffer */,
884 (size_t)0 /* bufferSize */,
885 AUDIO_INPUT_FLAG_DIRECT,
886 0ns /* timeout */);
887 status_t status = patchRecord->initCheck();
888 if (status != NO_ERROR) {
889 ALOGE("Secondary output patchRecord init failed: %d", status);
890 continue;
891 }
Andy Hungae22b482019-05-09 15:38:55 -0700892
893 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
894 // for fast usage: thread has fast mixer, sample rate matches, etc.;
895 // for now, we exclude fast tracks by removing the Fast flag.
896 const audio_output_flags_t outputFlags =
897 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800898 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
899 streamType,
900 output.sampleRate,
901 input.config.channel_mask,
902 input.config.format,
903 frameCount,
904 patchRecord->buffer(),
905 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700906 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100907 0ns /* timeout */,
908 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800909 status = patchTrack->initCheck();
910 if (status != NO_ERROR) {
911 ALOGE("Secondary output patchTrack init failed: %d", status);
912 continue;
913 }
914 teePatches.push_back({patchRecord, patchTrack});
915 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800916 // In case the downstream patchTrack on the secondaryThread temporarily outlives
917 // our created track, ensure the corresponding patchRecord is still alive.
918 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
919 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800920 }
921 track->setTeePatches(std::move(teePatches));
922 }
923
Eric Laurent39e94f82010-07-28 01:32:47 -0700924 // move effect chain to this output thread if an effect on same session was waiting
925 // for a track to be created
926 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700927 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700928 Mutex::Autolock _dl(thread->mLock);
929 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700930 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
931 effectThreadId = thread->id();
932 effectIds = thread->getEffectIds_l(sessionId);
933 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700934 }
Eric Laurenta011e352012-03-29 15:51:43 -0700935
936 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700937 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800938 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700939 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700940 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700941 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700942 } else {
943 mPendingSyncEvents[i]->cancel();
944 }
Eric Laurenta011e352012-03-29 15:51:43 -0700945 mPendingSyncEvents.removeAt(i);
946 i--;
947 }
948 }
949 }
Glenn Kastene198c362013-08-13 09:13:36 -0700950
Eric Laurent21da6472017-11-09 16:29:26 -0800951 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 }
Glenn Kastene198c362013-08-13 09:13:36 -0700953
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700954 if (lStatus != NO_ERROR) {
955 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700956 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700957 // Don't hold mClientLock when releasing the reference on the track as the
958 // destructor will acquire it.
959 {
960 Mutex::Autolock _cl(mClientLock);
961 client.clear();
962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700964 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 }
966
Eric Laurent6c796322019-04-09 14:13:17 -0700967 // effectThreadId is not NONE if an effect chain corresponding to the track session
968 // was found on another thread and must be moved on this thread
969 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
970 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
971 }
972
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700973 // return handle to client
974 trackHandle = new TrackHandle(track);
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800977 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700978 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800979 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700980 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 return trackHandle;
982}
983
Glenn Kasten2c073da2016-02-26 09:14:08 -0800984uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700985{
986 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800987 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800989 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 return 0;
991 }
992 return thread->sampleRate();
993}
994
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800995audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
997 Mutex::Autolock _l(mLock);
998 PlaybackThread *thread = checkPlaybackThread_l(output);
999 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001000 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001001 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002 }
1003 return thread->format();
1004}
1005
Glenn Kasten2c073da2016-02-26 09:14:08 -08001006size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007{
1008 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001009 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001011 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012 return 0;
1013 }
Glenn Kasten58912562012-04-03 10:45:00 -07001014 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1015 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 return thread->frameCount();
1017}
1018
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001019size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1020{
1021 Mutex::Autolock _l(mLock);
1022 ThreadBase *thread = checkThread_l(ioHandle);
1023 if (thread == NULL) {
1024 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1025 return 0;
1026 }
1027 return thread->frameCountHAL();
1028}
1029
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001030uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031{
1032 Mutex::Autolock _l(mLock);
1033 PlaybackThread *thread = checkPlaybackThread_l(output);
1034 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001035 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001036 return 0;
1037 }
1038 return thread->latency();
1039}
1040
1041status_t AudioFlinger::setMasterVolume(float value)
1042{
Eric Laurenta1884f92011-08-23 08:25:03 -07001043 status_t ret = initCheck();
1044 if (ret != NO_ERROR) {
1045 return ret;
1046 }
1047
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 // check calling permissions
1049 if (!settingsAllowed()) {
1050 return PERMISSION_DENIED;
1051 }
1052
Eric Laurenta4c5a552012-03-29 10:12:40 -07001053 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001054 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001055
John Grossmanee578c02012-07-23 17:05:46 -07001056 // Set master volume in the HALs which support it.
1057 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1058 AutoMutex lock(mHardwareLock);
1059 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001060
John Grossmanee578c02012-07-23 17:05:46 -07001061 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1062 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001063 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001064 }
John Grossmanee578c02012-07-23 17:05:46 -07001065 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067
John Grossmanee578c02012-07-23 17:05:46 -07001068 // Now set the master volume in each playback thread. Playback threads
1069 // assigned to HALs which do not have master volume support will apply
1070 // master volume during the mix operation. Threads with HALs which do
1071 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001072 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1073 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1074 continue;
1075 }
John Grossmanee578c02012-07-23 17:05:46 -07001076 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078
1079 return NO_ERROR;
1080}
1081
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001082status_t AudioFlinger::setMasterBalance(float balance)
1083{
1084 status_t ret = initCheck();
1085 if (ret != NO_ERROR) {
1086 return ret;
1087 }
1088
1089 // check calling permissions
1090 if (!settingsAllowed()) {
1091 return PERMISSION_DENIED;
1092 }
1093
1094 // check range
1095 if (isnan(balance) || fabs(balance) > 1.f) {
1096 return BAD_VALUE;
1097 }
1098
1099 Mutex::Autolock _l(mLock);
1100
1101 // short cut.
1102 if (mMasterBalance == balance) return NO_ERROR;
1103
1104 mMasterBalance = balance;
1105
1106 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1107 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1108 continue;
1109 }
1110 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1111 }
1112
1113 return NO_ERROR;
1114}
1115
Glenn Kastenf78aee72012-01-04 11:00:47 -08001116status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117{
Eric Laurenta1884f92011-08-23 08:25:03 -07001118 status_t ret = initCheck();
1119 if (ret != NO_ERROR) {
1120 return ret;
1121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122
1123 // check calling permissions
1124 if (!settingsAllowed()) {
1125 return PERMISSION_DENIED;
1126 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001127 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001128 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 return BAD_VALUE;
1130 }
1131
1132 { // scope for the lock
1133 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001134 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001136 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 mHardwareStatus = AUDIO_HW_IDLE;
1138 }
1139
1140 if (NO_ERROR == ret) {
1141 Mutex::Autolock _l(mLock);
1142 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001143 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001144 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 }
1146
1147 return ret;
1148}
1149
1150status_t AudioFlinger::setMicMute(bool state)
1151{
Eric Laurenta1884f92011-08-23 08:25:03 -07001152 status_t ret = initCheck();
1153 if (ret != NO_ERROR) {
1154 return ret;
1155 }
1156
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157 // check calling permissions
1158 if (!settingsAllowed()) {
1159 return PERMISSION_DENIED;
1160 }
1161
1162 AutoMutex lock(mHardwareLock);
1163 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001164 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001165 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1166 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001167 if (result != NO_ERROR) {
1168 ret = result;
1169 }
1170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mHardwareStatus = AUDIO_HW_IDLE;
1172 return ret;
1173}
1174
1175bool AudioFlinger::getMicMute() const
1176{
Eric Laurenta1884f92011-08-23 08:25:03 -07001177 status_t ret = initCheck();
1178 if (ret != NO_ERROR) {
1179 return false;
1180 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001181 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001182 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001183 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001185 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001186 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1187 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001188 if (result == NO_ERROR) {
1189 mute = mute && state;
1190 }
1191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001193
1194 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195}
1196
Eric Laurent5ada82e2019-08-29 17:53:54 -07001197void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001198{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001199 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001200
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001201 AutoMutex lock(mLock);
1202 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001203 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001204 }
1205 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001206 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001207 }
1208}
1209
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210status_t AudioFlinger::setMasterMute(bool muted)
1211{
John Grossmand8f178d2012-07-20 14:51:35 -07001212 status_t ret = initCheck();
1213 if (ret != NO_ERROR) {
1214 return ret;
1215 }
1216
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 // check calling permissions
1218 if (!settingsAllowed()) {
1219 return PERMISSION_DENIED;
1220 }
1221
John Grossmanee578c02012-07-23 17:05:46 -07001222 Mutex::Autolock _l(mLock);
1223 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001224
John Grossmanee578c02012-07-23 17:05:46 -07001225 // Set master mute in the HALs which support it.
1226 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1227 AutoMutex lock(mHardwareLock);
1228 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001229
John Grossmanee578c02012-07-23 17:05:46 -07001230 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1231 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001232 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001233 }
John Grossmanee578c02012-07-23 17:05:46 -07001234 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001235 }
1236
John Grossmanee578c02012-07-23 17:05:46 -07001237 // Now set the master mute in each playback thread. Playback threads
1238 // assigned to HALs which do not have master mute support will apply master
1239 // mute during the mix operation. Threads with HALs which do support master
1240 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001241 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1242 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1243 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245
1246 return NO_ERROR;
1247}
1248
1249float AudioFlinger::masterVolume() const
1250{
Glenn Kasten98067102011-12-13 11:47:54 -08001251 Mutex::Autolock _l(mLock);
1252 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253}
1254
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001255status_t AudioFlinger::getMasterBalance(float *balance) const
1256{
1257 Mutex::Autolock _l(mLock);
1258 *balance = getMasterBalance_l();
1259 return NO_ERROR; // if called through binder, may return a transactional error
1260}
1261
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262bool AudioFlinger::masterMute() const
1263{
Glenn Kasten98067102011-12-13 11:47:54 -08001264 Mutex::Autolock _l(mLock);
1265 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266}
1267
John Grossman4ff14ba2012-02-08 16:37:41 -08001268float AudioFlinger::masterVolume_l() const
1269{
John Grossman4ff14ba2012-02-08 16:37:41 -08001270 return mMasterVolume;
1271}
1272
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001273float AudioFlinger::getMasterBalance_l() const
1274{
1275 return mMasterBalance;
1276}
1277
John Grossmand8f178d2012-07-20 14:51:35 -07001278bool AudioFlinger::masterMute_l() const
1279{
John Grossmanee578c02012-07-23 17:05:46 -07001280 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001281}
1282
Eric Laurent223fd5c2014-11-11 13:43:36 -08001283status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1284{
1285 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001286 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001287 return BAD_VALUE;
1288 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001289 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1290 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1291 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001292 return PERMISSION_DENIED;
1293 }
1294
1295 return NO_ERROR;
1296}
1297
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001298status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1299 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300{
1301 // check calling permissions
1302 if (!settingsAllowed()) {
1303 return PERMISSION_DENIED;
1304 }
1305
Eric Laurent223fd5c2014-11-11 13:43:36 -08001306 status_t status = checkStreamType(stream);
1307 if (status != NO_ERROR) {
1308 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 }
Eric Laurent98e38192018-02-15 18:31:53 -08001310 if (output == AUDIO_IO_HANDLE_NONE) {
1311 return BAD_VALUE;
1312 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001313 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1314 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001315
1316 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001317 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1318 if (volumeInterface == NULL) {
1319 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320 }
Eric Laurent98e38192018-02-15 18:31:53 -08001321 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322
1323 return NO_ERROR;
1324}
1325
Glenn Kastenfff6d712012-01-12 16:38:12 -08001326status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327{
1328 // check calling permissions
1329 if (!settingsAllowed()) {
1330 return PERMISSION_DENIED;
1331 }
1332
Eric Laurent223fd5c2014-11-11 13:43:36 -08001333 status_t status = checkStreamType(stream);
1334 if (status != NO_ERROR) {
1335 return status;
1336 }
1337 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1338
1339 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001340 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341 return BAD_VALUE;
1342 }
1343
Eric Laurent93575202011-01-18 18:39:02 -08001344 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001345 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001346 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1347 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1348 volumeInterfaces[i]->setStreamMute(stream, muted);
1349 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350
1351 return NO_ERROR;
1352}
1353
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001354float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001355{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001356 status_t status = checkStreamType(stream);
1357 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 return 0.0f;
1359 }
Eric Laurent98e38192018-02-15 18:31:53 -08001360 if (output == AUDIO_IO_HANDLE_NONE) {
1361 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001362 }
1363
Eric Laurent98e38192018-02-15 18:31:53 -08001364 AutoMutex lock(mLock);
1365 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1366 if (volumeInterface == NULL) {
1367 return 0.0f;
1368 }
1369
1370 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371}
1372
Glenn Kastenfff6d712012-01-12 16:38:12 -08001373bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001375 status_t status = checkStreamType(stream);
1376 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 return true;
1378 }
1379
Glenn Kasten6637baa2012-01-09 09:40:36 -08001380 AutoMutex lock(mLock);
1381 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382}
1383
Eric Laurent054d9d32015-04-24 08:48:48 -07001384
1385void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1386{
1387 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1388 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1389 }
1390}
1391
jiabinc52b1ff2019-10-31 17:20:42 -07001392void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1393{
1394 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1395 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1396 }
1397}
1398
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001399// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1400void AudioFlinger::forwardParametersToDownstreamPatches_l(
1401 audio_io_handle_t upStream, const String8& keyValuePairs,
1402 std::function<bool(const sp<PlaybackThread>&)> useThread)
1403{
1404 std::vector<PatchPanel::SoftwarePatch> swPatches;
1405 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1406 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1407 __func__, swPatches.size(), upStream);
1408 for (const auto& swPatch : swPatches) {
1409 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1410 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1411 downStream->setParameters(keyValuePairs);
1412 }
1413 }
1414}
1415
Eric Laurentf1047e82018-04-16 19:18:20 -07001416// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1417// Some keys are used for audio routing and audio path configuration and should be reserved for use
1418// by audio policy and audio flinger for functional, privacy and security reasons.
1419void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1420{
1421 static const String8 kReservedParameters[] = {
1422 String8(AudioParameter::keyRouting),
1423 String8(AudioParameter::keySamplingRate),
1424 String8(AudioParameter::keyFormat),
1425 String8(AudioParameter::keyChannels),
1426 String8(AudioParameter::keyFrameCount),
1427 String8(AudioParameter::keyInputSource),
1428 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001429 String8(AudioParameter::keyDeviceConnect),
1430 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001431 String8(AudioParameter::keyStreamSupportedFormats),
1432 String8(AudioParameter::keyStreamSupportedChannels),
1433 String8(AudioParameter::keyStreamSupportedSamplingRates),
1434 };
1435
Andy Hung4ef19fa2018-05-15 19:35:29 -07001436 if (isAudioServerUid(callingUid)) {
1437 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001438 }
1439
1440 AudioParameter param = AudioParameter(keyValuePairs);
1441 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001442 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001443 for (auto& key : kReservedParameters) {
1444 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001445 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001446 param.remove(key);
1447 }
1448 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001449 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1450 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001451 keyValuePairs = param.toString();
1452}
1453
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001454void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1455 size_t rejectedKVPSize, const String8& rejectedKVPs,
1456 uid_t callingUid) {
1457 auto prefix = String8::format("UID %5d", callingUid);
1458 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1459 if (rejectedKVPSize != 0) {
1460 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1461 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1462 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1463 } else {
1464 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1465 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1466 }
1467}
1468
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001469status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470{
Eric Laurentf1047e82018-04-16 19:18:20 -07001471 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1472 ioHandle, keyValuePairs.string(),
1473 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001474
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 // check calling permissions
1476 if (!settingsAllowed()) {
1477 return PERMISSION_DENIED;
1478 }
1479
Eric Laurentf1047e82018-04-16 19:18:20 -07001480 String8 filteredKeyValuePairs = keyValuePairs;
1481 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1482
1483 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1484
Glenn Kasten142f5192014-03-25 17:44:59 -07001485 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1486 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001487 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001488 // result will remain NO_INIT if no audio device is present
1489 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001490 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001491 AutoMutex lock(mHardwareLock);
1492 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1493 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001494 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001495 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001496 // return success if at least one audio device accepts the parameters as not all
1497 // HALs are requested to support all parameters. If no audio device supports the
1498 // requested parameters, the last error is reported.
1499 if (final_result != NO_ERROR) {
1500 final_result = result;
1501 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001502 }
1503 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001504 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001505 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001506 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001507 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001508 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1509 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001510 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001511 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001512 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001513 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001514 }
1515 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001516 String8 screenState;
1517 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001518 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001519 if (isOff != (AudioFlinger::mScreenState & 1)) {
1520 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001521 }
1522 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001523 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524 }
1525
1526 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1527 // and the thread is exited once the lock is released
1528 sp<ThreadBase> thread;
1529 {
1530 Mutex::Autolock _l(mLock);
1531 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001532 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001534 if (thread == 0) {
1535 thread = checkMmapThread_l(ioHandle);
1536 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001537 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001538 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001539 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001540 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001541 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1542 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001543 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001544 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 }
1546 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001547 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001548 status_t result = thread->setParameters(filteredKeyValuePairs);
1549 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1550 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 }
1552 return BAD_VALUE;
1553}
1554
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001555String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001557 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1558 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559
Eric Laurenta4c5a552012-03-29 10:12:40 -07001560 Mutex::Autolock _l(mLock);
1561
Glenn Kasten142f5192014-03-25 17:44:59 -07001562 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001563 String8 out_s8;
1564
Dima Zavin799a70e2011-04-18 16:57:27 -07001565 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001566 String8 s;
1567 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001568 {
1569 AutoMutex lock(mHardwareLock);
1570 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001571 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1572 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001573 mHardwareStatus = AUDIO_HW_IDLE;
1574 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001575 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001576 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001577 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 }
1579
Eric Laurent6acd1d42017-01-04 14:23:29 -08001580 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1581 if (thread == NULL) {
1582 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1583 if (thread == NULL) {
1584 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1585 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001586 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001587 }
1588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001590 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591}
1592
Glenn Kastendd8104c2012-07-02 12:42:44 -07001593size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1594 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595{
Eric Laurenta1884f92011-08-23 08:25:03 -07001596 status_t ret = initCheck();
1597 if (ret != NO_ERROR) {
1598 return 0;
1599 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001600 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001601 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001602 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001603 return 0;
1604 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001605
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001606 AutoMutex lock(mHardwareLock);
1607 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001608
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001609 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001610 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1611 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1612 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1613 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1614 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1615
1616 std::vector<audio_format_t> formats = {format};
1617 if (format != AUDIO_FORMAT_PCM_16_BIT)
1618 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1619
1620 std::vector<uint32_t> sampleRates = {sampleRate};
1621 static const uint32_t SR_44100 = 44100;
1622 static const uint32_t SR_48000 = 48000;
1623
1624 if (sampleRate != SR_48000)
1625 sampleRates.push_back(SR_48000);
1626 if (sampleRate != SR_44100)
1627 sampleRates.push_back(SR_44100);
1628
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001629 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001630
Robin Lee9899ff72019-12-24 22:02:08 +01001631 // Change parameters of the configuration each iteration until we find a
1632 // configuration that the device will support.
1633 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001634 for (auto testChannelMask : channelMasks) {
1635 config.channel_mask = testChannelMask;
1636 for (auto testFormat : formats) {
1637 config.format = testFormat;
1638 for (auto testSampleRate : sampleRates) {
1639 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001640
Judy Hsiaoabab5222019-11-09 18:14:58 +08001641 size_t bytes = 0;
1642 status_t result = dev->getInputBufferSize(&config, &bytes);
1643 if (result != OK || bytes == 0) {
1644 continue;
1645 }
1646
1647 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1648 config.format != format) {
1649 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1650 uint32_t srcChannelCount =
1651 audio_channel_count_from_in_mask(config.channel_mask);
1652 size_t srcFrames =
1653 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1654 size_t dstFrames = destinationFramesPossible(
1655 srcFrames, config.sample_rate, sampleRate);
1656 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1657 }
1658 return bytes;
1659 }
1660 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001661 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001662
1663 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1664 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1665 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666}
1667
Glenn Kasten5f972c02014-01-13 09:59:31 -08001668uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670 Mutex::Autolock _l(mLock);
1671
1672 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1673 if (recordThread != NULL) {
1674 return recordThread->getInputFramesLost();
1675 }
1676 return 0;
1677}
1678
1679status_t AudioFlinger::setVoiceVolume(float value)
1680{
Eric Laurenta1884f92011-08-23 08:25:03 -07001681 status_t ret = initCheck();
1682 if (ret != NO_ERROR) {
1683 return ret;
1684 }
1685
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 // check calling permissions
1687 if (!settingsAllowed()) {
1688 return PERMISSION_DENIED;
1689 }
1690
1691 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001692 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001693 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001694 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 mHardwareStatus = AUDIO_HW_IDLE;
1696
1697 return ret;
1698}
1699
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001700status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001701 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 Mutex::Autolock _l(mLock);
1704
1705 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1706 if (playbackThread != NULL) {
1707 return playbackThread->getRenderPosition(halFrames, dspFrames);
1708 }
1709
1710 return BAD_VALUE;
1711}
1712
1713void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1714{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001716 if (client == 0) {
1717 return;
1718 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001719 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001720 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001721 {
1722 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001723 if (mNotificationClients.indexOfKey(pid) < 0) {
1724 sp<NotificationClient> notificationClient = new NotificationClient(this,
1725 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001726 pid,
1727 uid);
1728 ALOGV("registerClient() client %p, pid %d, uid %u",
1729 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730
Eric Laurent021cf962014-05-13 10:18:14 -07001731 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732
Marco Nelissen06b46062014-11-14 07:58:25 -08001733 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001734 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001735 }
1736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737
Eric Laurent021cf962014-05-13 10:18:14 -07001738 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001739 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001740 // the config change is always sent from playback or record threads to avoid deadlock
1741 // with AudioSystem::gLock
1742 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001743 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001744 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001746 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 }
1749}
1750
1751void AudioFlinger::removeNotificationClient(pid_t pid)
1752{
Eric Laurent6c796322019-04-09 14:13:17 -07001753 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001754 {
Eric Laurent6c796322019-04-09 14:13:17 -07001755 Mutex::Autolock _l(mLock);
1756 {
1757 Mutex::Autolock _cl(mClientLock);
1758 mNotificationClients.removeItem(pid);
1759 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001760
Eric Laurent6c796322019-04-09 14:13:17 -07001761 ALOGV("%d died, releasing its sessions", pid);
1762 size_t num = mAudioSessionRefs.size();
1763 bool removed = false;
1764 for (size_t i = 0; i < num; ) {
1765 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1766 ALOGV(" pid %d @ %zu", ref->mPid, i);
1767 if (ref->mPid == pid) {
1768 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1769 mAudioSessionRefs.removeAt(i);
1770 delete ref;
1771 removed = true;
1772 num--;
1773 } else {
1774 i++;
1775 }
1776 }
1777 if (removed) {
1778 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001779 }
1780 }
Eric Laurent6c796322019-04-09 14:13:17 -07001781 for (auto& effect : removedEffects) {
1782 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001783 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784}
1785
Eric Laurent73e26b62015-04-27 16:55:58 -07001786void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001787 const sp<AudioIoDescriptor>& ioDesc,
1788 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789{
Eric Laurent021cf962014-05-13 10:18:14 -07001790 Mutex::Autolock _l(mClientLock);
1791 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001793 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1794 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796 }
1797}
1798
Eric Laurent021cf962014-05-13 10:18:14 -07001799// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800void AudioFlinger::removeClient_l(pid_t pid)
1801{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001802 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001803 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804 mClients.removeItem(pid);
1805}
1806
Eric Laurent717e1282012-06-29 16:36:52 -07001807// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001808sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1809 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001810{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001811 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001812
1813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001814 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001815 ALOG_ASSERT(thread == 0);
1816 thread = mPlaybackThreads.valueAt(i);
1817 }
1818 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001819 if (thread != nullptr) {
1820 return thread;
1821 }
1822 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1823 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1824 ALOG_ASSERT(thread == 0);
1825 thread = mRecordThreads.valueAt(i);
1826 }
1827 }
1828 if (thread != nullptr) {
1829 return thread;
1830 }
1831 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1832 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1833 ALOG_ASSERT(thread == 0);
1834 thread = mMmapThreads.valueAt(i);
1835 }
1836 }
Eric Laurent717e1282012-06-29 16:36:52 -07001837 return thread;
1838}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841
1842// ----------------------------------------------------------------------------
1843
1844AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1845 : RefBase(),
1846 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001847 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848{
Andy Hung6f248bb2018-01-23 14:04:37 -08001849 mMemoryDealer = new MemoryDealer(
1850 audioFlinger->getClientSharedHeapSize(),
1851 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852}
1853
Eric Laurent021cf962014-05-13 10:18:14 -07001854// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855AudioFlinger::Client::~Client()
1856{
1857 mAudioFlinger->removeClient_l(mPid);
1858}
1859
Glenn Kasten435dbe62012-01-30 10:15:48 -08001860sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861{
1862 return mMemoryDealer;
1863}
1864
1865// ----------------------------------------------------------------------------
1866
1867AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1868 const sp<IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001869 pid_t pid,
1870 uid_t uid)
1871 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872{
1873}
1874
1875AudioFlinger::NotificationClient::~NotificationClient()
1876{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877}
1878
Glenn Kasten0f11b512014-01-31 16:18:54 -08001879void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880{
1881 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001882 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883}
1884
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001885// ----------------------------------------------------------------------------
1886AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1887 : mPendingRequests(false) {}
1888
1889
1890void AudioFlinger::MediaLogNotifier::requestMerge() {
1891 AutoMutex _l(mMutex);
1892 mPendingRequests = true;
1893 mCond.signal();
1894}
1895
1896bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001897 // Should already have been checked, but just in case
1898 if (sMediaLogService == 0) {
1899 return false;
1900 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001901 // Wait until there are pending requests
1902 {
1903 AutoMutex _l(mMutex);
1904 mPendingRequests = false; // to ignore past requests
1905 while (!mPendingRequests) {
1906 mCond.wait(mMutex);
1907 // TODO may also need an exitPending check
1908 }
1909 mPendingRequests = false;
1910 }
1911 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001912 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001913 usleep(kPostTriggerSleepPeriod);
1914 return true;
1915}
1916
1917void AudioFlinger::requestLogMerge() {
1918 mMediaLogNotifier->requestMerge();
1919}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920
1921// ----------------------------------------------------------------------------
1922
Eric Laurentf14db3c2017-12-08 14:20:36 -08001923sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1924 CreateRecordOutput& output,
1925 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926{
1927 sp<RecordThread::RecordTrack> recordTrack;
1928 sp<RecordHandle> recordHandle;
1929 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001931 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001932 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933
Eric Laurentf14db3c2017-12-08 14:20:36 -08001934 output.cblk.clear();
1935 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001936 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001937
Eric Laurentf14db3c2017-12-08 14:20:36 -08001938 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001939 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001940 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001941 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001942 ALOGW_IF(clientUid != callingUid,
1943 "%s uid %d tried to pass itself off as %d",
1944 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001945 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001946 updatePid = true;
1947 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001948 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001949 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001950 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001951 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001952 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001953 __func__, callingUid, callingPid, clientPid);
1954 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001955 }
1956
Andy Hung6770c6f2015-04-07 13:43:36 -07001957 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001958 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1959 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001960 lStatus = BAD_VALUE;
1961 goto Exit;
1962 }
1963
Glenn Kasten53b5d092014-02-05 10:00:23 -08001964 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001965 if (!audio_is_input_channel(input.config.channel_mask)) {
1966 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001967 lStatus = BAD_VALUE;
1968 goto Exit;
1969 }
1970
Eric Laurentf14db3c2017-12-08 14:20:36 -08001971 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1972 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1973 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1974 lStatus = BAD_VALUE;
1975 goto Exit;
1976 }
1977
1978 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001979 output.selectedDeviceId = input.selectedDeviceId;
1980 output.flags = input.flags;
1981
1982 client = registerPid(clientPid);
1983
1984 // Not a conventional loop, but a retry loop for at most two iterations total.
1985 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1986 // Exits loop via break on no error of got exit on error
1987 // The sp<> references will be dropped when re-entering scope.
1988 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1989 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001990 // release previously opened input if retrying.
1991 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1992 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001993 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001994 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001995 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001996 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001997 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001998 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001999 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002000 sessionId,
2001 // FIXME compare to AudioTrack
2002 clientPid,
2003 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002004 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002005 &input.config,
2006 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002007 if (lStatus != NO_ERROR) {
2008 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2009 goto Exit;
2010 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002011
Glenn Kasten05997e22014-03-13 15:08:33 -07002012 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002014 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07002016 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 lStatus = BAD_VALUE;
2018 goto Exit;
2019 }
2020
Eric Laurentf14db3c2017-12-08 14:20:36 -08002021 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022
Eric Laurentf14db3c2017-12-08 14:20:36 -08002023 output.sampleRate = input.config.sample_rate;
2024 output.frameCount = input.frameCount;
2025 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002026
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002027 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002028 input.config.format, input.config.channel_mask,
2029 &output.frameCount, sessionId,
2030 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002031 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002032 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002033 &lStatus, portId,
2034 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002035 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002036
Eric Laurentf14db3c2017-12-08 14:20:36 -08002037 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2038 // audio policy manager without FAST constraint
2039 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002040 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002041 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002042
2043 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002044 goto Exit;
2045 }
2046
2047 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2048 // session and move it to this thread.
2049 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2050 if (chain != 0) {
2051 Mutex::Autolock _l(thread->mLock);
2052 thread->addEffectChain_l(chain);
2053 }
2054 break;
2055 }
2056 // End of retry loop.
2057 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 }
Glenn Kastene198c362013-08-13 09:13:36 -07002059
Eric Laurentf14db3c2017-12-08 14:20:36 -08002060 output.cblk = recordTrack->getCblk();
2061 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002062 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002063
2064 // return handle to client
2065 recordHandle = new RecordHandle(recordTrack);
2066
2067Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002068 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002069 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002070 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002071 // Don't hold mClientLock when releasing the reference on the track as the
2072 // destructor will acquire it.
2073 {
2074 Mutex::Autolock _cl(mClientLock);
2075 client.clear();
2076 }
Eric Laurent896c9672017-12-08 14:08:45 -08002077 recordTrack.clear();
2078 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002079 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002080 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 }
2082
Glenn Kasten9156ef32013-08-06 15:39:08 -07002083 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 return recordHandle;
2085}
2086
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002087
2088
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089// ----------------------------------------------------------------------------
2090
Eric Laurenta4c5a552012-03-29 10:12:40 -07002091audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2092{
Eric Laurent44622db2014-08-01 19:00:33 -07002093 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002094 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002095 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002096 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002097 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002098 }
2099 Mutex::Autolock _l(mLock);
2100 return loadHwModule_l(name);
2101}
2102
2103// loadHwModule_l() must be called with AudioFlinger::mLock held
2104audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2105{
2106 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2107 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2108 ALOGW("loadHwModule() module %s already loaded", name);
2109 return mAudioHwDevs.keyAt(i);
2110 }
2111 }
2112
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002113 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002114
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002115 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002116 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002117 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002118 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002119 }
2120
2121 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002122 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002123 mHardwareStatus = AUDIO_HW_IDLE;
2124 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002125 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002126 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002127 }
2128
John Grossmanee578c02012-07-23 17:05:46 -07002129 // Check and cache this HAL's level of support for master mute and master
2130 // volume. If this is the first HAL opened, and it supports the get
2131 // methods, use the initial values provided by the HAL as the current
2132 // master mute and volume settings.
2133
2134 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2135 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002136 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002137
2138 if (0 == mAudioHwDevs.size()) {
2139 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002140 float mv;
2141 if (OK == dev->getMasterVolume(&mv)) {
2142 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002143 }
2144
2145 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002146 bool mm;
2147 if (OK == dev->getMasterMute(&mm)) {
2148 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002149 }
2150 }
2151
Eric Laurenta4c5a552012-03-29 10:12:40 -07002152 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002153 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002154 flags = static_cast<AudioHwDevice::Flags>(flags |
2155 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2156 }
2157
2158 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002159 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002160 flags = static_cast<AudioHwDevice::Flags>(flags |
2161 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2162 }
2163
Eric Laurenta4c5a552012-03-29 10:12:40 -07002164 mHardwareStatus = AUDIO_HW_IDLE;
2165 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002166 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002167 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2168 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2169 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002170
Glenn Kastena13cde92016-03-28 15:26:02 -07002171 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002172 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002173
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002174 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002175
2176 return handle;
2177
2178}
2179
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002180// ----------------------------------------------------------------------------
2181
Glenn Kasten3b16c762012-11-14 08:44:39 -08002182uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002183{
2184 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002185 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002186 return thread != NULL ? thread->sampleRate() : 0;
2187}
2188
Glenn Kastene33054e2012-11-14 12:54:39 -08002189size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002190{
2191 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002192 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002193 return thread != NULL ? thread->frameCountHAL() : 0;
2194}
2195
2196// ----------------------------------------------------------------------------
2197
Andy Hung6f248bb2018-01-23 14:04:37 -08002198status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002199{
2200 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002201 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002202 return PERMISSION_DENIED;
2203 }
2204 Mutex::Autolock _l(mLock);
2205 if (mIsDeviceTypeKnown) {
2206 return INVALID_OPERATION;
2207 }
2208 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002209 mTotalMemory = totalMemory;
2210 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2211 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2212 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2213 // though actual setting is determined through device configuration.
2214 constexpr int64_t GB = 1024 * 1024 * 1024;
2215 mClientSharedHeapSize =
2216 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2217 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2218 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2219 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2220 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002221 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002222
2223 // TODO: Cache the client shared heap size in a persistent property.
2224 // It's possible that a native process or Java service or app accesses audioserver
2225 // after it is registered by system server, but before AudioService updates
2226 // the memory info. This would occur immediately after boot or an audioserver
2227 // crash and restore. Before update from AudioService, the client would get the
2228 // minimum heap size.
2229
2230 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2231 (isLowRamDevice ? "true" : "false"),
2232 (long long)mTotalMemory,
2233 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002234 return NO_ERROR;
2235}
2236
Andy Hung6f248bb2018-01-23 14:04:37 -08002237size_t AudioFlinger::getClientSharedHeapSize() const
2238{
2239 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2240 if (heapSizeInBytes != 0) { // read-only property overrides all.
2241 return heapSizeInBytes;
2242 }
2243 return mClientSharedHeapSize;
2244}
2245
Mikhail Naganovdea53042018-04-26 13:10:21 -07002246status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2247{
2248 ALOGV(__func__);
2249
2250 audio_module_handle_t module;
2251 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2252 module = config->ext.device.hw_module;
2253 } else {
2254 module = config->ext.mix.hw_module;
2255 }
2256
2257 Mutex::Autolock _l(mLock);
2258 ssize_t index = mAudioHwDevs.indexOfKey(module);
2259 if (index < 0) {
2260 ALOGW("%s() bad hw module %d", __func__, module);
2261 return BAD_VALUE;
2262 }
2263
2264 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2265 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2266}
2267
Eric Laurent93c3d412014-08-01 14:48:35 -07002268audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2269{
2270 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002271
2272 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2273 if (index >= 0) {
2274 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2275 mHwAvSyncIds.valueAt(index), sessionId);
2276 return mHwAvSyncIds.valueAt(index);
2277 }
2278
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002279 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002280 if (dev == NULL) {
2281 return AUDIO_HW_SYNC_INVALID;
2282 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002283 String8 reply;
2284 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002285 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002286 param = AudioParameter(reply);
2287 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002288
2289 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002290 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002291 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2292 return AUDIO_HW_SYNC_INVALID;
2293 }
2294
2295 // allow only one session for a given HW A/V sync ID.
2296 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2297 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2298 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2299 value, mHwAvSyncIds.keyAt(i));
2300 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002301 break;
2302 }
2303 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002304
2305 mHwAvSyncIds.add(sessionId, value);
2306
2307 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2308 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2309 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002310 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002311 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002312 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002313 String8 keyValuePairs = param.toString();
2314 thread->setParameters(keyValuePairs);
2315 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2316 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002317 break;
2318 }
2319 }
2320
2321 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2322 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002323}
2324
Eric Laurent72e3f392015-05-20 14:43:50 -07002325status_t AudioFlinger::systemReady()
2326{
2327 Mutex::Autolock _l(mLock);
2328 ALOGI("%s", __FUNCTION__);
2329 if (mSystemReady) {
2330 ALOGW("%s called twice", __FUNCTION__);
2331 return NO_ERROR;
2332 }
2333 mSystemReady = true;
2334 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2335 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2336 thread->systemReady();
2337 }
2338 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2339 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2340 thread->systemReady();
2341 }
2342 return NO_ERROR;
2343}
2344
jiabin46a76fa2018-01-05 10:18:21 -08002345status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2346{
jiabin9ff780e2018-03-19 18:19:52 -07002347 AutoMutex lock(mHardwareLock);
2348 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2349 status_t status = dev->getMicrophones(microphones);
2350 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002351}
2352
Eric Laurentfa90e842014-10-17 18:12:31 -07002353// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2354void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2355{
2356 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2357 if (index >= 0) {
2358 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2359 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2360 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002361 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002362 String8 keyValuePairs = param.toString();
2363 thread->setParameters(keyValuePairs);
2364 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2365 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002366 }
2367}
2368
2369
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002370// ----------------------------------------------------------------------------
2371
Eric Laurent83b88082014-06-20 18:31:16 -07002372
Eric Laurent6acd1d42017-01-04 14:23:29 -08002373sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002374 audio_io_handle_t *output,
2375 audio_config_t *config,
2376 audio_devices_t deviceType,
2377 const String8& address,
2378 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002379{
jiabin43810402019-10-24 14:58:31 -07002380 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002381 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002382 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002383 }
2384
Eric Laurentcf2c0212014-07-25 16:20:43 -07002385 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002386 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2387 } else {
2388 // Audio Policy does not currently request a specific output handle.
2389 // If this is ever needed, see openInput_l() for example code.
2390 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2391 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002392 }
Eric Laurent83b88082014-06-20 18:31:16 -07002393
2394 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2395
Eric Laurent83b88082014-06-20 18:31:16 -07002396 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002397 // This if statement allows overriding the audio policy settings
2398 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2399 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2400 // Check only for Normal Mixing mode
2401 if (kEnableExtendedPrecision) {
2402 // Specify format (uncomment one below to choose)
2403 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2404 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2405 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2406 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002407 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002408 }
2409 if (kEnableExtendedChannels) {
2410 // Specify channel mask (uncomment one below to choose)
2411 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2412 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2413 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2414 }
Eric Laurent83b88082014-06-20 18:31:16 -07002415 }
2416
Phil Burk062e67a2015-02-11 13:40:50 -08002417 AudioStreamOut *outputStream = NULL;
2418 status_t status = outHwDev->openOutputStream(
2419 &outputStream,
2420 *output,
jiabin43810402019-10-24 14:58:31 -07002421 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002422 flags,
2423 config,
2424 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002425
2426 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002427
Phil Burk062e67a2015-02-11 13:40:50 -08002428 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002429 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2430 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002431 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002432 mMmapThreads.add(*output, thread);
2433 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2434 *output, thread.get());
2435 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002436 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002437 sp<PlaybackThread> thread;
2438 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002439 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002440 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2441 *output, thread.get());
2442 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2443 || !isValidPcmSinkFormat(config->format)
2444 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002445 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002446 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2447 *output, thread.get());
2448 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002449 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002450 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2451 *output, thread.get());
2452 }
2453 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002454 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002455 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002456 }
Eric Laurent83b88082014-06-20 18:31:16 -07002457 }
2458
2459 return 0;
2460}
2461
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462status_t AudioFlinger::openOutput(audio_module_handle_t module,
2463 audio_io_handle_t *output,
2464 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002465 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002466 uint32_t *latencyMs,
2467 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468{
jiabin43810402019-10-24 14:58:31 -07002469 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002470 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002471 this, module,
jiabin43810402019-10-24 14:58:31 -07002472 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002473 config->sample_rate,
2474 config->format,
2475 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002476 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477
jiabin43810402019-10-24 14:58:31 -07002478 audio_devices_t deviceType = device->type();
2479 const String8 address = String8(device->address().c_str());
2480
2481 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002482 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002483 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002484
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485 Mutex::Autolock _l(mLock);
2486
jiabin43810402019-10-24 14:58:31 -07002487 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002488 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002489 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2490 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2491 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492
Eric Laurent6acd1d42017-01-04 14:23:29 -08002493 // notify client processes of the new output creation
2494 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002495
Eric Laurent6acd1d42017-01-04 14:23:29 -08002496 // the first primary output opened designates the primary hw device
2497 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002498 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002499 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002500
Eric Laurent6acd1d42017-01-04 14:23:29 -08002501 AutoMutex lock(mHardwareLock);
2502 mHardwareStatus = AUDIO_HW_SET_MODE;
2503 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2504 mHardwareStatus = AUDIO_HW_IDLE;
2505 }
2506 } else {
2507 MmapThread *mmapThread = (MmapThread *)thread.get();
2508 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002509 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002510 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511 }
2512
Eric Laurentcf2c0212014-07-25 16:20:43 -07002513 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514}
2515
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002516audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2517 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002518{
2519 Mutex::Autolock _l(mLock);
2520 MixerThread *thread1 = checkMixerThread_l(output1);
2521 MixerThread *thread2 = checkMixerThread_l(output2);
2522
2523 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002524 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2525 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002526 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 }
2528
Glenn Kasteneeecb982016-02-26 10:44:04 -08002529 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002530 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 thread->addOutputTrack(thread2);
2532 mPlaybackThreads.add(id, thread);
2533 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002534 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 return id;
2536}
2537
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002538status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539{
Glenn Kastend96c5722012-04-25 13:44:49 -07002540 return closeOutput_nonvirtual(output);
2541}
2542
2543status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2544{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 // keep strong reference on the playback thread so that
2546 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002547 sp<PlaybackThread> playbackThread;
2548 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 {
2550 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002551 playbackThread = checkPlaybackThread_l(output);
2552 if (playbackThread != NULL) {
2553 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002554
Andy Hungdc099c22018-09-18 13:46:39 -07002555 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002556
Eric Laurent6acd1d42017-01-04 14:23:29 -08002557 if (playbackThread->type() == ThreadBase::MIXER) {
2558 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2559 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2560 DuplicatingThread *dupThread =
2561 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2562 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2563 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002564 }
2565 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002566
2567
Eric Laurent6acd1d42017-01-04 14:23:29 -08002568 mPlaybackThreads.removeItem(output);
2569 // save all effects to the default thread
2570 if (mPlaybackThreads.size()) {
2571 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2572 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002573 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002574 Mutex::Autolock _dl(dstThread->mLock);
2575 Mutex::Autolock _sl(playbackThread->mLock);
2576 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2577 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002578 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002579 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 }
2582 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 } else {
2584 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2585 if (mmapThread == 0) {
2586 return BAD_VALUE;
2587 }
Andy Hungdc099c22018-09-18 13:46:39 -07002588 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002589 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002590 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002592 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2593 ioDesc->mIoHandle = output;
2594 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002595 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002597 // The thread entity (active unit of execution) is no longer running here,
2598 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599
Eric Laurent6acd1d42017-01-04 14:23:29 -08002600 if (playbackThread != 0) {
2601 playbackThread->exit();
2602 if (!playbackThread->isDuplicating()) {
2603 closeOutputFinish(playbackThread);
2604 }
2605 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002606 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002607 mmapThread->exit();
2608 AudioStreamOut *out = mmapThread->clearOutput();
2609 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2610 // from now on thread->mOutput is NULL
2611 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 }
2613 return NO_ERROR;
2614}
2615
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002616void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002617{
2618 AudioStreamOut *out = thread->clearOutput();
2619 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2620 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002621 delete out;
2622}
2623
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002624void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002625{
2626 mPlaybackThreads.removeItem(thread->mId);
2627 thread->exit();
2628 closeOutputFinish(thread);
2629}
2630
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002631status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632{
2633 Mutex::Autolock _l(mLock);
2634 PlaybackThread *thread = checkPlaybackThread_l(output);
2635
2636 if (thread == NULL) {
2637 return BAD_VALUE;
2638 }
2639
Steve Block3856b092011-10-20 11:56:00 +01002640 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 thread->suspend();
2642
2643 return NO_ERROR;
2644}
2645
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002646status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647{
2648 Mutex::Autolock _l(mLock);
2649 PlaybackThread *thread = checkPlaybackThread_l(output);
2650
2651 if (thread == NULL) {
2652 return BAD_VALUE;
2653 }
2654
Steve Block3856b092011-10-20 11:56:00 +01002655 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656
2657 thread->restore();
2658
2659 return NO_ERROR;
2660}
2661
Eric Laurentcf2c0212014-07-25 16:20:43 -07002662status_t AudioFlinger::openInput(audio_module_handle_t module,
2663 audio_io_handle_t *input,
2664 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002665 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002666 const String8& address,
2667 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002668 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669{
Eric Laurent83b88082014-06-20 18:31:16 -07002670 Mutex::Autolock _l(mLock);
2671
Glenn Kastene7d66712015-03-05 13:46:52 -08002672 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002673 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002674 }
2675
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002676 sp<ThreadBase> thread = openInput_l(
2677 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002678
2679 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002680 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002681 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002682 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002684 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002685}
Dima Zavin799a70e2011-04-18 16:57:27 -07002686
Eric Laurent6acd1d42017-01-04 14:23:29 -08002687sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002688 audio_io_handle_t *input,
2689 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002690 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002691 const String8& address,
2692 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002693 audio_input_flags_t flags,
2694 audio_devices_t outputDevice,
2695 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002696{
Glenn Kastene7d66712015-03-05 13:46:52 -08002697 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002698 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002699 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002700 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002701 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002702
Glenn Kasteneeecb982016-02-26 10:44:04 -08002703 // Audio Policy can request a specific handle for hardware hotword.
2704 // The goal here is not to re-open an already opened input.
2705 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002706 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002707 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2708 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2709 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2710 return 0;
2711 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2712 // This should not happen in a transient state with current design.
2713 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2714 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002715 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002716
Eric Laurentcf2c0212014-07-25 16:20:43 -07002717 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002718 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002719 sp<StreamInHalInterface> inStream;
2720 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002721 *input, devices, &halconfig, flags, address.string(), source,
2722 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002723 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2724 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002725 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002726 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002727 halconfig.sample_rate,
2728 halconfig.format,
2729 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002730 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002731 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002733 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002734 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002735 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002736 audio_is_linear_pcm(config->format) &&
2737 audio_is_linear_pcm(halconfig.format) &&
2738 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002739 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2740 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002741 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002742 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002743 inStream.clear();
2744 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002745 *input, devices, &halconfig, flags, address.string(), source,
2746 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002747 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 }
2749
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002750 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002751 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002752 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2753 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002754 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002755 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002756 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2757 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002758 return thread;
2759 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002760 // Start record thread
2761 // RecordThread requires both input and output device indication to forward to audio
2762 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002763 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002764 mRecordThreads.add(*input, thread);
2765 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2766 return thread;
2767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 }
2769
Eric Laurentcf2c0212014-07-25 16:20:43 -07002770 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 return 0;
2772}
2773
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002774status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775{
Glenn Kastend96c5722012-04-25 13:44:49 -07002776 return closeInput_nonvirtual(input);
2777}
2778
2779status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2780{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 // keep strong reference on the record thread so that
2782 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002783 sp<RecordThread> recordThread;
2784 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785 {
2786 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002787 recordThread = checkRecordThread_l(input);
2788 if (recordThread != 0) {
2789 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790
Andy Hungdc099c22018-09-18 13:46:39 -07002791 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002792
Eric Laurent6acd1d42017-01-04 14:23:29 -08002793 // If we still have effect chains, it means that a client still holds a handle
2794 // on at least one effect. We must either move the chain to an existing thread with the
2795 // same session ID or put it aside in case a new record thread is opened for a
2796 // new capture on the same session
2797 sp<EffectChain> chain;
2798 {
2799 Mutex::Autolock _sl(recordThread->mLock);
2800 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2801 // Note: maximum one chain per record thread
2802 if (effectChains.size() != 0) {
2803 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002804 }
2805 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002806 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002807 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002808 // This should only happen in case of overlap between one thread tear down and the
2809 // creation of its replacement
2810 size_t i;
2811 for (i = 0; i < mRecordThreads.size(); i++) {
2812 sp<RecordThread> t = mRecordThreads.valueAt(i);
2813 if (t == recordThread) {
2814 continue;
2815 }
2816 if (t->hasAudioSession(chain->sessionId()) != 0) {
2817 Mutex::Autolock _l(t->mLock);
2818 ALOGV("closeInput() found thread %d for effect session %d",
2819 t->id(), chain->sessionId());
2820 t->addEffectChain_l(chain);
2821 break;
2822 }
2823 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002824 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002825 if (i == mRecordThreads.size()) {
2826 putOrphanEffectChain_l(chain);
2827 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002828 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 mRecordThreads.removeItem(input);
2830 } else {
2831 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2832 if (mmapThread == 0) {
2833 return BAD_VALUE;
2834 }
Andy Hungdc099c22018-09-18 13:46:39 -07002835 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002836 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002837 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002838 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2839 ioDesc->mIoHandle = input;
2840 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 }
Eric Laurent83b88082014-06-20 18:31:16 -07002842 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2843 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002844 if (recordThread != 0) {
2845 closeInputFinish(recordThread);
2846 } else if (mmapThread != 0) {
2847 mmapThread->exit();
2848 AudioStreamIn *in = mmapThread->clearInput();
2849 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2850 // from now on thread->mInput is NULL
2851 delete in;
2852 }
Eric Laurent83b88082014-06-20 18:31:16 -07002853 return NO_ERROR;
2854}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002856void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002857{
2858 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002859 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002860 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002861 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002862 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002863}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002865void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002866{
2867 mRecordThreads.removeItem(thread->mId);
2868 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869}
2870
Glenn Kastend2304db2014-02-03 07:40:31 -08002871status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872{
2873 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002874 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875
2876 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2877 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002878 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002879 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002880 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2881 mMmapThreads[i]->invalidateTracks(stream);
2882 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 return NO_ERROR;
2884}
2885
2886
Glenn Kasteneeecb982016-02-26 10:44:04 -08002887audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888{
Glenn Kasten9d003132016-04-06 14:38:09 -07002889 // This is a binder API, so a malicious client could pass in a bad parameter.
2890 // Check for that before calling the internal API nextUniqueId().
2891 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2892 ALOGE("newAudioUniqueId invalid use %d", use);
2893 return AUDIO_UNIQUE_ID_ALLOCATE;
2894 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002895 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896}
2897
Glenn Kastend848eb42016-03-08 13:42:11 -08002898void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002899{
2900 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002901 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002902 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002903 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2904 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002905 caller = pid;
2906 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002907
Eric Laurent021cf962014-05-13 10:18:14 -07002908 {
2909 Mutex::Autolock _cl(mClientLock);
2910 // Ignore requests received from processes not known as notification client. The request
2911 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2912 // called from a different pid leaving a stale session reference. Also we don't know how
2913 // to clear this reference if the client process dies.
2914 if (mNotificationClients.indexOfKey(caller) < 0) {
2915 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2916 return;
2917 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002918 }
2919
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002920 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002921 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002922 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002923 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2924 ref->mCnt++;
2925 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002926 return;
2927 }
2928 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002929 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2930 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002931}
2932
Glenn Kastend848eb42016-03-08 13:42:11 -08002933void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002934{
Eric Laurent6c796322019-04-09 14:13:17 -07002935 std::vector< sp<EffectModule> > removedEffects;
2936 {
2937 Mutex::Autolock _l(mLock);
2938 pid_t caller = IPCThreadState::self()->getCallingPid();
2939 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2940 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2941 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2942 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002943 }
Eric Laurent6c796322019-04-09 14:13:17 -07002944 size_t num = mAudioSessionRefs.size();
2945 for (size_t i = 0; i < num; i++) {
2946 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2947 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2948 ref->mCnt--;
2949 ALOGV(" decremented refcount to %d", ref->mCnt);
2950 if (ref->mCnt == 0) {
2951 mAudioSessionRefs.removeAt(i);
2952 delete ref;
2953 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2954 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2955 }
2956 goto Exit;
2957 }
2958 }
2959 // If the caller is audioserver it is likely that the session being released was acquired
2960 // on behalf of a process not in notification clients and we ignore the warning.
2961 ALOGW_IF(!isAudioServerUid(callerUid),
2962 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002963 }
Eric Laurent6c796322019-04-09 14:13:17 -07002964
2965Exit:
2966 for (auto& effect : removedEffects) {
2967 effect->updatePolicyState();
2968 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002969}
2970
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002971bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2972{
2973 size_t num = mAudioSessionRefs.size();
2974 for (size_t i = 0; i < num; i++) {
2975 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2976 if (ref->mSessionid == audioSession) {
2977 return true;
2978 }
2979 }
2980 return false;
2981}
2982
Eric Laurent6c796322019-04-09 14:13:17 -07002983std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002984
Steve Block3856b092011-10-20 11:56:00 +01002985 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002986
2987 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002988 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002989
2990 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2991 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002992 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002993 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2994 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002995 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07002996 chains.push(ec);
2997 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002998 }
2999 }
Eric Laurent6c796322019-04-09 14:13:17 -07003000
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003001 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3002 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003003 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003004 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3005 sp<EffectChain> ec = t->mEffectChains[j];
3006 chains.push(ec);
3007 }
3008 }
3009
Eric Laurent6c796322019-04-09 14:13:17 -07003010 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3011 sp<MmapThread> t = mMmapThreads.valueAt(i);
3012 Mutex::Autolock _l(t->mLock);
3013 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3014 sp<EffectChain> ec = t->mEffectChains[j];
3015 chains.push(ec);
3016 }
3017 }
3018
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003019 for (size_t i = 0; i < chains.size(); i++) {
3020 sp<EffectChain> ec = chains[i];
3021 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003022 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003023 if (t == 0) {
3024 continue;
3025 }
3026 size_t numsessionrefs = mAudioSessionRefs.size();
3027 bool found = false;
3028 for (size_t k = 0; k < numsessionrefs; k++) {
3029 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003030 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003031 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003032 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003033 found = true;
3034 break;
3035 }
3036 }
3037 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003038 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003039 // remove all effects from the chain
3040 while (ec->mEffects.size()) {
3041 sp<EffectModule> effect = ec->mEffects[0];
3042 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003043 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003044 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003045 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003046 }
Eric Laurent6c796322019-04-09 14:13:17 -07003047 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003048 }
3049 }
3050 }
Eric Laurent6c796322019-04-09 14:13:17 -07003051 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003052}
3053
Andy Hungdc099c22018-09-18 13:46:39 -07003054// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3055void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3056{
3057 audio_utils::FdToString fdToString;
3058 const int fd = fdToString.fd();
3059 if (fd >= 0) {
3060 thread->dump(fd, {} /* args */);
3061 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3062 }
3063}
3064
Glenn Kasteneeecb982016-02-26 10:44:04 -08003065// checkThread_l() must be called with AudioFlinger::mLock held
3066AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3067{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003068 ThreadBase *thread = checkMmapThread_l(ioHandle);
3069 if (thread == 0) {
3070 switch (audio_unique_id_get_use(ioHandle)) {
3071 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3072 thread = checkPlaybackThread_l(ioHandle);
3073 break;
3074 case AUDIO_UNIQUE_ID_USE_INPUT:
3075 thread = checkRecordThread_l(ioHandle);
3076 break;
3077 default:
3078 break;
3079 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003080 }
3081 return thread;
3082}
3083
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003085AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086{
Glenn Kastena1117922012-01-26 10:53:32 -08003087 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088}
3089
3090// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003091AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092{
3093 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003094 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095}
3096
3097// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003098AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099{
Glenn Kastena1117922012-01-26 10:53:32 -08003100 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101}
3102
Eric Laurent6acd1d42017-01-04 14:23:29 -08003103// checkMmapThread_l() must be called with AudioFlinger::mLock held
3104AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3105{
3106 return mMmapThreads.valueFor(io).get();
3107}
3108
3109
3110// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3111AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3112{
Eric Laurent7459b902017-04-19 18:10:41 -07003113 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003114 if (volumeInterface == nullptr) {
3115 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3116 if (mmapThread != nullptr) {
3117 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003118 MmapPlaybackThread *mmapPlaybackThread =
3119 static_cast<MmapPlaybackThread *>(mmapThread);
3120 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003121 }
3122 }
3123 }
3124 return volumeInterface;
3125}
3126
3127Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3128{
3129 Vector <VolumeInterface *> volumeInterfaces;
3130 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003131 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003132 }
3133 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3134 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003135 MmapPlaybackThread *mmapPlaybackThread =
3136 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3137 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003138 }
3139 }
3140 return volumeInterfaces;
3141}
3142
Glenn Kasteneeecb982016-02-26 10:44:04 -08003143audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144{
Glenn Kasten9d003132016-04-06 14:38:09 -07003145 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003146 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003147 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3148 for (int retry = 0; retry < maxRetries; retry++) {
3149 // The cast allows wraparound from max positive to min negative instead of abort
3150 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3151 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3152 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3153 // allow wrap by skipping 0 and -1 for session ids
3154 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3155 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3156 return (audio_unique_id_t) (base | use);
3157 }
3158 }
3159 // We have no way of recovering from wraparound
3160 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3161 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162}
3163
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003164AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003165{
3166 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3167 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003168 if(thread->isDuplicating()) {
3169 continue;
3170 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003171 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003172 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003173 return thread;
3174 }
3175 }
3176 return NULL;
3177}
3178
jiabinc52b1ff2019-10-31 17:20:42 -07003179DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003180{
3181 PlaybackThread *thread = primaryPlaybackThread_l();
3182
3183 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003184 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003185 }
3186
jiabinc52b1ff2019-10-31 17:20:42 -07003187 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003188}
3189
Glenn Kastena7335632016-06-09 17:09:53 -07003190AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3191{
3192 size_t minFrameCount = 0;
3193 PlaybackThread *minThread = NULL;
3194 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3195 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3196 if (!thread->isDuplicating()) {
3197 size_t frameCount = thread->frameCountHAL();
3198 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3199 (frameCount == minFrameCount && thread->hasFastMixer() &&
3200 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3201 minFrameCount = frameCount;
3202 minThread = thread;
3203 }
3204 }
3205 }
3206 return minThread;
3207}
3208
Eric Laurenta011e352012-03-29 15:51:43 -07003209sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003210 audio_session_t triggerSession,
3211 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003212 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003213 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003214{
3215 Mutex::Autolock _l(mLock);
3216
3217 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3218 status_t playStatus = NAME_NOT_FOUND;
3219 status_t recStatus = NAME_NOT_FOUND;
3220 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3221 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3222 if (playStatus == NO_ERROR) {
3223 return event;
3224 }
3225 }
3226 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3227 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3228 if (recStatus == NO_ERROR) {
3229 return event;
3230 }
3231 }
3232 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3233 mPendingSyncEvents.add(event);
3234 } else {
3235 ALOGV("createSyncEvent() invalid event %d", event->type());
3236 event.clear();
3237 }
3238 return event;
3239}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003240
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241// ----------------------------------------------------------------------------
3242// Effect management
3243// ----------------------------------------------------------------------------
3244
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003245sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3246 return mEffectsFactoryHal;
3247}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248
Glenn Kastenf587ba52012-01-26 16:25:10 -08003249status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250{
3251 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003252 if (mEffectsFactoryHal.get()) {
3253 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3254 } else {
3255 return -ENODEV;
3256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257}
3258
Glenn Kastenf587ba52012-01-26 16:25:10 -08003259status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260{
3261 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003262 if (mEffectsFactoryHal.get()) {
3263 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3264 } else {
3265 return -ENODEV;
3266 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267}
3268
Glenn Kasten5e92a782012-01-30 07:40:52 -08003269status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003270 const effect_uuid_t *pTypeUuid,
3271 uint32_t preferredTypeFlag,
3272 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003274 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3275 return BAD_VALUE;
3276 }
3277
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003279
3280 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003281 return -ENODEV;
3282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003284 status_t status = NO_ERROR;
3285 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3286 // If uuid is specified, request effect descriptor from that.
3287 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3288 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3289 // If uuid is not specified, look for an available implementation
3290 // of the required type instead.
3291
3292 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3293 effect_descriptor_t desc;
3294 desc.flags = 0; // prevent compiler warning
3295
3296 uint32_t numEffects = 0;
3297 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3298 if (status < 0) {
3299 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3300 return status;
3301 }
3302
3303 bool found = false;
3304 for (uint32_t i = 0; i < numEffects; i++) {
3305 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3306 if (status < 0) {
3307 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3308 continue;
3309 }
3310 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3311 // If matching type found save effect descriptor.
3312 found = true;
3313 *descriptor = desc;
3314
3315 // If there's no preferred flag or this descriptor matches the preferred
3316 // flag, success! If this descriptor doesn't match the preferred
3317 // flag, continue enumeration in case a better matching version of this
3318 // effect type is available. Note that this means if no effect with a
3319 // correct flag is found, the descriptor returned will correspond to the
3320 // last effect that at least had a matching type uuid (if any).
3321 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3322 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3323 break;
3324 }
3325 }
3326 }
3327
3328 if (!found) {
3329 status = NAME_NOT_FOUND;
3330 ALOGW("getEffectDescriptor(): Effect not found by type.");
3331 }
3332 } else {
3333 status = BAD_VALUE;
3334 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3335 }
3336 return status;
3337}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003339sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 effect_descriptor_t *pDesc,
3341 const sp<IEffectClient>& effectClient,
3342 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003343 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003344 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003345 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003346 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003347 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 status_t *status,
3349 int *id,
3350 int *enabled)
3351{
3352 status_t lStatus = NO_ERROR;
3353 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355
Eric Laurentb6436272016-12-07 19:24:50 -08003356 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003357 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003358 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3359 ALOGW_IF(pid != -1 && pid != callingPid,
3360 "%s uid %d pid %d tried to pass itself off as pid %d",
3361 __func__, callingUid, callingPid, pid);
3362 pid = callingPid;
3363 }
3364
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003365 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3366 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367
3368 if (pDesc == NULL) {
3369 lStatus = BAD_VALUE;
3370 goto Exit;
3371 }
3372
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003373 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003374 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003375 lStatus = NO_INIT;
3376 goto Exit;
3377 }
3378
Andy Hung6096dcd2019-03-13 13:20:30 -07003379 // check audio settings permission for global effects
3380 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3381 if (!settingsAllowed()) {
3382 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3383 lStatus = PERMISSION_DENIED;
3384 goto Exit;
3385 }
3386 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3387 if (!isAudioServerUid(callingUid)) {
3388 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3389 lStatus = PERMISSION_DENIED;
3390 goto Exit;
3391 }
3392
3393 if (io == AUDIO_IO_HANDLE_NONE) {
3394 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3395 lStatus = BAD_VALUE;
3396 goto Exit;
3397 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003398 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3399 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3400 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3401 lStatus = PERMISSION_DENIED;
3402 goto Exit;
3403 }
Eric Laurent94876032019-11-13 12:45:28 -08003404 if (io != AUDIO_IO_HANDLE_NONE) {
3405 ALOGE("%s: io handle should not be specified for device effect", __func__);
3406 lStatus = BAD_VALUE;
3407 goto Exit;
3408 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003409 } else {
3410 // general sessionId.
3411
3412 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3413 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3414 lStatus = BAD_VALUE;
3415 goto Exit;
3416 }
3417
3418 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3419 // to prevent creating an effect when one doesn't actually have track with that session?
3420 }
3421
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003423 // Get the full effect descriptor from the uuid/type.
3424 // If the session is the output mix, prefer an auxiliary effect,
3425 // otherwise no preference.
3426 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3427 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3428 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3429 if (lStatus < 0) {
3430 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3431 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003432 }
3433
3434 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003435 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3437 lStatus = INVALID_OPERATION;
3438 goto Exit;
3439 }
3440
Eric Laurent59255e42011-07-27 19:49:51 -07003441 // check recording permission for visualizer
3442 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003443 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003444 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003445 lStatus = PERMISSION_DENIED;
3446 goto Exit;
3447 }
3448
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003450 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003451 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003452 // if the output returned by getOutputForEffect() is removed before we lock the
3453 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3454 // and we will exit safely
3455 io = AudioSystem::getOutputForEffect(&desc);
3456 ALOGV("createEffect got output %d", io);
3457 }
3458
3459 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460
Eric Laurentb82e6b72019-11-22 17:25:04 -08003461 if (sessionId == AUDIO_SESSION_DEVICE) {
3462 sp<Client> client = registerPid(pid);
3463 ALOGV("%s device type %d address %s", __func__, device.mType, device.getAddress());
3464 handle = mDeviceEffectManager.createEffect_l(
3465 &desc, device, client, effectClient, mPatchPanel.patches_l(),
3466 enabled, &lStatus);
3467 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3468 // remove local strong reference to Client with mClientLock held
3469 Mutex::Autolock _cl(mClientLock);
3470 client.clear();
3471 } else {
3472 // handle must be valid here, but check again to be safe.
3473 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3474 }
3475 goto Register;
3476 }
3477
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 // If output is not specified try to find a matching audio session ID in one of the
3479 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003480 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3481 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003482 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3483 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003484 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003485 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003486 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3487 if (io == AUDIO_IO_HANDLE_NONE) {
3488 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003490 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003491 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003492 }
Andy Hung444bb552019-03-14 17:06:39 -07003493
3494 // If you wish to create a Record preprocessing AudioEffect in Java,
3495 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3496 // Otherwise it will fail when created on a Playback thread by legacy
3497 // handling below. Ditto with Mmap, the associated Mmap track must be created
3498 // before creating the AudioEffect or the io handle must be specified.
3499 //
3500 // Detect if the effect is created after an AudioRecord is destroyed.
3501 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3502 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3503 " for session %d no longer exists",
3504 __func__, desc.name, sessionId);
3505 lStatus = PERMISSION_DENIED;
3506 goto Exit;
3507 }
3508
3509 // Legacy handling of creating an effect on an expired or made-up
3510 // session id. We think that it is a Playback effect.
3511 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003512 // If no output thread contains the requested session ID, default to
3513 // first output. The effect chain will be moved to the correct output
3514 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003515 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003516 io = mPlaybackThreads.keyAt(0);
3517 }
Steve Block3856b092011-10-20 11:56:00 +01003518 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003519 } else if (checkPlaybackThread_l(io) != nullptr) {
3520 // allow only one effect chain per sessionId on mPlaybackThreads.
3521 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3522 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3523 if (io == checkIo) continue;
3524 const uint32_t sessionType =
3525 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3526 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3527 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3528 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3529 android_errorWriteLog(0x534e4554, "123237974");
3530 lStatus = BAD_VALUE;
3531 goto Exit;
3532 }
3533 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003534 }
3535 ThreadBase *thread = checkRecordThread_l(io);
3536 if (thread == NULL) {
3537 thread = checkPlaybackThread_l(io);
3538 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003539 thread = checkMmapThread_l(io);
3540 if (thread == NULL) {
3541 ALOGE("createEffect() unknown output thread");
3542 lStatus = BAD_VALUE;
3543 goto Exit;
3544 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003545 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003546 } else {
3547 // Check if one effect chain was awaiting for an effect to be created on this
3548 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003549 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003550 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003551 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003552 thread->addEffectChain_l(chain);
3553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003555
Eric Laurent021cf962014-05-13 10:18:14 -07003556 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003558 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003559 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003560 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003561 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003562 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003563 // remove local strong reference to Client with mClientLock held
3564 Mutex::Autolock _cl(mClientLock);
3565 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003566 } else {
3567 // handle must be valid here, but check again to be safe.
3568 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 }
3571
Eric Laurentb82e6b72019-11-22 17:25:04 -08003572Register:
Eric Laurent6c796322019-04-09 14:13:17 -07003573 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3574 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003575 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003576 if (effect != nullptr) {
3577 status_t rStatus = effect->updatePolicyState();
3578 if (rStatus != NO_ERROR) {
3579 lStatus = rStatus;
3580 }
3581 }
3582 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003583 handle.clear();
3584 }
3585
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003587 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 return handle;
3589}
3590
Glenn Kastend848eb42016-03-08 13:42:11 -08003591status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003592 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003593{
Steve Block3856b092011-10-20 11:56:00 +01003594 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003595 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003596 Mutex::Autolock _l(mLock);
3597 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003598 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003599 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 }
Eric Laurentde070132010-07-13 04:45:46 -07003601 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3602 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003603 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003604 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 }
Eric Laurentde070132010-07-13 04:45:46 -07003606 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3607 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003608 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003609 return BAD_VALUE;
3610 }
3611
3612 Mutex::Autolock _dl(dstThread->mLock);
3613 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003614 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615}
3616
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003617
3618void AudioFlinger::setEffectSuspended(int effectId,
3619 audio_session_t sessionId,
3620 bool suspended)
3621{
3622 Mutex::Autolock _l(mLock);
3623
3624 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3625 if (thread == nullptr) {
3626 return;
3627 }
3628 Mutex::Autolock _sl(thread->mLock);
3629 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3630 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3631}
3632
3633
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003634// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003635status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003636 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003637 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003638{
Steve Block3856b092011-10-20 11:56:00 +01003639 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003640 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003641
Eric Laurent59255e42011-07-27 19:49:51 -07003642 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003643 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003644 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003645 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003646 return INVALID_OPERATION;
3647 }
3648
Eric Laurent4c415062016-06-17 16:14:16 -07003649 // Check whether the destination thread and all effects in the chain are compatible
3650 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003651 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003652 " destination thread %p is not compatible with effects in the chain",
3653 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003654 return INVALID_OPERATION;
3655 }
3656
Eric Laurent39e94f82010-07-28 01:32:47 -07003657 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003658 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003659 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003660 // removed.
3661 srcThread->removeEffectChain_l(chain);
3662
3663 // transfer all effects one by one so that new effect chain is created on new thread with
3664 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003665 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003666 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003667 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003668 Vector< sp<EffectModule> > removed;
3669 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003670 while (effect != 0) {
3671 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003672 removed.add(effect);
3673 status = dstThread->addEffect_l(effect);
3674 if (status != NO_ERROR) {
3675 break;
3676 }
Eric Laurentec35a142011-10-05 17:42:25 -07003677 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3678 if (effect->state() == EffectModule::ACTIVE ||
3679 effect->state() == EffectModule::STOPPING) {
3680 effect->start();
3681 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003682 // if the move request is not received from audio policy manager, the effect must be
3683 // re-registered with the new strategy and output
3684 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003685 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003686 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003687 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003688 status = NO_INIT;
3689 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003690 }
3691 strategy = dstChain->strategy();
3692 }
Eric Laurentde070132010-07-13 04:45:46 -07003693 effect = chain->getEffectFromId_l(0);
3694 }
3695
Eric Laurent5baf2af2013-09-12 17:37:00 -07003696 if (status != NO_ERROR) {
3697 for (size_t i = 0; i < removed.size(); i++) {
3698 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003699 }
3700 }
3701
3702 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003703}
3704
Eric Laurent6c796322019-04-09 14:13:17 -07003705status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3706 const sp<PlaybackThread>& dstThread,
3707 sp<PlaybackThread> *srcThread)
3708{
3709 status_t status = NO_ERROR;
3710 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003711 sp<PlaybackThread> thread =
3712 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003713
3714 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3715 Mutex::Autolock _dl(dstThread->mLock);
3716 Mutex::Autolock _sl(thread->mLock);
3717 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3718 sp<EffectChain> dstChain;
3719 if (srcChain == 0) {
3720 return INVALID_OPERATION;
3721 }
3722
3723 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3724 if (effect == 0) {
3725 return INVALID_OPERATION;
3726 }
3727 thread->removeEffect_l(effect);
3728 status = dstThread->addEffect_l(effect);
3729 if (status != NO_ERROR) {
3730 thread->addEffect_l(effect);
3731 status = INVALID_OPERATION;
3732 goto Exit;
3733 }
3734
Eric Laurent6b446ce2019-12-13 10:56:31 -08003735 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003736 if (dstChain == 0) {
3737 thread->addEffect_l(effect);
3738 status = INVALID_OPERATION;
3739 }
3740
3741Exit:
3742 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3743 if (effect->state() == EffectModule::ACTIVE ||
3744 effect->state() == EffectModule::STOPPING) {
3745 effect->start();
3746 }
3747 }
3748
3749 if (status == NO_ERROR && srcThread != nullptr) {
3750 *srcThread = thread;
3751 }
3752 return status;
3753}
3754
Eric Laurent5baf2af2013-09-12 17:37:00 -07003755bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003756{
3757 if (mGlobalEffectEnableTime != 0 &&
3758 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3759 return true;
3760 }
3761
3762 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3763 sp<EffectChain> ec =
3764 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003765 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003766 return true;
3767 }
3768 }
3769 return false;
3770}
3771
Eric Laurent5baf2af2013-09-12 17:37:00 -07003772void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003773{
3774 Mutex::Autolock _l(mLock);
3775
3776 mGlobalEffectEnableTime = systemTime();
3777
3778 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3779 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3780 if (t->mType == ThreadBase::OFFLOAD) {
3781 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3782 }
3783 }
3784
3785}
3786
Eric Laurentaaa44472014-09-12 17:41:50 -07003787status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3788{
Eric Laurentd8365c52017-07-16 15:27:05 -07003789 // clear possible suspended state before parking the chain so that it starts in default state
3790 // when attached to a new record thread
3791 chain->setEffectSuspended_l(FX_IID_AEC, false);
3792 chain->setEffectSuspended_l(FX_IID_NS, false);
3793
Glenn Kastend848eb42016-03-08 13:42:11 -08003794 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003795 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003796 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003797 if (index >= 0) {
3798 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3799 return ALREADY_EXISTS;
3800 }
3801 mOrphanEffectChains.add(session, chain);
3802 return NO_ERROR;
3803}
3804
3805sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3806{
3807 sp<EffectChain> chain;
3808 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003809 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003810 if (index >= 0) {
3811 chain = mOrphanEffectChains.valueAt(index);
3812 mOrphanEffectChains.removeItemsAt(index);
3813 }
3814 return chain;
3815}
3816
3817bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3818{
3819 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003820 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003821 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003822 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003823 if (index >= 0) {
3824 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003825 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003826 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003827 mOrphanEffectChains.removeItemsAt(index);
3828 }
3829 return true;
3830 }
3831 return false;
3832}
3833
3834
Mathias Agopian65ab4712010-07-14 17:59:35 -07003835// ----------------------------------------------------------------------------
3836
3837status_t AudioFlinger::onTransact(
3838 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3839{
3840 return BnAudioFlinger::onTransact(code, data, reply, flags);
3841}
3842
Glenn Kasten63238ef2015-03-02 15:50:29 -08003843} // namespace android