blob: 6a2f0a6e0a24a1786f5a30c62ecfa37f377fc36c [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 Laurent6acd1d42017-01-04 14:23:29 -0800351 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700352 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700353 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700354 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800355 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700356 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800357 ret = NO_INIT;
358 }
359
360 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
361
Eric Laurentfc235202016-12-20 18:48:17 -0800362 return ret;
363}
364
jiabin57303cc2018-12-18 15:45:57 -0800365/* static */
366int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
367 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
368 if (evs != 0) {
369 int32_t ret;
370 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
371 if (status.isOk()) {
372 return ret;
373 }
374 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800375 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800376}
377
378/* static */
379void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
380 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
381 if (evs != 0) {
382 evs->onExternalVibrationStop(*externalVibration);
383 }
384}
385
Eric Laurentb82e6b72019-11-22 17:25:04 -0800386status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
387 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
388 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
389 if (audioHwDevice == nullptr) {
390 return NO_INIT;
391 }
392 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
393}
394
395status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
396 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
397 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
398 if (audioHwDevice == nullptr) {
399 return NO_INIT;
400 }
401 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
402}
403
Eric Laurenta4c5a552012-03-29 10:12:40 -0700404static const char * const audio_interfaces[] = {
405 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
406 AUDIO_HARDWARE_MODULE_ID_A2DP,
407 AUDIO_HARDWARE_MODULE_ID_USB,
408};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700409
Phil Burk062e67a2015-02-11 13:40:50 -0800410AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700411 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700412 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700413{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700414 // if module is 0, the request comes from an old policy manager and we should load
415 // well known modules
416 if (module == 0) {
417 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700418 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700419 loadHwModule_l(audio_interfaces[i]);
420 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700421 // then try to find a module supporting the requested device.
422 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
423 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700424 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
425 uint32_t supportedDevices;
426 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700427 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700428 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700429 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700430 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700431 } else {
432 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700433 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
434 if (audioHwDevice != NULL) {
435 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700436 }
437 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700438
Dima Zavin799a70e2011-04-18 16:57:27 -0700439 return NULL;
440}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441
Glenn Kasten0f11b512014-01-31 16:18:54 -0800442void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443{
444 const size_t SIZE = 256;
445 char buffer[SIZE];
446 String8 result;
447
448 result.append("Clients:\n");
449 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800450 sp<Client> client = mClients.valueAt(i).promote();
451 if (client != 0) {
452 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
453 result.append(buffer);
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");
458 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
459 snprintf(buffer, SIZE, " pid: %d\n", mNotificationClients.keyAt(i));
460 result.append(buffer);
461 }
462
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700463 result.append("Global session refs:\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800464 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700465 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
466 AudioSessionRef *r = mAudioSessionRefs[i];
Marco Nelissenb2208842014-02-07 14:00:50 -0800467 snprintf(buffer, SIZE, " %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700468 result.append(buffer);
469 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471}
472
473
Glenn Kasten0f11b512014-01-31 16:18:54 -0800474void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475{
476 const size_t SIZE = 256;
477 char buffer[SIZE];
478 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800479 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
John Grossman4ff14ba2012-02-08 16:37:41 -0800481 snprintf(buffer, SIZE, "Hardware status: %d\n"
482 "Standby Time mSec: %u\n",
483 hardwareStatus,
484 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 result.append(buffer);
486 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487}
488
Glenn Kasten0f11b512014-01-31 16:18:54 -0800489void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490{
491 const size_t SIZE = 256;
492 char buffer[SIZE];
493 String8 result;
494 snprintf(buffer, SIZE, "Permission Denial: "
495 "can't dump AudioFlinger from pid=%d, uid=%d\n",
496 IPCThreadState::self()->getCallingPid(),
497 IPCThreadState::self()->getCallingUid());
498 result.append(buffer);
499 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500}
501
Eric Laurent81784c32012-11-19 14:55:58 -0800502bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700504 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
505 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506}
507
508status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
509{
Glenn Kasten44deb052012-02-05 18:09:08 -0800510 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 dumpPermissionDenial(fd, args);
512 } else {
513 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800514 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 if (!hardwareLocked) {
516 String8 result(kHardwareLockedString);
517 write(fd, result.string(), result.size());
518 } else {
519 mHardwareLock.unlock();
520 }
521
Eric Tan7b651152018-07-13 10:17:19 -0700522 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700523
524 // failed to lock - AudioFlinger is probably deadlocked
525 if (!locked) {
526 String8 result(kDeadlockedString);
527 write(fd, result.string(), result.size());
528 }
529
Eric Laurent021cf962014-05-13 10:18:14 -0700530 bool clientLocked = dumpTryLock(mClientLock);
531 if (!clientLocked) {
532 String8 result(kClientLockedString);
533 write(fd, result.string(), result.size());
534 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700535
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700536 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700537 mEffectsFactoryHal->dumpEffects(fd);
538 } else {
539 String8 result(kNoEffectsFactory);
540 write(fd, result.string(), result.size());
541 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700542
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700544 if (clientLocked) {
545 mClientLock.unlock();
546 }
547
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 dumpInternals(fd, args);
549
550 // dump playback threads
551 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
552 mPlaybackThreads.valueAt(i)->dump(fd, args);
553 }
554
555 // dump record threads
556 for (size_t i = 0; i < mRecordThreads.size(); i++) {
557 mRecordThreads.valueAt(i)->dump(fd, args);
558 }
559
Eric Laurent6acd1d42017-01-04 14:23:29 -0800560 // dump mmap threads
561 for (size_t i = 0; i < mMmapThreads.size(); i++) {
562 mMmapThreads.valueAt(i)->dump(fd, args);
563 }
564
Eric Laurentaaa44472014-09-12 17:41:50 -0700565 // dump orphan effect chains
566 if (mOrphanEffectChains.size() != 0) {
567 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
568 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
569 mOrphanEffectChains.valueAt(i)->dump(fd, args);
570 }
571 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700572 // dump all hardware devs
573 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700574 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
575 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700577
Mikhail Naganov201369b2018-05-16 16:52:32 -0700578 mPatchPanel.dump(fd);
579
Eric Laurentb82e6b72019-11-22 17:25:04 -0800580 mDeviceEffectManager.dump(fd);
581
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700582 // dump external setParameters
583 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
584 dprintf(fd, "\n%s setParameters:\n", name);
585 logger.dump(fd, " " /* prefix */);
586 };
587 dumpLogger(mRejectedSetParameterLog, "Rejected");
588 dumpLogger(mAppSetParameterLog, "App");
589 dumpLogger(mSystemSetParameterLog, "System");
590
Andy Hunga8115dc2018-08-24 15:51:59 -0700591 // dump historical threads in the last 10 seconds
592 const std::string threadLog = mThreadLog.dumpToString(
593 "Historical Thread Log ", 0 /* lines */,
594 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
595 write(fd, threadLog.c_str(), threadLog.size());
596
rago3bd1c872016-09-26 12:58:14 -0700597 BUFLOG_RESET;
598
Glenn Kastend65d73c2012-06-22 17:21:07 -0700599 if (locked) {
600 mLock.unlock();
601 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800602
Andy Hung8946a282018-04-19 20:04:56 -0700603#ifdef TEE_SINK
604 // NBAIO_Tee dump is safe to call outside of AF lock.
605 NBAIO_Tee::dumpAll(fd, "_DUMP");
606#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800607 // append a copy of media.log here by forwarding fd to it, but don't attempt
608 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700609 if (sMediaLogServiceAsBinder != 0) {
610 dprintf(fd, "\nmedia.log:\n");
611 Vector<String16> args;
612 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800613 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700614
615 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700616 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700617 bool unreachableMemory = false;
618 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700619 if (arg == String16("-m")) {
620 dumpMem = true;
621 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700622 unreachableMemory = true;
623 }
624 }
625
Andy Hung07b745e2016-05-23 16:21:07 -0700626 if (dumpMem) {
627 dprintf(fd, "\nDumping memory:\n");
628 std::string s = dumpMemoryAddresses(100 /* limit */);
629 write(fd, s.c_str(), s.size());
630 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700631 if (unreachableMemory) {
632 dprintf(fd, "\nDumping unreachable memory:\n");
633 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700634 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700635 write(fd, s.c_str(), s.size());
636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 }
638 return NO_ERROR;
639}
640
Eric Laurent021cf962014-05-13 10:18:14 -0700641sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800642{
Eric Laurent021cf962014-05-13 10:18:14 -0700643 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800644 // If pid is already in the mClients wp<> map, then use that entry
645 // (for which promote() is always != 0), otherwise create a new entry and Client.
646 sp<Client> client = mClients.valueFor(pid).promote();
647 if (client == 0) {
648 client = new Client(this, pid);
649 mClients.add(pid, client);
650 }
651
652 return client;
653}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654
Glenn Kasten9e58b552013-01-18 15:09:48 -0800655sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
656{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700657 // If there is no memory allocated for logs, return a dummy writer that does nothing.
658 // Similarly if we can't contact the media.log service, also return a dummy writer.
659 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800660 return new NBLog::Writer();
661 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700662 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
663 // If allocation fails, consult the vector of previously unregistered writers
664 // and garbage-collect one or more them until an allocation succeeds
665 if (shared == 0) {
666 Mutex::Autolock _l(mUnregisteredWritersLock);
667 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
668 {
669 // Pick the oldest stale writer to garbage-collect
670 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
671 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700672 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700673 // Now the media.log remote reference to IMemory is gone. When our last local
674 // reference to IMemory also drops to zero at end of this block,
675 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
676 }
677 // Re-attempt the allocation
678 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
679 if (shared != 0) {
680 goto success;
681 }
682 }
683 // Even after garbage-collecting all old writers, there is still not enough memory,
684 // so return a dummy writer
685 return new NBLog::Writer();
686 }
687success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700688 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800689 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
690 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700691 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800692 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800693}
694
695void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
696{
Glenn Kasten685ef092013-02-04 08:15:34 -0800697 if (writer == 0) {
698 return;
699 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800700 sp<IMemory> iMemory(writer->getIMemory());
701 if (iMemory == 0) {
702 return;
703 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700704 // Rather than removing the writer immediately, append it to a queue of old writers to
705 // be garbage-collected later. This allows us to continue to view old logs for a while.
706 Mutex::Autolock _l(mUnregisteredWritersLock);
707 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800708}
709
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710// IAudioFlinger interface
711
Eric Laurent21da6472017-11-09 16:29:26 -0800712sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
713 CreateTrackOutput& output,
714 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715{
716 sp<PlaybackThread::Track> track;
717 sp<TrackHandle> trackHandle;
718 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800720 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800721 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800722 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723
Eric Laurent21da6472017-11-09 16:29:26 -0800724 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700725 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800726 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700727 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
728 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700729 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700730
Andy Hung4ef19fa2018-05-15 19:35:29 -0700731 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800732 ALOGW_IF(clientUid != callingUid,
733 "%s uid %d tried to pass itself off as %d",
734 __FUNCTION__, callingUid, clientUid);
735 clientUid = callingUid;
736 updatePid = true;
737 }
738 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700739 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800740 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800741 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700742 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800743 __func__, callingUid, callingPid, clientPid);
744 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700745 }
746
Eric Laurent21da6472017-11-09 16:29:26 -0800747 audio_session_t sessionId = input.sessionId;
748 if (sessionId == AUDIO_SESSION_ALLOCATE) {
749 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800750 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
751 lStatus = BAD_VALUE;
752 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800753 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800754
Eric Laurent21da6472017-11-09 16:29:26 -0800755 output.sessionId = sessionId;
756 output.outputId = AUDIO_IO_HANDLE_NONE;
757 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700758 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200759 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800760 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800761
762 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
763 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
764 goto Exit;
765 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800766 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
767 // but if someone uses binder directly they could bypass that and cause us to crash
768 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000769 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 lStatus = BAD_VALUE;
771 goto Exit;
772 }
773
Glenn Kasten53b5d092014-02-05 10:00:23 -0800774 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800775 if (!audio_is_output_channel(input.config.channel_mask)) {
776 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800777 lStatus = BAD_VALUE;
778 goto Exit;
779 }
780
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700781 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800782 if (!audio_is_valid_format(input.config.format)) {
783 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700784 lStatus = BAD_VALUE;
785 goto Exit;
786 }
787
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788 {
789 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800790 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800792 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 lStatus = BAD_VALUE;
794 goto Exit;
795 }
796
Eric Laurent21da6472017-11-09 16:29:26 -0800797 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798
Glenn Kastene848bd92014-03-13 15:00:32 -0700799 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800800 // check if an effect chain with the same session ID is present on another
801 // output thread and move it here.
802 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
803 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
804 if (mPlaybackThreads.keyAt(i) != output.outputId) {
805 uint32_t sessions = t->hasAudioSession(sessionId);
806 if (sessions & ThreadBase::EFFECT_SESSION) {
807 effectThread = t.get();
808 break;
Eric Laurentde070132010-07-13 04:45:46 -0700809 }
810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
Eric Laurent21da6472017-11-09 16:29:26 -0800812 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813
Eric Laurent21da6472017-11-09 16:29:26 -0800814 output.sampleRate = input.config.sample_rate;
815 output.frameCount = input.frameCount;
816 output.notificationFrameCount = input.notificationFrameCount;
817 output.flags = input.flags;
818
Eric Laurent42984412019-05-09 17:57:03 -0700819 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700820 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800821 &output.frameCount, &output.notificationFrameCount,
822 input.notificationsPerBuffer, input.speed,
823 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700824 callingPid, input.clientInfo.clientTid, clientUid,
825 &lStatus, portId);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800826 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700827 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700828
Eric Laurent21da6472017-11-09 16:29:26 -0800829 output.afFrameCount = thread->frameCount();
830 output.afSampleRate = thread->sampleRate();
831 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800832 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800833
Kevin Rocard153f92d2018-12-18 18:33:28 -0800834 if (lStatus == NO_ERROR) {
835 // Connect secondary outputs. Failure on a secondary output must not imped the primary
836 // Any secondary output setup failure will lead to a desync between the AP and AF until
837 // the track is destroyed.
838 TeePatches teePatches;
839 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
840 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
841 if (secondaryThread == NULL) {
842 ALOGE("no playback thread found for secondary output %d", output.outputId);
843 continue;
844 }
845
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100846 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
847 / thread->sampleRate();
848 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
849 / secondaryThread->sampleRate();
850 // If the secondary output has just been opened, the first secondaryThread write
851 // will not block as it will fill the empty startup buffer of the HAL,
852 // so a second sink buffer needs to be ready for the immediate next blocking write.
853 // Additionally, have a margin of one main thread buffer as the scheduling jitter
854 // can reorder the writes (eg if thread A&B have the same write intervale,
855 // the scheduler could schedule AB...BA)
856 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
857 // Total secondary output buffer must be at least as the read frames plus
858 // the margin of a few buffers on both sides in case the
859 // threads scheduling has some jitter.
860 // That value should not impact latency as the secondary track is started before
861 // its buffer is full, see frameCountToBeReady.
862 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
863 // The frameCount should also not be smaller than the secondary thread min frame
864 // count
865 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
866 [&] { Mutex::Autolock _l(secondaryThread->mLock);
867 return secondaryThread->latency_l(); }(),
868 secondaryThread->mNormalFrameCount,
869 secondaryThread->mSampleRate,
870 output.sampleRate,
871 input.speed);
872 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800873
874 using namespace std::chrono_literals;
875 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
876 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
877 output.sampleRate,
878 inChannelMask,
879 input.config.format,
880 frameCount,
881 NULL /* buffer */,
882 (size_t)0 /* bufferSize */,
883 AUDIO_INPUT_FLAG_DIRECT,
884 0ns /* timeout */);
885 status_t status = patchRecord->initCheck();
886 if (status != NO_ERROR) {
887 ALOGE("Secondary output patchRecord init failed: %d", status);
888 continue;
889 }
Andy Hungae22b482019-05-09 15:38:55 -0700890
891 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
892 // for fast usage: thread has fast mixer, sample rate matches, etc.;
893 // for now, we exclude fast tracks by removing the Fast flag.
894 const audio_output_flags_t outputFlags =
895 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800896 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
897 streamType,
898 output.sampleRate,
899 input.config.channel_mask,
900 input.config.format,
901 frameCount,
902 patchRecord->buffer(),
903 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700904 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100905 0ns /* timeout */,
906 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800907 status = patchTrack->initCheck();
908 if (status != NO_ERROR) {
909 ALOGE("Secondary output patchTrack init failed: %d", status);
910 continue;
911 }
912 teePatches.push_back({patchRecord, patchTrack});
913 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800914 // In case the downstream patchTrack on the secondaryThread temporarily outlives
915 // our created track, ensure the corresponding patchRecord is still alive.
916 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
917 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800918 }
919 track->setTeePatches(std::move(teePatches));
920 }
921
Eric Laurent39e94f82010-07-28 01:32:47 -0700922 // move effect chain to this output thread if an effect on same session was waiting
923 // for a track to be created
924 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700925 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700926 Mutex::Autolock _dl(thread->mLock);
927 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700928 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
929 effectThreadId = thread->id();
930 effectIds = thread->getEffectIds_l(sessionId);
931 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700932 }
Eric Laurenta011e352012-03-29 15:51:43 -0700933
934 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700935 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800936 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700937 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700938 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700939 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700940 } else {
941 mPendingSyncEvents[i]->cancel();
942 }
Eric Laurenta011e352012-03-29 15:51:43 -0700943 mPendingSyncEvents.removeAt(i);
944 i--;
945 }
946 }
947 }
Glenn Kastene198c362013-08-13 09:13:36 -0700948
Eric Laurent21da6472017-11-09 16:29:26 -0800949 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 }
Glenn Kastene198c362013-08-13 09:13:36 -0700951
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700952 if (lStatus != NO_ERROR) {
953 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700954 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700955 // Don't hold mClientLock when releasing the reference on the track as the
956 // destructor will acquire it.
957 {
958 Mutex::Autolock _cl(mClientLock);
959 client.clear();
960 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700962 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700963 }
964
Eric Laurent6c796322019-04-09 14:13:17 -0700965 // effectThreadId is not NONE if an effect chain corresponding to the track session
966 // was found on another thread and must be moved on this thread
967 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
968 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
969 }
970
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700971 // return handle to client
972 trackHandle = new TrackHandle(track);
973
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974Exit:
Eric Laurent21da6472017-11-09 16:29:26 -0800975 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700976 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -0800977 }
Glenn Kasten9156ef32013-08-06 15:39:08 -0700978 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 return trackHandle;
980}
981
Glenn Kasten2c073da2016-02-26 09:14:08 -0800982uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983{
984 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -0800985 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -0800987 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 return 0;
989 }
990 return thread->sampleRate();
991}
992
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800993audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994{
995 Mutex::Autolock _l(mLock);
996 PlaybackThread *thread = checkPlaybackThread_l(output);
997 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000998 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800999 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 }
1001 return thread->format();
1002}
1003
Glenn Kasten2c073da2016-02-26 09:14:08 -08001004size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005{
1006 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001007 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001009 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 return 0;
1011 }
Glenn Kasten58912562012-04-03 10:45:00 -07001012 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1013 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014 return thread->frameCount();
1015}
1016
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001017size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1018{
1019 Mutex::Autolock _l(mLock);
1020 ThreadBase *thread = checkThread_l(ioHandle);
1021 if (thread == NULL) {
1022 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1023 return 0;
1024 }
1025 return thread->frameCountHAL();
1026}
1027
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001028uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029{
1030 Mutex::Autolock _l(mLock);
1031 PlaybackThread *thread = checkPlaybackThread_l(output);
1032 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001033 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 return 0;
1035 }
1036 return thread->latency();
1037}
1038
1039status_t AudioFlinger::setMasterVolume(float value)
1040{
Eric Laurenta1884f92011-08-23 08:25:03 -07001041 status_t ret = initCheck();
1042 if (ret != NO_ERROR) {
1043 return ret;
1044 }
1045
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 // check calling permissions
1047 if (!settingsAllowed()) {
1048 return PERMISSION_DENIED;
1049 }
1050
Eric Laurenta4c5a552012-03-29 10:12:40 -07001051 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001052 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001053
John Grossmanee578c02012-07-23 17:05:46 -07001054 // Set master volume in the HALs which support it.
1055 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1056 AutoMutex lock(mHardwareLock);
1057 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001058
John Grossmanee578c02012-07-23 17:05:46 -07001059 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1060 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001061 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001062 }
John Grossmanee578c02012-07-23 17:05:46 -07001063 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065
John Grossmanee578c02012-07-23 17:05:46 -07001066 // Now set the master volume in each playback thread. Playback threads
1067 // assigned to HALs which do not have master volume support will apply
1068 // master volume during the mix operation. Threads with HALs which do
1069 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001070 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1071 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1072 continue;
1073 }
John Grossmanee578c02012-07-23 17:05:46 -07001074 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001075 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076
1077 return NO_ERROR;
1078}
1079
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001080status_t AudioFlinger::setMasterBalance(float balance)
1081{
1082 status_t ret = initCheck();
1083 if (ret != NO_ERROR) {
1084 return ret;
1085 }
1086
1087 // check calling permissions
1088 if (!settingsAllowed()) {
1089 return PERMISSION_DENIED;
1090 }
1091
1092 // check range
1093 if (isnan(balance) || fabs(balance) > 1.f) {
1094 return BAD_VALUE;
1095 }
1096
1097 Mutex::Autolock _l(mLock);
1098
1099 // short cut.
1100 if (mMasterBalance == balance) return NO_ERROR;
1101
1102 mMasterBalance = balance;
1103
1104 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1105 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1106 continue;
1107 }
1108 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1109 }
1110
1111 return NO_ERROR;
1112}
1113
Glenn Kastenf78aee72012-01-04 11:00:47 -08001114status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115{
Eric Laurenta1884f92011-08-23 08:25:03 -07001116 status_t ret = initCheck();
1117 if (ret != NO_ERROR) {
1118 return ret;
1119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120
1121 // check calling permissions
1122 if (!settingsAllowed()) {
1123 return PERMISSION_DENIED;
1124 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001125 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001126 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 return BAD_VALUE;
1128 }
1129
1130 { // scope for the lock
1131 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001132 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001134 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135 mHardwareStatus = AUDIO_HW_IDLE;
1136 }
1137
1138 if (NO_ERROR == ret) {
1139 Mutex::Autolock _l(mLock);
1140 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001141 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001142 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143 }
1144
1145 return ret;
1146}
1147
1148status_t AudioFlinger::setMicMute(bool state)
1149{
Eric Laurenta1884f92011-08-23 08:25:03 -07001150 status_t ret = initCheck();
1151 if (ret != NO_ERROR) {
1152 return ret;
1153 }
1154
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155 // check calling permissions
1156 if (!settingsAllowed()) {
1157 return PERMISSION_DENIED;
1158 }
1159
1160 AutoMutex lock(mHardwareLock);
1161 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2f035f52014-09-14 12:11:52 -07001162 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001163 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1164 status_t result = dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001165 if (result != NO_ERROR) {
1166 ret = result;
1167 }
1168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 mHardwareStatus = AUDIO_HW_IDLE;
1170 return ret;
1171}
1172
1173bool AudioFlinger::getMicMute() const
1174{
Eric Laurenta1884f92011-08-23 08:25:03 -07001175 status_t ret = initCheck();
1176 if (ret != NO_ERROR) {
1177 return false;
1178 }
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001179 bool mute = true;
Dima Zavinfce7a472011-04-19 22:30:36 -07001180 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001181 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001183 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001184 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1185 status_t result = dev->getMicMute(&state);
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001186 if (result == NO_ERROR) {
1187 mute = mute && state;
1188 }
1189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 mHardwareStatus = AUDIO_HW_IDLE;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001191
1192 return mute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193}
1194
Eric Laurent5ada82e2019-08-29 17:53:54 -07001195void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001196{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001197 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001198
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001199 AutoMutex lock(mLock);
1200 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001201 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001202 }
1203 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001204 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001205 }
1206}
1207
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208status_t AudioFlinger::setMasterMute(bool muted)
1209{
John Grossmand8f178d2012-07-20 14:51:35 -07001210 status_t ret = initCheck();
1211 if (ret != NO_ERROR) {
1212 return ret;
1213 }
1214
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215 // check calling permissions
1216 if (!settingsAllowed()) {
1217 return PERMISSION_DENIED;
1218 }
1219
John Grossmanee578c02012-07-23 17:05:46 -07001220 Mutex::Autolock _l(mLock);
1221 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001222
John Grossmanee578c02012-07-23 17:05:46 -07001223 // Set master mute in the HALs which support it.
1224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1225 AutoMutex lock(mHardwareLock);
1226 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001227
John Grossmanee578c02012-07-23 17:05:46 -07001228 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1229 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001230 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001231 }
John Grossmanee578c02012-07-23 17:05:46 -07001232 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001233 }
1234
John Grossmanee578c02012-07-23 17:05:46 -07001235 // Now set the master mute in each playback thread. Playback threads
1236 // assigned to HALs which do not have master mute support will apply master
1237 // mute during the mix operation. Threads with HALs which do support master
1238 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001239 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1240 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1241 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243
1244 return NO_ERROR;
1245}
1246
1247float AudioFlinger::masterVolume() const
1248{
Glenn Kasten98067102011-12-13 11:47:54 -08001249 Mutex::Autolock _l(mLock);
1250 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251}
1252
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001253status_t AudioFlinger::getMasterBalance(float *balance) const
1254{
1255 Mutex::Autolock _l(mLock);
1256 *balance = getMasterBalance_l();
1257 return NO_ERROR; // if called through binder, may return a transactional error
1258}
1259
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260bool AudioFlinger::masterMute() const
1261{
Glenn Kasten98067102011-12-13 11:47:54 -08001262 Mutex::Autolock _l(mLock);
1263 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264}
1265
John Grossman4ff14ba2012-02-08 16:37:41 -08001266float AudioFlinger::masterVolume_l() const
1267{
John Grossman4ff14ba2012-02-08 16:37:41 -08001268 return mMasterVolume;
1269}
1270
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001271float AudioFlinger::getMasterBalance_l() const
1272{
1273 return mMasterBalance;
1274}
1275
John Grossmand8f178d2012-07-20 14:51:35 -07001276bool AudioFlinger::masterMute_l() const
1277{
John Grossmanee578c02012-07-23 17:05:46 -07001278 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001279}
1280
Eric Laurent223fd5c2014-11-11 13:43:36 -08001281status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1282{
1283 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001284 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001285 return BAD_VALUE;
1286 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001287 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1288 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1289 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001290 return PERMISSION_DENIED;
1291 }
1292
1293 return NO_ERROR;
1294}
1295
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001296status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1297 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298{
1299 // check calling permissions
1300 if (!settingsAllowed()) {
1301 return PERMISSION_DENIED;
1302 }
1303
Eric Laurent223fd5c2014-11-11 13:43:36 -08001304 status_t status = checkStreamType(stream);
1305 if (status != NO_ERROR) {
1306 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 }
Eric Laurent98e38192018-02-15 18:31:53 -08001308 if (output == AUDIO_IO_HANDLE_NONE) {
1309 return BAD_VALUE;
1310 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001311 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1312 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313
1314 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001315 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1316 if (volumeInterface == NULL) {
1317 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 }
Eric Laurent98e38192018-02-15 18:31:53 -08001319 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320
1321 return NO_ERROR;
1322}
1323
Glenn Kastenfff6d712012-01-12 16:38:12 -08001324status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001325{
1326 // check calling permissions
1327 if (!settingsAllowed()) {
1328 return PERMISSION_DENIED;
1329 }
1330
Eric Laurent223fd5c2014-11-11 13:43:36 -08001331 status_t status = checkStreamType(stream);
1332 if (status != NO_ERROR) {
1333 return status;
1334 }
1335 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1336
1337 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001338 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001339 return BAD_VALUE;
1340 }
1341
Eric Laurent93575202011-01-18 18:39:02 -08001342 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001343 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001344 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1345 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1346 volumeInterfaces[i]->setStreamMute(stream, muted);
1347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348
1349 return NO_ERROR;
1350}
1351
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001352float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001354 status_t status = checkStreamType(stream);
1355 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356 return 0.0f;
1357 }
Eric Laurent98e38192018-02-15 18:31:53 -08001358 if (output == AUDIO_IO_HANDLE_NONE) {
1359 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360 }
1361
Eric Laurent98e38192018-02-15 18:31:53 -08001362 AutoMutex lock(mLock);
1363 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1364 if (volumeInterface == NULL) {
1365 return 0.0f;
1366 }
1367
1368 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369}
1370
Glenn Kastenfff6d712012-01-12 16:38:12 -08001371bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001373 status_t status = checkStreamType(stream);
1374 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375 return true;
1376 }
1377
Glenn Kasten6637baa2012-01-09 09:40:36 -08001378 AutoMutex lock(mLock);
1379 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380}
1381
Eric Laurent054d9d32015-04-24 08:48:48 -07001382
1383void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1384{
1385 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1386 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1387 }
1388}
1389
jiabinc52b1ff2019-10-31 17:20:42 -07001390void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1391{
1392 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1393 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1394 }
1395}
1396
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001397// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1398void AudioFlinger::forwardParametersToDownstreamPatches_l(
1399 audio_io_handle_t upStream, const String8& keyValuePairs,
1400 std::function<bool(const sp<PlaybackThread>&)> useThread)
1401{
1402 std::vector<PatchPanel::SoftwarePatch> swPatches;
1403 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1404 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1405 __func__, swPatches.size(), upStream);
1406 for (const auto& swPatch : swPatches) {
1407 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1408 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1409 downStream->setParameters(keyValuePairs);
1410 }
1411 }
1412}
1413
Eric Laurentf1047e82018-04-16 19:18:20 -07001414// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1415// Some keys are used for audio routing and audio path configuration and should be reserved for use
1416// by audio policy and audio flinger for functional, privacy and security reasons.
1417void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1418{
1419 static const String8 kReservedParameters[] = {
1420 String8(AudioParameter::keyRouting),
1421 String8(AudioParameter::keySamplingRate),
1422 String8(AudioParameter::keyFormat),
1423 String8(AudioParameter::keyChannels),
1424 String8(AudioParameter::keyFrameCount),
1425 String8(AudioParameter::keyInputSource),
1426 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001427 String8(AudioParameter::keyDeviceConnect),
1428 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001429 String8(AudioParameter::keyStreamSupportedFormats),
1430 String8(AudioParameter::keyStreamSupportedChannels),
1431 String8(AudioParameter::keyStreamSupportedSamplingRates),
1432 };
1433
Andy Hung4ef19fa2018-05-15 19:35:29 -07001434 if (isAudioServerUid(callingUid)) {
1435 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001436 }
1437
1438 AudioParameter param = AudioParameter(keyValuePairs);
1439 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001440 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001441 for (auto& key : kReservedParameters) {
1442 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001443 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001444 param.remove(key);
1445 }
1446 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001447 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1448 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001449 keyValuePairs = param.toString();
1450}
1451
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001452void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1453 size_t rejectedKVPSize, const String8& rejectedKVPs,
1454 uid_t callingUid) {
1455 auto prefix = String8::format("UID %5d", callingUid);
1456 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1457 if (rejectedKVPSize != 0) {
1458 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1459 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1460 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1461 } else {
1462 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1463 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1464 }
1465}
1466
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001467status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468{
Eric Laurentf1047e82018-04-16 19:18:20 -07001469 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1470 ioHandle, keyValuePairs.string(),
1471 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001472
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 // check calling permissions
1474 if (!settingsAllowed()) {
1475 return PERMISSION_DENIED;
1476 }
1477
Eric Laurentf1047e82018-04-16 19:18:20 -07001478 String8 filteredKeyValuePairs = keyValuePairs;
1479 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1480
1481 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1482
Glenn Kasten142f5192014-03-25 17:44:59 -07001483 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1484 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001485 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001486 // result will remain NO_INIT if no audio device is present
1487 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001488 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001489 AutoMutex lock(mHardwareLock);
1490 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1491 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001492 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001493 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001494 // return success if at least one audio device accepts the parameters as not all
1495 // HALs are requested to support all parameters. If no audio device supports the
1496 // requested parameters, the last error is reported.
1497 if (final_result != NO_ERROR) {
1498 final_result = result;
1499 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001500 }
1501 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001502 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001503 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001504 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001505 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001506 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1507 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001508 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001509 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001510 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001511 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001512 }
1513 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001514 String8 screenState;
1515 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001516 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001517 if (isOff != (AudioFlinger::mScreenState & 1)) {
1518 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001519 }
1520 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001521 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 }
1523
1524 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1525 // and the thread is exited once the lock is released
1526 sp<ThreadBase> thread;
1527 {
1528 Mutex::Autolock _l(mLock);
1529 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001530 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001532 if (thread == 0) {
1533 thread = checkMmapThread_l(ioHandle);
1534 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001535 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001536 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001537 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001538 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001539 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1540 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001541 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001542 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 }
1544 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001545 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001546 status_t result = thread->setParameters(filteredKeyValuePairs);
1547 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1548 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 }
1550 return BAD_VALUE;
1551}
1552
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001553String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001555 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1556 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557
Eric Laurenta4c5a552012-03-29 10:12:40 -07001558 Mutex::Autolock _l(mLock);
1559
Glenn Kasten142f5192014-03-25 17:44:59 -07001560 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001561 String8 out_s8;
1562
Dima Zavin799a70e2011-04-18 16:57:27 -07001563 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001564 String8 s;
1565 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001566 {
1567 AutoMutex lock(mHardwareLock);
1568 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001569 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1570 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001571 mHardwareStatus = AUDIO_HW_IDLE;
1572 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001573 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001574 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001575 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 }
1577
Eric Laurent6acd1d42017-01-04 14:23:29 -08001578 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1579 if (thread == NULL) {
1580 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1581 if (thread == NULL) {
1582 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1583 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001584 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001585 }
1586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001588 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589}
1590
Glenn Kastendd8104c2012-07-02 12:42:44 -07001591size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1592 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593{
Eric Laurenta1884f92011-08-23 08:25:03 -07001594 status_t ret = initCheck();
1595 if (ret != NO_ERROR) {
1596 return 0;
1597 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001598 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001599 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001600 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001601 return 0;
1602 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001603
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001604 AutoMutex lock(mHardwareLock);
1605 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001606
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001607 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001608 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1609 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1610 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1611 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1612 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1613
1614 std::vector<audio_format_t> formats = {format};
1615 if (format != AUDIO_FORMAT_PCM_16_BIT)
1616 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1617
1618 std::vector<uint32_t> sampleRates = {sampleRate};
1619 static const uint32_t SR_44100 = 44100;
1620 static const uint32_t SR_48000 = 48000;
1621
1622 if (sampleRate != SR_48000)
1623 sampleRates.push_back(SR_48000);
1624 if (sampleRate != SR_44100)
1625 sampleRates.push_back(SR_44100);
1626
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001627 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001628
Robin Lee9899ff72019-12-24 22:02:08 +01001629 // Change parameters of the configuration each iteration until we find a
1630 // configuration that the device will support.
1631 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001632 for (auto testChannelMask : channelMasks) {
1633 config.channel_mask = testChannelMask;
1634 for (auto testFormat : formats) {
1635 config.format = testFormat;
1636 for (auto testSampleRate : sampleRates) {
1637 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001638
Judy Hsiaoabab5222019-11-09 18:14:58 +08001639 size_t bytes = 0;
1640 status_t result = dev->getInputBufferSize(&config, &bytes);
1641 if (result != OK || bytes == 0) {
1642 continue;
1643 }
1644
1645 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1646 config.format != format) {
1647 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1648 uint32_t srcChannelCount =
1649 audio_channel_count_from_in_mask(config.channel_mask);
1650 size_t srcFrames =
1651 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1652 size_t dstFrames = destinationFramesPossible(
1653 srcFrames, config.sample_rate, sampleRate);
1654 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1655 }
1656 return bytes;
1657 }
1658 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001659 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001660
1661 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1662 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1663 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664}
1665
Glenn Kasten5f972c02014-01-13 09:59:31 -08001666uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668 Mutex::Autolock _l(mLock);
1669
1670 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1671 if (recordThread != NULL) {
1672 return recordThread->getInputFramesLost();
1673 }
1674 return 0;
1675}
1676
1677status_t AudioFlinger::setVoiceVolume(float value)
1678{
Eric Laurenta1884f92011-08-23 08:25:03 -07001679 status_t ret = initCheck();
1680 if (ret != NO_ERROR) {
1681 return ret;
1682 }
1683
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 // check calling permissions
1685 if (!settingsAllowed()) {
1686 return PERMISSION_DENIED;
1687 }
1688
1689 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001690 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001691 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001692 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 mHardwareStatus = AUDIO_HW_IDLE;
1694
1695 return ret;
1696}
1697
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001698status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001699 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 Mutex::Autolock _l(mLock);
1702
1703 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1704 if (playbackThread != NULL) {
1705 return playbackThread->getRenderPosition(halFrames, dspFrames);
1706 }
1707
1708 return BAD_VALUE;
1709}
1710
1711void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1712{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001714 if (client == 0) {
1715 return;
1716 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001717 pid_t pid = IPCThreadState::self()->getCallingPid();
Eric Laurent021cf962014-05-13 10:18:14 -07001718 {
1719 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001720 if (mNotificationClients.indexOfKey(pid) < 0) {
1721 sp<NotificationClient> notificationClient = new NotificationClient(this,
1722 client,
1723 pid);
1724 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725
Eric Laurent021cf962014-05-13 10:18:14 -07001726 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727
Marco Nelissen06b46062014-11-14 07:58:25 -08001728 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001729 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001730 }
1731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732
Eric Laurent021cf962014-05-13 10:18:14 -07001733 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001734 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001735 // the config change is always sent from playback or record threads to avoid deadlock
1736 // with AudioSystem::gLock
1737 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001738 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001741 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001742 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 }
1744}
1745
1746void AudioFlinger::removeNotificationClient(pid_t pid)
1747{
Eric Laurent6c796322019-04-09 14:13:17 -07001748 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001749 {
Eric Laurent6c796322019-04-09 14:13:17 -07001750 Mutex::Autolock _l(mLock);
1751 {
1752 Mutex::Autolock _cl(mClientLock);
1753 mNotificationClients.removeItem(pid);
1754 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001755
Eric Laurent6c796322019-04-09 14:13:17 -07001756 ALOGV("%d died, releasing its sessions", pid);
1757 size_t num = mAudioSessionRefs.size();
1758 bool removed = false;
1759 for (size_t i = 0; i < num; ) {
1760 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1761 ALOGV(" pid %d @ %zu", ref->mPid, i);
1762 if (ref->mPid == pid) {
1763 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1764 mAudioSessionRefs.removeAt(i);
1765 delete ref;
1766 removed = true;
1767 num--;
1768 } else {
1769 i++;
1770 }
1771 }
1772 if (removed) {
1773 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001774 }
1775 }
Eric Laurent6c796322019-04-09 14:13:17 -07001776 for (auto& effect : removedEffects) {
1777 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001778 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779}
1780
Eric Laurent73e26b62015-04-27 16:55:58 -07001781void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001782 const sp<AudioIoDescriptor>& ioDesc,
1783 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784{
Eric Laurent021cf962014-05-13 10:18:14 -07001785 Mutex::Autolock _l(mClientLock);
1786 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001788 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1789 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 }
1792}
1793
Eric Laurent021cf962014-05-13 10:18:14 -07001794// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795void AudioFlinger::removeClient_l(pid_t pid)
1796{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001797 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001798 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 mClients.removeItem(pid);
1800}
1801
Eric Laurent717e1282012-06-29 16:36:52 -07001802// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001803sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1804 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001805{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001806 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001807
1808 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001809 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001810 ALOG_ASSERT(thread == 0);
1811 thread = mPlaybackThreads.valueAt(i);
1812 }
1813 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001814 if (thread != nullptr) {
1815 return thread;
1816 }
1817 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1818 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1819 ALOG_ASSERT(thread == 0);
1820 thread = mRecordThreads.valueAt(i);
1821 }
1822 }
1823 if (thread != nullptr) {
1824 return thread;
1825 }
1826 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1827 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1828 ALOG_ASSERT(thread == 0);
1829 thread = mMmapThreads.valueAt(i);
1830 }
1831 }
Eric Laurent717e1282012-06-29 16:36:52 -07001832 return thread;
1833}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836
1837// ----------------------------------------------------------------------------
1838
1839AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1840 : RefBase(),
1841 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001842 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843{
Andy Hung6f248bb2018-01-23 14:04:37 -08001844 mMemoryDealer = new MemoryDealer(
1845 audioFlinger->getClientSharedHeapSize(),
1846 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Eric Laurent021cf962014-05-13 10:18:14 -07001849// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850AudioFlinger::Client::~Client()
1851{
1852 mAudioFlinger->removeClient_l(mPid);
1853}
1854
Glenn Kasten435dbe62012-01-30 10:15:48 -08001855sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856{
1857 return mMemoryDealer;
1858}
1859
1860// ----------------------------------------------------------------------------
1861
1862AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1863 const sp<IAudioFlingerClient>& client,
1864 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001865 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866{
1867}
1868
1869AudioFlinger::NotificationClient::~NotificationClient()
1870{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871}
1872
Glenn Kasten0f11b512014-01-31 16:18:54 -08001873void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874{
1875 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001876 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877}
1878
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001879// ----------------------------------------------------------------------------
1880AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1881 : mPendingRequests(false) {}
1882
1883
1884void AudioFlinger::MediaLogNotifier::requestMerge() {
1885 AutoMutex _l(mMutex);
1886 mPendingRequests = true;
1887 mCond.signal();
1888}
1889
1890bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001891 // Should already have been checked, but just in case
1892 if (sMediaLogService == 0) {
1893 return false;
1894 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001895 // Wait until there are pending requests
1896 {
1897 AutoMutex _l(mMutex);
1898 mPendingRequests = false; // to ignore past requests
1899 while (!mPendingRequests) {
1900 mCond.wait(mMutex);
1901 // TODO may also need an exitPending check
1902 }
1903 mPendingRequests = false;
1904 }
1905 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001906 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001907 usleep(kPostTriggerSleepPeriod);
1908 return true;
1909}
1910
1911void AudioFlinger::requestLogMerge() {
1912 mMediaLogNotifier->requestMerge();
1913}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914
1915// ----------------------------------------------------------------------------
1916
Eric Laurentf14db3c2017-12-08 14:20:36 -08001917sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1918 CreateRecordOutput& output,
1919 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920{
1921 sp<RecordThread::RecordTrack> recordTrack;
1922 sp<RecordHandle> recordHandle;
1923 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001925 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001926 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927
Eric Laurentf14db3c2017-12-08 14:20:36 -08001928 output.cblk.clear();
1929 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001930 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001931
Eric Laurentf14db3c2017-12-08 14:20:36 -08001932 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001933 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001934 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001935 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001936 ALOGW_IF(clientUid != callingUid,
1937 "%s uid %d tried to pass itself off as %d",
1938 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001939 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001940 updatePid = true;
1941 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001942 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001943 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001944 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001945 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001946 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001947 __func__, callingUid, callingPid, clientPid);
1948 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001949 }
1950
Andy Hung6770c6f2015-04-07 13:43:36 -07001951 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001952 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1953 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001954 lStatus = BAD_VALUE;
1955 goto Exit;
1956 }
1957
Glenn Kasten53b5d092014-02-05 10:00:23 -08001958 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001959 if (!audio_is_input_channel(input.config.channel_mask)) {
1960 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001961 lStatus = BAD_VALUE;
1962 goto Exit;
1963 }
1964
Eric Laurentf14db3c2017-12-08 14:20:36 -08001965 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1966 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1967 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1968 lStatus = BAD_VALUE;
1969 goto Exit;
1970 }
1971
1972 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001973 output.selectedDeviceId = input.selectedDeviceId;
1974 output.flags = input.flags;
1975
1976 client = registerPid(clientPid);
1977
1978 // Not a conventional loop, but a retry loop for at most two iterations total.
1979 // Try first maybe with FAST flag then try again without FAST flag if that fails.
1980 // Exits loop via break on no error of got exit on error
1981 // The sp<> references will be dropped when re-entering scope.
1982 // The lack of indentation is deliberate, to reduce code churn and ease merges.
1983 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08001984 // release previously opened input if retrying.
1985 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
1986 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08001987 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08001988 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08001989 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001990 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08001991 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001992 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001993 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001994 sessionId,
1995 // FIXME compare to AudioTrack
1996 clientPid,
1997 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08001998 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08001999 &input.config,
2000 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002001 if (lStatus != NO_ERROR) {
2002 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2003 goto Exit;
2004 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002005
Glenn Kasten05997e22014-03-13 15:08:33 -07002006 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002008 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07002010 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 lStatus = BAD_VALUE;
2012 goto Exit;
2013 }
2014
Eric Laurentf14db3c2017-12-08 14:20:36 -08002015 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016
Eric Laurentf14db3c2017-12-08 14:20:36 -08002017 output.sampleRate = input.config.sample_rate;
2018 output.frameCount = input.frameCount;
2019 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002020
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002021 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002022 input.config.format, input.config.channel_mask,
2023 &output.frameCount, sessionId,
2024 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002025 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002026 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002027 &lStatus, portId,
2028 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002029 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002030
Eric Laurentf14db3c2017-12-08 14:20:36 -08002031 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2032 // audio policy manager without FAST constraint
2033 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002034 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002035 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002036
2037 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002038 goto Exit;
2039 }
2040
2041 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2042 // session and move it to this thread.
2043 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2044 if (chain != 0) {
2045 Mutex::Autolock _l(thread->mLock);
2046 thread->addEffectChain_l(chain);
2047 }
2048 break;
2049 }
2050 // End of retry loop.
2051 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 }
Glenn Kastene198c362013-08-13 09:13:36 -07002053
Eric Laurentf14db3c2017-12-08 14:20:36 -08002054 output.cblk = recordTrack->getCblk();
2055 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002056 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002057
2058 // return handle to client
2059 recordHandle = new RecordHandle(recordTrack);
2060
2061Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002062 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002063 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002064 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002065 // Don't hold mClientLock when releasing the reference on the track as the
2066 // destructor will acquire it.
2067 {
2068 Mutex::Autolock _cl(mClientLock);
2069 client.clear();
2070 }
Eric Laurent896c9672017-12-08 14:08:45 -08002071 recordTrack.clear();
2072 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002073 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002074 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075 }
2076
Glenn Kasten9156ef32013-08-06 15:39:08 -07002077 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 return recordHandle;
2079}
2080
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002081
2082
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083// ----------------------------------------------------------------------------
2084
Eric Laurenta4c5a552012-03-29 10:12:40 -07002085audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2086{
Eric Laurent44622db2014-08-01 19:00:33 -07002087 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002088 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002089 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002090 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002091 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002092 }
2093 Mutex::Autolock _l(mLock);
2094 return loadHwModule_l(name);
2095}
2096
2097// loadHwModule_l() must be called with AudioFlinger::mLock held
2098audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2099{
2100 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2101 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2102 ALOGW("loadHwModule() module %s already loaded", name);
2103 return mAudioHwDevs.keyAt(i);
2104 }
2105 }
2106
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002107 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002108
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002109 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002110 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002111 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002112 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002113 }
2114
2115 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002116 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002117 mHardwareStatus = AUDIO_HW_IDLE;
2118 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002119 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002120 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002121 }
2122
John Grossmanee578c02012-07-23 17:05:46 -07002123 // Check and cache this HAL's level of support for master mute and master
2124 // volume. If this is the first HAL opened, and it supports the get
2125 // methods, use the initial values provided by the HAL as the current
2126 // master mute and volume settings.
2127
2128 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2129 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002130 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002131
2132 if (0 == mAudioHwDevs.size()) {
2133 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002134 float mv;
2135 if (OK == dev->getMasterVolume(&mv)) {
2136 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002137 }
2138
2139 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002140 bool mm;
2141 if (OK == dev->getMasterMute(&mm)) {
2142 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002143 }
2144 }
2145
Eric Laurenta4c5a552012-03-29 10:12:40 -07002146 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002147 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002148 flags = static_cast<AudioHwDevice::Flags>(flags |
2149 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2150 }
2151
2152 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002153 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002154 flags = static_cast<AudioHwDevice::Flags>(flags |
2155 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2156 }
2157
Eric Laurenta4c5a552012-03-29 10:12:40 -07002158 mHardwareStatus = AUDIO_HW_IDLE;
2159 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002160 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002161 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2162 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2163 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002164
Glenn Kastena13cde92016-03-28 15:26:02 -07002165 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002166 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002167
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002168 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002169
2170 return handle;
2171
2172}
2173
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002174// ----------------------------------------------------------------------------
2175
Glenn Kasten3b16c762012-11-14 08:44:39 -08002176uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002177{
2178 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002179 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002180 return thread != NULL ? thread->sampleRate() : 0;
2181}
2182
Glenn Kastene33054e2012-11-14 12:54:39 -08002183size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002184{
2185 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002186 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002187 return thread != NULL ? thread->frameCountHAL() : 0;
2188}
2189
2190// ----------------------------------------------------------------------------
2191
Andy Hung6f248bb2018-01-23 14:04:37 -08002192status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002193{
2194 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002195 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002196 return PERMISSION_DENIED;
2197 }
2198 Mutex::Autolock _l(mLock);
2199 if (mIsDeviceTypeKnown) {
2200 return INVALID_OPERATION;
2201 }
2202 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002203 mTotalMemory = totalMemory;
2204 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2205 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2206 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2207 // though actual setting is determined through device configuration.
2208 constexpr int64_t GB = 1024 * 1024 * 1024;
2209 mClientSharedHeapSize =
2210 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2211 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2212 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2213 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2214 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002215 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002216
2217 // TODO: Cache the client shared heap size in a persistent property.
2218 // It's possible that a native process or Java service or app accesses audioserver
2219 // after it is registered by system server, but before AudioService updates
2220 // the memory info. This would occur immediately after boot or an audioserver
2221 // crash and restore. Before update from AudioService, the client would get the
2222 // minimum heap size.
2223
2224 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2225 (isLowRamDevice ? "true" : "false"),
2226 (long long)mTotalMemory,
2227 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002228 return NO_ERROR;
2229}
2230
Andy Hung6f248bb2018-01-23 14:04:37 -08002231size_t AudioFlinger::getClientSharedHeapSize() const
2232{
2233 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2234 if (heapSizeInBytes != 0) { // read-only property overrides all.
2235 return heapSizeInBytes;
2236 }
2237 return mClientSharedHeapSize;
2238}
2239
Mikhail Naganovdea53042018-04-26 13:10:21 -07002240status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2241{
2242 ALOGV(__func__);
2243
2244 audio_module_handle_t module;
2245 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2246 module = config->ext.device.hw_module;
2247 } else {
2248 module = config->ext.mix.hw_module;
2249 }
2250
2251 Mutex::Autolock _l(mLock);
2252 ssize_t index = mAudioHwDevs.indexOfKey(module);
2253 if (index < 0) {
2254 ALOGW("%s() bad hw module %d", __func__, module);
2255 return BAD_VALUE;
2256 }
2257
2258 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2259 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2260}
2261
Eric Laurent93c3d412014-08-01 14:48:35 -07002262audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2263{
2264 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002265
2266 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2267 if (index >= 0) {
2268 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2269 mHwAvSyncIds.valueAt(index), sessionId);
2270 return mHwAvSyncIds.valueAt(index);
2271 }
2272
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002273 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002274 if (dev == NULL) {
2275 return AUDIO_HW_SYNC_INVALID;
2276 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002277 String8 reply;
2278 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002279 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002280 param = AudioParameter(reply);
2281 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002282
2283 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002284 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002285 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2286 return AUDIO_HW_SYNC_INVALID;
2287 }
2288
2289 // allow only one session for a given HW A/V sync ID.
2290 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2291 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2292 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2293 value, mHwAvSyncIds.keyAt(i));
2294 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002295 break;
2296 }
2297 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002298
2299 mHwAvSyncIds.add(sessionId, value);
2300
2301 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2302 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2303 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002304 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002305 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002306 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002307 String8 keyValuePairs = param.toString();
2308 thread->setParameters(keyValuePairs);
2309 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2310 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002311 break;
2312 }
2313 }
2314
2315 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2316 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002317}
2318
Eric Laurent72e3f392015-05-20 14:43:50 -07002319status_t AudioFlinger::systemReady()
2320{
2321 Mutex::Autolock _l(mLock);
2322 ALOGI("%s", __FUNCTION__);
2323 if (mSystemReady) {
2324 ALOGW("%s called twice", __FUNCTION__);
2325 return NO_ERROR;
2326 }
2327 mSystemReady = true;
2328 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2329 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2330 thread->systemReady();
2331 }
2332 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2333 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2334 thread->systemReady();
2335 }
2336 return NO_ERROR;
2337}
2338
jiabin46a76fa2018-01-05 10:18:21 -08002339status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2340{
jiabin9ff780e2018-03-19 18:19:52 -07002341 AutoMutex lock(mHardwareLock);
2342 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2343 status_t status = dev->getMicrophones(microphones);
2344 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002345}
2346
Eric Laurentfa90e842014-10-17 18:12:31 -07002347// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2348void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2349{
2350 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2351 if (index >= 0) {
2352 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2353 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2354 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002355 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002356 String8 keyValuePairs = param.toString();
2357 thread->setParameters(keyValuePairs);
2358 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2359 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002360 }
2361}
2362
2363
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002364// ----------------------------------------------------------------------------
2365
Eric Laurent83b88082014-06-20 18:31:16 -07002366
Eric Laurent6acd1d42017-01-04 14:23:29 -08002367sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002368 audio_io_handle_t *output,
2369 audio_config_t *config,
2370 audio_devices_t deviceType,
2371 const String8& address,
2372 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002373{
jiabin43810402019-10-24 14:58:31 -07002374 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002375 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002376 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002377 }
2378
Eric Laurentcf2c0212014-07-25 16:20:43 -07002379 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002380 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2381 } else {
2382 // Audio Policy does not currently request a specific output handle.
2383 // If this is ever needed, see openInput_l() for example code.
2384 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2385 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002386 }
Eric Laurent83b88082014-06-20 18:31:16 -07002387
2388 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2389
Eric Laurent83b88082014-06-20 18:31:16 -07002390 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002391 // This if statement allows overriding the audio policy settings
2392 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2393 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2394 // Check only for Normal Mixing mode
2395 if (kEnableExtendedPrecision) {
2396 // Specify format (uncomment one below to choose)
2397 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2398 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2399 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2400 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002401 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002402 }
2403 if (kEnableExtendedChannels) {
2404 // Specify channel mask (uncomment one below to choose)
2405 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2406 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2407 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2408 }
Eric Laurent83b88082014-06-20 18:31:16 -07002409 }
2410
Phil Burk062e67a2015-02-11 13:40:50 -08002411 AudioStreamOut *outputStream = NULL;
2412 status_t status = outHwDev->openOutputStream(
2413 &outputStream,
2414 *output,
jiabin43810402019-10-24 14:58:31 -07002415 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002416 flags,
2417 config,
2418 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002419
2420 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002421
Phil Burk062e67a2015-02-11 13:40:50 -08002422 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002423 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2424 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002425 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002426 mMmapThreads.add(*output, thread);
2427 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2428 *output, thread.get());
2429 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002430 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002431 sp<PlaybackThread> thread;
2432 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002433 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002434 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2435 *output, thread.get());
2436 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2437 || !isValidPcmSinkFormat(config->format)
2438 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002439 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002440 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2441 *output, thread.get());
2442 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002443 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002444 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2445 *output, thread.get());
2446 }
2447 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002448 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002449 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002450 }
Eric Laurent83b88082014-06-20 18:31:16 -07002451 }
2452
2453 return 0;
2454}
2455
Eric Laurentcf2c0212014-07-25 16:20:43 -07002456status_t AudioFlinger::openOutput(audio_module_handle_t module,
2457 audio_io_handle_t *output,
2458 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002459 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002460 uint32_t *latencyMs,
2461 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462{
jiabin43810402019-10-24 14:58:31 -07002463 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002464 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002465 this, module,
jiabin43810402019-10-24 14:58:31 -07002466 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002467 config->sample_rate,
2468 config->format,
2469 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002470 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471
jiabin43810402019-10-24 14:58:31 -07002472 audio_devices_t deviceType = device->type();
2473 const String8 address = String8(device->address().c_str());
2474
2475 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002476 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002478
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 Mutex::Autolock _l(mLock);
2480
jiabin43810402019-10-24 14:58:31 -07002481 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002482 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002483 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2484 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2485 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486
Eric Laurent6acd1d42017-01-04 14:23:29 -08002487 // notify client processes of the new output creation
2488 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002489
Eric Laurent6acd1d42017-01-04 14:23:29 -08002490 // the first primary output opened designates the primary hw device
2491 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002492 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002493 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002494
Eric Laurent6acd1d42017-01-04 14:23:29 -08002495 AutoMutex lock(mHardwareLock);
2496 mHardwareStatus = AUDIO_HW_SET_MODE;
2497 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2498 mHardwareStatus = AUDIO_HW_IDLE;
2499 }
2500 } else {
2501 MmapThread *mmapThread = (MmapThread *)thread.get();
2502 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002503 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002504 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 }
2506
Eric Laurentcf2c0212014-07-25 16:20:43 -07002507 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508}
2509
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002510audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2511 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512{
2513 Mutex::Autolock _l(mLock);
2514 MixerThread *thread1 = checkMixerThread_l(output1);
2515 MixerThread *thread2 = checkMixerThread_l(output2);
2516
2517 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002518 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2519 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002520 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521 }
2522
Glenn Kasteneeecb982016-02-26 10:44:04 -08002523 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002524 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 thread->addOutputTrack(thread2);
2526 mPlaybackThreads.add(id, thread);
2527 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002528 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529 return id;
2530}
2531
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002532status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533{
Glenn Kastend96c5722012-04-25 13:44:49 -07002534 return closeOutput_nonvirtual(output);
2535}
2536
2537status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2538{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 // keep strong reference on the playback thread so that
2540 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002541 sp<PlaybackThread> playbackThread;
2542 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 {
2544 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002545 playbackThread = checkPlaybackThread_l(output);
2546 if (playbackThread != NULL) {
2547 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548
Andy Hungdc099c22018-09-18 13:46:39 -07002549 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002550
Eric Laurent6acd1d42017-01-04 14:23:29 -08002551 if (playbackThread->type() == ThreadBase::MIXER) {
2552 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2553 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2554 DuplicatingThread *dupThread =
2555 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2556 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2557 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002558 }
2559 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002560
2561
Eric Laurent6acd1d42017-01-04 14:23:29 -08002562 mPlaybackThreads.removeItem(output);
2563 // save all effects to the default thread
2564 if (mPlaybackThreads.size()) {
2565 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2566 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002567 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002568 Mutex::Autolock _dl(dstThread->mLock);
2569 Mutex::Autolock _sl(playbackThread->mLock);
2570 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2571 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002572 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002573 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002574 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 }
2576 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002577 } else {
2578 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2579 if (mmapThread == 0) {
2580 return BAD_VALUE;
2581 }
Andy Hungdc099c22018-09-18 13:46:39 -07002582 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002583 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002584 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002586 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2587 ioDesc->mIoHandle = output;
2588 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002589 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002591 // The thread entity (active unit of execution) is no longer running here,
2592 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593
Eric Laurent6acd1d42017-01-04 14:23:29 -08002594 if (playbackThread != 0) {
2595 playbackThread->exit();
2596 if (!playbackThread->isDuplicating()) {
2597 closeOutputFinish(playbackThread);
2598 }
2599 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002600 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002601 mmapThread->exit();
2602 AudioStreamOut *out = mmapThread->clearOutput();
2603 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2604 // from now on thread->mOutput is NULL
2605 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 }
2607 return NO_ERROR;
2608}
2609
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002610void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002611{
2612 AudioStreamOut *out = thread->clearOutput();
2613 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2614 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002615 delete out;
2616}
2617
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002618void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002619{
2620 mPlaybackThreads.removeItem(thread->mId);
2621 thread->exit();
2622 closeOutputFinish(thread);
2623}
2624
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002625status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626{
2627 Mutex::Autolock _l(mLock);
2628 PlaybackThread *thread = checkPlaybackThread_l(output);
2629
2630 if (thread == NULL) {
2631 return BAD_VALUE;
2632 }
2633
Steve Block3856b092011-10-20 11:56:00 +01002634 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 thread->suspend();
2636
2637 return NO_ERROR;
2638}
2639
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002640status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641{
2642 Mutex::Autolock _l(mLock);
2643 PlaybackThread *thread = checkPlaybackThread_l(output);
2644
2645 if (thread == NULL) {
2646 return BAD_VALUE;
2647 }
2648
Steve Block3856b092011-10-20 11:56:00 +01002649 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650
2651 thread->restore();
2652
2653 return NO_ERROR;
2654}
2655
Eric Laurentcf2c0212014-07-25 16:20:43 -07002656status_t AudioFlinger::openInput(audio_module_handle_t module,
2657 audio_io_handle_t *input,
2658 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002659 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002660 const String8& address,
2661 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002662 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663{
Eric Laurent83b88082014-06-20 18:31:16 -07002664 Mutex::Autolock _l(mLock);
2665
Glenn Kastene7d66712015-03-05 13:46:52 -08002666 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002667 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002668 }
2669
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002670 sp<ThreadBase> thread = openInput_l(
2671 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002672
2673 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002674 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002675 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002676 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002678 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002679}
Dima Zavin799a70e2011-04-18 16:57:27 -07002680
Eric Laurent6acd1d42017-01-04 14:23:29 -08002681sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002682 audio_io_handle_t *input,
2683 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002684 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002685 const String8& address,
2686 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002687 audio_input_flags_t flags,
2688 audio_devices_t outputDevice,
2689 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002690{
Glenn Kastene7d66712015-03-05 13:46:52 -08002691 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002692 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002693 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002694 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002695 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002696
Glenn Kasteneeecb982016-02-26 10:44:04 -08002697 // Audio Policy can request a specific handle for hardware hotword.
2698 // The goal here is not to re-open an already opened input.
2699 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002700 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002701 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2702 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2703 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2704 return 0;
2705 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2706 // This should not happen in a transient state with current design.
2707 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2708 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002709 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002710
Eric Laurentcf2c0212014-07-25 16:20:43 -07002711 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002712 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002713 sp<StreamInHalInterface> inStream;
2714 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002715 *input, devices, &halconfig, flags, address.string(), source,
2716 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002717 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2718 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002719 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002720 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002721 halconfig.sample_rate,
2722 halconfig.format,
2723 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002724 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002725 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002727 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002728 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002729 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002730 audio_is_linear_pcm(config->format) &&
2731 audio_is_linear_pcm(halconfig.format) &&
2732 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002733 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2734 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002735 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002736 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002737 inStream.clear();
2738 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002739 *input, devices, &halconfig, flags, address.string(), source,
2740 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002741 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 }
2743
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002744 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002745 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002746 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2747 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002748 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002749 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002750 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2751 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002752 return thread;
2753 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002754 // Start record thread
2755 // RecordThread requires both input and output device indication to forward to audio
2756 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002757 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002758 mRecordThreads.add(*input, thread);
2759 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2760 return thread;
2761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762 }
2763
Eric Laurentcf2c0212014-07-25 16:20:43 -07002764 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002765 return 0;
2766}
2767
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002768status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769{
Glenn Kastend96c5722012-04-25 13:44:49 -07002770 return closeInput_nonvirtual(input);
2771}
2772
2773status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2774{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 // keep strong reference on the record thread so that
2776 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002777 sp<RecordThread> recordThread;
2778 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 {
2780 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002781 recordThread = checkRecordThread_l(input);
2782 if (recordThread != 0) {
2783 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784
Andy Hungdc099c22018-09-18 13:46:39 -07002785 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002786
Eric Laurent6acd1d42017-01-04 14:23:29 -08002787 // If we still have effect chains, it means that a client still holds a handle
2788 // on at least one effect. We must either move the chain to an existing thread with the
2789 // same session ID or put it aside in case a new record thread is opened for a
2790 // new capture on the same session
2791 sp<EffectChain> chain;
2792 {
2793 Mutex::Autolock _sl(recordThread->mLock);
2794 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2795 // Note: maximum one chain per record thread
2796 if (effectChains.size() != 0) {
2797 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002798 }
2799 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002800 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002801 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002802 // This should only happen in case of overlap between one thread tear down and the
2803 // creation of its replacement
2804 size_t i;
2805 for (i = 0; i < mRecordThreads.size(); i++) {
2806 sp<RecordThread> t = mRecordThreads.valueAt(i);
2807 if (t == recordThread) {
2808 continue;
2809 }
2810 if (t->hasAudioSession(chain->sessionId()) != 0) {
2811 Mutex::Autolock _l(t->mLock);
2812 ALOGV("closeInput() found thread %d for effect session %d",
2813 t->id(), chain->sessionId());
2814 t->addEffectChain_l(chain);
2815 break;
2816 }
2817 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002818 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002819 if (i == mRecordThreads.size()) {
2820 putOrphanEffectChain_l(chain);
2821 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002822 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002823 mRecordThreads.removeItem(input);
2824 } else {
2825 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2826 if (mmapThread == 0) {
2827 return BAD_VALUE;
2828 }
Andy Hungdc099c22018-09-18 13:46:39 -07002829 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002830 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002831 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002832 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2833 ioDesc->mIoHandle = input;
2834 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 }
Eric Laurent83b88082014-06-20 18:31:16 -07002836 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2837 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002838 if (recordThread != 0) {
2839 closeInputFinish(recordThread);
2840 } else if (mmapThread != 0) {
2841 mmapThread->exit();
2842 AudioStreamIn *in = mmapThread->clearInput();
2843 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2844 // from now on thread->mInput is NULL
2845 delete in;
2846 }
Eric Laurent83b88082014-06-20 18:31:16 -07002847 return NO_ERROR;
2848}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002850void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002851{
2852 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002853 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002854 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002855 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002856 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002857}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002859void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002860{
2861 mRecordThreads.removeItem(thread->mId);
2862 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863}
2864
Glenn Kastend2304db2014-02-03 07:40:31 -08002865status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866{
2867 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002868 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869
2870 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2871 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002872 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002873 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002874 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2875 mMmapThreads[i]->invalidateTracks(stream);
2876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 return NO_ERROR;
2878}
2879
2880
Glenn Kasteneeecb982016-02-26 10:44:04 -08002881audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882{
Glenn Kasten9d003132016-04-06 14:38:09 -07002883 // This is a binder API, so a malicious client could pass in a bad parameter.
2884 // Check for that before calling the internal API nextUniqueId().
2885 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2886 ALOGE("newAudioUniqueId invalid use %d", use);
2887 return AUDIO_UNIQUE_ID_ALLOCATE;
2888 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002889 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890}
2891
Glenn Kastend848eb42016-03-08 13:42:11 -08002892void AudioFlinger::acquireAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002893{
2894 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002895 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002896 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002897 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2898 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match releaseAudioSessionId()
Marco Nelissend457c972014-02-11 08:47:07 -08002899 caller = pid;
2900 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002901
Eric Laurent021cf962014-05-13 10:18:14 -07002902 {
2903 Mutex::Autolock _cl(mClientLock);
2904 // Ignore requests received from processes not known as notification client. The request
2905 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2906 // called from a different pid leaving a stale session reference. Also we don't know how
2907 // to clear this reference if the client process dies.
2908 if (mNotificationClients.indexOfKey(caller) < 0) {
2909 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2910 return;
2911 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002912 }
2913
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002914 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002915 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002916 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002917 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2918 ref->mCnt++;
2919 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002920 return;
2921 }
2922 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002923 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
2924 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002925}
2926
Glenn Kastend848eb42016-03-08 13:42:11 -08002927void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002928{
Eric Laurent6c796322019-04-09 14:13:17 -07002929 std::vector< sp<EffectModule> > removedEffects;
2930 {
2931 Mutex::Autolock _l(mLock);
2932 pid_t caller = IPCThreadState::self()->getCallingPid();
2933 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2934 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
2935 if (pid != -1 && isAudioServerUid(callerUid)) { // check must match acquireAudioSessionId()
2936 caller = pid;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002937 }
Eric Laurent6c796322019-04-09 14:13:17 -07002938 size_t num = mAudioSessionRefs.size();
2939 for (size_t i = 0; i < num; i++) {
2940 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2941 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2942 ref->mCnt--;
2943 ALOGV(" decremented refcount to %d", ref->mCnt);
2944 if (ref->mCnt == 0) {
2945 mAudioSessionRefs.removeAt(i);
2946 delete ref;
2947 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2948 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2949 }
2950 goto Exit;
2951 }
2952 }
2953 // If the caller is audioserver it is likely that the session being released was acquired
2954 // on behalf of a process not in notification clients and we ignore the warning.
2955 ALOGW_IF(!isAudioServerUid(callerUid),
2956 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002957 }
Eric Laurent6c796322019-04-09 14:13:17 -07002958
2959Exit:
2960 for (auto& effect : removedEffects) {
2961 effect->updatePolicyState();
2962 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002963}
2964
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002965bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
2966{
2967 size_t num = mAudioSessionRefs.size();
2968 for (size_t i = 0; i < num; i++) {
2969 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2970 if (ref->mSessionid == audioSession) {
2971 return true;
2972 }
2973 }
2974 return false;
2975}
2976
Eric Laurent6c796322019-04-09 14:13:17 -07002977std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002978
Steve Block3856b092011-10-20 11:56:00 +01002979 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002980
2981 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07002982 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002983
2984 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2985 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002986 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002987 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2988 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002989 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07002990 chains.push(ec);
2991 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002992 }
2993 }
Eric Laurent6c796322019-04-09 14:13:17 -07002994
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002995 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2996 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02002997 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002998 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
2999 sp<EffectChain> ec = t->mEffectChains[j];
3000 chains.push(ec);
3001 }
3002 }
3003
Eric Laurent6c796322019-04-09 14:13:17 -07003004 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3005 sp<MmapThread> t = mMmapThreads.valueAt(i);
3006 Mutex::Autolock _l(t->mLock);
3007 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3008 sp<EffectChain> ec = t->mEffectChains[j];
3009 chains.push(ec);
3010 }
3011 }
3012
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003013 for (size_t i = 0; i < chains.size(); i++) {
3014 sp<EffectChain> ec = chains[i];
3015 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003016 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003017 if (t == 0) {
3018 continue;
3019 }
3020 size_t numsessionrefs = mAudioSessionRefs.size();
3021 bool found = false;
3022 for (size_t k = 0; k < numsessionrefs; k++) {
3023 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003024 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003025 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003026 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003027 found = true;
3028 break;
3029 }
3030 }
3031 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003032 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003033 // remove all effects from the chain
3034 while (ec->mEffects.size()) {
3035 sp<EffectModule> effect = ec->mEffects[0];
3036 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003037 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003038 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003039 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003040 }
Eric Laurent6c796322019-04-09 14:13:17 -07003041 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003042 }
3043 }
3044 }
Eric Laurent6c796322019-04-09 14:13:17 -07003045 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003046}
3047
Andy Hungdc099c22018-09-18 13:46:39 -07003048// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3049void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3050{
3051 audio_utils::FdToString fdToString;
3052 const int fd = fdToString.fd();
3053 if (fd >= 0) {
3054 thread->dump(fd, {} /* args */);
3055 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3056 }
3057}
3058
Glenn Kasteneeecb982016-02-26 10:44:04 -08003059// checkThread_l() must be called with AudioFlinger::mLock held
3060AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3061{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003062 ThreadBase *thread = checkMmapThread_l(ioHandle);
3063 if (thread == 0) {
3064 switch (audio_unique_id_get_use(ioHandle)) {
3065 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3066 thread = checkPlaybackThread_l(ioHandle);
3067 break;
3068 case AUDIO_UNIQUE_ID_USE_INPUT:
3069 thread = checkRecordThread_l(ioHandle);
3070 break;
3071 default:
3072 break;
3073 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003074 }
3075 return thread;
3076}
3077
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003079AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080{
Glenn Kastena1117922012-01-26 10:53:32 -08003081 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082}
3083
3084// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003085AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086{
3087 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003088 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089}
3090
3091// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003092AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093{
Glenn Kastena1117922012-01-26 10:53:32 -08003094 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095}
3096
Eric Laurent6acd1d42017-01-04 14:23:29 -08003097// checkMmapThread_l() must be called with AudioFlinger::mLock held
3098AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3099{
3100 return mMmapThreads.valueFor(io).get();
3101}
3102
3103
3104// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3105AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3106{
Eric Laurent7459b902017-04-19 18:10:41 -07003107 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003108 if (volumeInterface == nullptr) {
3109 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3110 if (mmapThread != nullptr) {
3111 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003112 MmapPlaybackThread *mmapPlaybackThread =
3113 static_cast<MmapPlaybackThread *>(mmapThread);
3114 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003115 }
3116 }
3117 }
3118 return volumeInterface;
3119}
3120
3121Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3122{
3123 Vector <VolumeInterface *> volumeInterfaces;
3124 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003125 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003126 }
3127 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3128 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003129 MmapPlaybackThread *mmapPlaybackThread =
3130 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3131 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003132 }
3133 }
3134 return volumeInterfaces;
3135}
3136
Glenn Kasteneeecb982016-02-26 10:44:04 -08003137audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138{
Glenn Kasten9d003132016-04-06 14:38:09 -07003139 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003140 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003141 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3142 for (int retry = 0; retry < maxRetries; retry++) {
3143 // The cast allows wraparound from max positive to min negative instead of abort
3144 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3145 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3146 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3147 // allow wrap by skipping 0 and -1 for session ids
3148 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3149 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3150 return (audio_unique_id_t) (base | use);
3151 }
3152 }
3153 // We have no way of recovering from wraparound
3154 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3155 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156}
3157
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003158AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003159{
3160 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3161 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003162 if(thread->isDuplicating()) {
3163 continue;
3164 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003165 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003166 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003167 return thread;
3168 }
3169 }
3170 return NULL;
3171}
3172
jiabinc52b1ff2019-10-31 17:20:42 -07003173DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003174{
3175 PlaybackThread *thread = primaryPlaybackThread_l();
3176
3177 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003178 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003179 }
3180
jiabinc52b1ff2019-10-31 17:20:42 -07003181 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003182}
3183
Glenn Kastena7335632016-06-09 17:09:53 -07003184AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3185{
3186 size_t minFrameCount = 0;
3187 PlaybackThread *minThread = NULL;
3188 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3189 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3190 if (!thread->isDuplicating()) {
3191 size_t frameCount = thread->frameCountHAL();
3192 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3193 (frameCount == minFrameCount && thread->hasFastMixer() &&
3194 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3195 minFrameCount = frameCount;
3196 minThread = thread;
3197 }
3198 }
3199 }
3200 return minThread;
3201}
3202
Eric Laurenta011e352012-03-29 15:51:43 -07003203sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003204 audio_session_t triggerSession,
3205 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003206 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003207 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003208{
3209 Mutex::Autolock _l(mLock);
3210
3211 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3212 status_t playStatus = NAME_NOT_FOUND;
3213 status_t recStatus = NAME_NOT_FOUND;
3214 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3215 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3216 if (playStatus == NO_ERROR) {
3217 return event;
3218 }
3219 }
3220 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3221 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3222 if (recStatus == NO_ERROR) {
3223 return event;
3224 }
3225 }
3226 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3227 mPendingSyncEvents.add(event);
3228 } else {
3229 ALOGV("createSyncEvent() invalid event %d", event->type());
3230 event.clear();
3231 }
3232 return event;
3233}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003234
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235// ----------------------------------------------------------------------------
3236// Effect management
3237// ----------------------------------------------------------------------------
3238
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003239sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3240 return mEffectsFactoryHal;
3241}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242
Glenn Kastenf587ba52012-01-26 16:25:10 -08003243status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244{
3245 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003246 if (mEffectsFactoryHal.get()) {
3247 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3248 } else {
3249 return -ENODEV;
3250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251}
3252
Glenn Kastenf587ba52012-01-26 16:25:10 -08003253status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254{
3255 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003256 if (mEffectsFactoryHal.get()) {
3257 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3258 } else {
3259 return -ENODEV;
3260 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261}
3262
Glenn Kasten5e92a782012-01-30 07:40:52 -08003263status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003264 const effect_uuid_t *pTypeUuid,
3265 uint32_t preferredTypeFlag,
3266 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003268 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3269 return BAD_VALUE;
3270 }
3271
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003273
3274 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003275 return -ENODEV;
3276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003278 status_t status = NO_ERROR;
3279 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3280 // If uuid is specified, request effect descriptor from that.
3281 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3282 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3283 // If uuid is not specified, look for an available implementation
3284 // of the required type instead.
3285
3286 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3287 effect_descriptor_t desc;
3288 desc.flags = 0; // prevent compiler warning
3289
3290 uint32_t numEffects = 0;
3291 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3292 if (status < 0) {
3293 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3294 return status;
3295 }
3296
3297 bool found = false;
3298 for (uint32_t i = 0; i < numEffects; i++) {
3299 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3300 if (status < 0) {
3301 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3302 continue;
3303 }
3304 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3305 // If matching type found save effect descriptor.
3306 found = true;
3307 *descriptor = desc;
3308
3309 // If there's no preferred flag or this descriptor matches the preferred
3310 // flag, success! If this descriptor doesn't match the preferred
3311 // flag, continue enumeration in case a better matching version of this
3312 // effect type is available. Note that this means if no effect with a
3313 // correct flag is found, the descriptor returned will correspond to the
3314 // last effect that at least had a matching type uuid (if any).
3315 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3316 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3317 break;
3318 }
3319 }
3320 }
3321
3322 if (!found) {
3323 status = NAME_NOT_FOUND;
3324 ALOGW("getEffectDescriptor(): Effect not found by type.");
3325 }
3326 } else {
3327 status = BAD_VALUE;
3328 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3329 }
3330 return status;
3331}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003333sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 effect_descriptor_t *pDesc,
3335 const sp<IEffectClient>& effectClient,
3336 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003337 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003338 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003339 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003340 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003341 pid_t pid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 status_t *status,
3343 int *id,
3344 int *enabled)
3345{
3346 status_t lStatus = NO_ERROR;
3347 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349
Eric Laurentb6436272016-12-07 19:24:50 -08003350 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003351 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003352 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3353 ALOGW_IF(pid != -1 && pid != callingPid,
3354 "%s uid %d pid %d tried to pass itself off as pid %d",
3355 __func__, callingUid, callingPid, pid);
3356 pid = callingPid;
3357 }
3358
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003359 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3360 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361
3362 if (pDesc == NULL) {
3363 lStatus = BAD_VALUE;
3364 goto Exit;
3365 }
3366
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003367 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003368 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003369 lStatus = NO_INIT;
3370 goto Exit;
3371 }
3372
Andy Hung6096dcd2019-03-13 13:20:30 -07003373 // check audio settings permission for global effects
3374 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3375 if (!settingsAllowed()) {
3376 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3377 lStatus = PERMISSION_DENIED;
3378 goto Exit;
3379 }
3380 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3381 if (!isAudioServerUid(callingUid)) {
3382 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3383 lStatus = PERMISSION_DENIED;
3384 goto Exit;
3385 }
3386
3387 if (io == AUDIO_IO_HANDLE_NONE) {
3388 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3389 lStatus = BAD_VALUE;
3390 goto Exit;
3391 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003392 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3393 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3394 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3395 lStatus = PERMISSION_DENIED;
3396 goto Exit;
3397 }
Eric Laurent94876032019-11-13 12:45:28 -08003398 if (io != AUDIO_IO_HANDLE_NONE) {
3399 ALOGE("%s: io handle should not be specified for device effect", __func__);
3400 lStatus = BAD_VALUE;
3401 goto Exit;
3402 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003403 } else {
3404 // general sessionId.
3405
3406 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3407 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3408 lStatus = BAD_VALUE;
3409 goto Exit;
3410 }
3411
3412 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3413 // to prevent creating an effect when one doesn't actually have track with that session?
3414 }
3415
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003417 // Get the full effect descriptor from the uuid/type.
3418 // If the session is the output mix, prefer an auxiliary effect,
3419 // otherwise no preference.
3420 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3421 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3422 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3423 if (lStatus < 0) {
3424 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3425 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426 }
3427
3428 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003429 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3431 lStatus = INVALID_OPERATION;
3432 goto Exit;
3433 }
3434
Eric Laurent59255e42011-07-27 19:49:51 -07003435 // check recording permission for visualizer
3436 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003437 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003438 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003439 lStatus = PERMISSION_DENIED;
3440 goto Exit;
3441 }
3442
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003444 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003445 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003446 // if the output returned by getOutputForEffect() is removed before we lock the
3447 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3448 // and we will exit safely
3449 io = AudioSystem::getOutputForEffect(&desc);
3450 ALOGV("createEffect got output %d", io);
3451 }
3452
3453 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454
Eric Laurentb82e6b72019-11-22 17:25:04 -08003455 if (sessionId == AUDIO_SESSION_DEVICE) {
3456 sp<Client> client = registerPid(pid);
3457 ALOGV("%s device type %d address %s", __func__, device.mType, device.getAddress());
3458 handle = mDeviceEffectManager.createEffect_l(
3459 &desc, device, client, effectClient, mPatchPanel.patches_l(),
3460 enabled, &lStatus);
3461 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3462 // remove local strong reference to Client with mClientLock held
3463 Mutex::Autolock _cl(mClientLock);
3464 client.clear();
3465 } else {
3466 // handle must be valid here, but check again to be safe.
3467 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3468 }
3469 goto Register;
3470 }
3471
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 // If output is not specified try to find a matching audio session ID in one of the
3473 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003474 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3475 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003476 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3477 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003478 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003479 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003480 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3481 if (io == AUDIO_IO_HANDLE_NONE) {
3482 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003484 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003485 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003486 }
Andy Hung444bb552019-03-14 17:06:39 -07003487
3488 // If you wish to create a Record preprocessing AudioEffect in Java,
3489 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3490 // Otherwise it will fail when created on a Playback thread by legacy
3491 // handling below. Ditto with Mmap, the associated Mmap track must be created
3492 // before creating the AudioEffect or the io handle must be specified.
3493 //
3494 // Detect if the effect is created after an AudioRecord is destroyed.
3495 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3496 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3497 " for session %d no longer exists",
3498 __func__, desc.name, sessionId);
3499 lStatus = PERMISSION_DENIED;
3500 goto Exit;
3501 }
3502
3503 // Legacy handling of creating an effect on an expired or made-up
3504 // session id. We think that it is a Playback effect.
3505 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003506 // If no output thread contains the requested session ID, default to
3507 // first output. The effect chain will be moved to the correct output
3508 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003509 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003510 io = mPlaybackThreads.keyAt(0);
3511 }
Steve Block3856b092011-10-20 11:56:00 +01003512 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003513 } else if (checkPlaybackThread_l(io) != nullptr) {
3514 // allow only one effect chain per sessionId on mPlaybackThreads.
3515 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3516 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3517 if (io == checkIo) continue;
3518 const uint32_t sessionType =
3519 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3520 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3521 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3522 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3523 android_errorWriteLog(0x534e4554, "123237974");
3524 lStatus = BAD_VALUE;
3525 goto Exit;
3526 }
3527 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003528 }
3529 ThreadBase *thread = checkRecordThread_l(io);
3530 if (thread == NULL) {
3531 thread = checkPlaybackThread_l(io);
3532 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003533 thread = checkMmapThread_l(io);
3534 if (thread == NULL) {
3535 ALOGE("createEffect() unknown output thread");
3536 lStatus = BAD_VALUE;
3537 goto Exit;
3538 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003539 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003540 } else {
3541 // Check if one effect chain was awaiting for an effect to be created on this
3542 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003543 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003544 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003545 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003546 thread->addEffectChain_l(chain);
3547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003549
Eric Laurent021cf962014-05-13 10:18:14 -07003550 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003552 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003553 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003554 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003555 &desc, enabled, &lStatus, pinned);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003556 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003557 // remove local strong reference to Client with mClientLock held
3558 Mutex::Autolock _cl(mClientLock);
3559 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003560 } else {
3561 // handle must be valid here, but check again to be safe.
3562 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 }
3565
Eric Laurentb82e6b72019-11-22 17:25:04 -08003566Register:
Eric Laurent6c796322019-04-09 14:13:17 -07003567 if (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS) {
3568 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003569 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003570 if (effect != nullptr) {
3571 status_t rStatus = effect->updatePolicyState();
3572 if (rStatus != NO_ERROR) {
3573 lStatus = rStatus;
3574 }
3575 }
3576 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003577 handle.clear();
3578 }
3579
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003581 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 return handle;
3583}
3584
Glenn Kastend848eb42016-03-08 13:42:11 -08003585status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003586 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003587{
Steve Block3856b092011-10-20 11:56:00 +01003588 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003589 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003590 Mutex::Autolock _l(mLock);
3591 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003592 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003593 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 }
Eric Laurentde070132010-07-13 04:45:46 -07003595 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3596 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003597 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003598 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599 }
Eric Laurentde070132010-07-13 04:45:46 -07003600 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3601 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003602 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003603 return BAD_VALUE;
3604 }
3605
3606 Mutex::Autolock _dl(dstThread->mLock);
3607 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003608 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609}
3610
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003611
3612void AudioFlinger::setEffectSuspended(int effectId,
3613 audio_session_t sessionId,
3614 bool suspended)
3615{
3616 Mutex::Autolock _l(mLock);
3617
3618 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3619 if (thread == nullptr) {
3620 return;
3621 }
3622 Mutex::Autolock _sl(thread->mLock);
3623 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3624 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3625}
3626
3627
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003628// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003629status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003630 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003631 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003632{
Steve Block3856b092011-10-20 11:56:00 +01003633 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003634 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003635
Eric Laurent59255e42011-07-27 19:49:51 -07003636 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003637 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003638 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003639 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003640 return INVALID_OPERATION;
3641 }
3642
Eric Laurent4c415062016-06-17 16:14:16 -07003643 // Check whether the destination thread and all effects in the chain are compatible
3644 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003645 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003646 " destination thread %p is not compatible with effects in the chain",
3647 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003648 return INVALID_OPERATION;
3649 }
3650
Eric Laurent39e94f82010-07-28 01:32:47 -07003651 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003652 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003653 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003654 // removed.
3655 srcThread->removeEffectChain_l(chain);
3656
3657 // transfer all effects one by one so that new effect chain is created on new thread with
3658 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003659 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003660 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003661 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003662 Vector< sp<EffectModule> > removed;
3663 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003664 while (effect != 0) {
3665 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003666 removed.add(effect);
3667 status = dstThread->addEffect_l(effect);
3668 if (status != NO_ERROR) {
3669 break;
3670 }
Eric Laurentec35a142011-10-05 17:42:25 -07003671 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3672 if (effect->state() == EffectModule::ACTIVE ||
3673 effect->state() == EffectModule::STOPPING) {
3674 effect->start();
3675 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003676 // if the move request is not received from audio policy manager, the effect must be
3677 // re-registered with the new strategy and output
3678 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003679 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003680 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003681 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003682 status = NO_INIT;
3683 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003684 }
3685 strategy = dstChain->strategy();
3686 }
Eric Laurentde070132010-07-13 04:45:46 -07003687 effect = chain->getEffectFromId_l(0);
3688 }
3689
Eric Laurent5baf2af2013-09-12 17:37:00 -07003690 if (status != NO_ERROR) {
3691 for (size_t i = 0; i < removed.size(); i++) {
3692 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003693 }
3694 }
3695
3696 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003697}
3698
Eric Laurent6c796322019-04-09 14:13:17 -07003699status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3700 const sp<PlaybackThread>& dstThread,
3701 sp<PlaybackThread> *srcThread)
3702{
3703 status_t status = NO_ERROR;
3704 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003705 sp<PlaybackThread> thread =
3706 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003707
3708 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3709 Mutex::Autolock _dl(dstThread->mLock);
3710 Mutex::Autolock _sl(thread->mLock);
3711 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3712 sp<EffectChain> dstChain;
3713 if (srcChain == 0) {
3714 return INVALID_OPERATION;
3715 }
3716
3717 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3718 if (effect == 0) {
3719 return INVALID_OPERATION;
3720 }
3721 thread->removeEffect_l(effect);
3722 status = dstThread->addEffect_l(effect);
3723 if (status != NO_ERROR) {
3724 thread->addEffect_l(effect);
3725 status = INVALID_OPERATION;
3726 goto Exit;
3727 }
3728
Eric Laurent6b446ce2019-12-13 10:56:31 -08003729 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003730 if (dstChain == 0) {
3731 thread->addEffect_l(effect);
3732 status = INVALID_OPERATION;
3733 }
3734
3735Exit:
3736 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3737 if (effect->state() == EffectModule::ACTIVE ||
3738 effect->state() == EffectModule::STOPPING) {
3739 effect->start();
3740 }
3741 }
3742
3743 if (status == NO_ERROR && srcThread != nullptr) {
3744 *srcThread = thread;
3745 }
3746 return status;
3747}
3748
Eric Laurent5baf2af2013-09-12 17:37:00 -07003749bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003750{
3751 if (mGlobalEffectEnableTime != 0 &&
3752 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3753 return true;
3754 }
3755
3756 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3757 sp<EffectChain> ec =
3758 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003759 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003760 return true;
3761 }
3762 }
3763 return false;
3764}
3765
Eric Laurent5baf2af2013-09-12 17:37:00 -07003766void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003767{
3768 Mutex::Autolock _l(mLock);
3769
3770 mGlobalEffectEnableTime = systemTime();
3771
3772 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3773 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3774 if (t->mType == ThreadBase::OFFLOAD) {
3775 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3776 }
3777 }
3778
3779}
3780
Eric Laurentaaa44472014-09-12 17:41:50 -07003781status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3782{
Eric Laurentd8365c52017-07-16 15:27:05 -07003783 // clear possible suspended state before parking the chain so that it starts in default state
3784 // when attached to a new record thread
3785 chain->setEffectSuspended_l(FX_IID_AEC, false);
3786 chain->setEffectSuspended_l(FX_IID_NS, false);
3787
Glenn Kastend848eb42016-03-08 13:42:11 -08003788 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003789 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003790 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003791 if (index >= 0) {
3792 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3793 return ALREADY_EXISTS;
3794 }
3795 mOrphanEffectChains.add(session, chain);
3796 return NO_ERROR;
3797}
3798
3799sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3800{
3801 sp<EffectChain> chain;
3802 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003803 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003804 if (index >= 0) {
3805 chain = mOrphanEffectChains.valueAt(index);
3806 mOrphanEffectChains.removeItemsAt(index);
3807 }
3808 return chain;
3809}
3810
3811bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3812{
3813 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003814 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003815 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003816 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003817 if (index >= 0) {
3818 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003819 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003820 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003821 mOrphanEffectChains.removeItemsAt(index);
3822 }
3823 return true;
3824 }
3825 return false;
3826}
3827
3828
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829// ----------------------------------------------------------------------------
3830
3831status_t AudioFlinger::onTransact(
3832 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3833{
3834 return BnAudioFlinger::onTransact(code, data, reply, flags);
3835}
3836
Glenn Kasten63238ef2015-03-02 15:50:29 -08003837} // namespace android