blob: 03c16f38c755a4428e773688db8b0007855d0a9d [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>
Mikhail Naganov88b30d22020-03-09 19:43:13 +000032#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033
jiabin57303cc2018-12-18 15:45:57 -080034#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080035#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <binder/IServiceManager.h>
37#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070038#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070040#include <media/audiohal/DeviceHalInterface.h>
41#include <media/audiohal/DevicesFactoryHalInterface.h>
42#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070043#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080044#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070045#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070046#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070047#include <utils/String16.h>
48#include <utils/threads.h>
49
Steven Morelandf0c02ce2018-02-23 14:53:55 -080050#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <cutils/properties.h>
52
Dima Zavin64760242011-05-11 14:15:23 -070053#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070054#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070057#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Andy Hung6770c6f2015-04-07 13:43:36 -070059#include <media/AudioResamplerPublic.h>
60
Mikhail Naganov9fe94012016-10-14 14:57:40 -070061#include <system/audio_effects/effect_visualizer.h>
62#include <system/audio_effects/effect_ns.h>
63#include <system/audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Glenn Kasten3b21c502011-12-15 09:52:39 -080065#include <audio_utils/primitives.h>
66
Eric Laurentfeb0db62011-07-22 09:04:31 -070067#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080068
Glenn Kasten9e58b552013-01-18 15:09:48 -080069#include <media/IMediaLogService.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080070#include <media/nbaio/Pipe.h>
71#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080072#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070073#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070074#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070075#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070076#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080077
rago3bd1c872016-09-26 12:58:14 -070078//#define BUFLOG_NDEBUG 0
79#include <BufLog.h>
80
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080081#include "TypedLogger.h"
82
Mathias Agopian65ab4712010-07-14 17:59:35 -070083// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070084
John Grossman1c345192012-03-27 14:00:17 -070085// Note: the following macro is used for extremely verbose logging message. In
86// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
87// 0; but one side effect of this is to turn all LOGV's as well. Some messages
88// are so verbose that we want to suppress them even when we have ALOG_ASSERT
89// turned on. Do not uncomment the #def below unless you really know what you
90// are doing and want to see all of the extremely verbose messages.
91//#define VERY_VERY_VERBOSE_LOGGING
92#ifdef VERY_VERY_VERBOSE_LOGGING
93#define ALOGVV ALOGV
94#else
95#define ALOGVV(a...) do { } while(0)
96#endif
Eric Laurentde070132010-07-13 04:45:46 -070097
Mathias Agopian65ab4712010-07-14 17:59:35 -070098namespace android {
99
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800100static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
101static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700102static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700103static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
Glenn Kasten58912562012-04-03 10:45:00 -0700105
John Grossman4ff14ba2012-02-08 16:37:41 -0800106nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800107
Eric Laurent81784c32012-11-19 14:55:58 -0800108uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700109
Eric Laurent813e2a72013-08-31 12:59:48 -0700110// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
111// we define a minimum time during which a global effect is considered enabled.
112static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
113
Eric Laurentfc235202016-12-20 18:48:17 -0800114Mutex gLock;
115wp<AudioFlinger> gAudioFlinger;
116
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700117// Keep a strong reference to media.log service around forever.
118// The service is within our parent process so it can never die in a way that we could observe.
119// These two variables are const after initialization.
120static sp<IBinder> sMediaLogServiceAsBinder;
121static sp<IMediaLogService> sMediaLogService;
122
123static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
124
125static void sMediaLogInit()
126{
127 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
128 if (sMediaLogServiceAsBinder != 0) {
129 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
130 }
131}
132
jiabin57303cc2018-12-18 15:45:57 -0800133// Keep a strong reference to external vibrator service
134static sp<os::IExternalVibratorService> sExternalVibratorService;
135
136static sp<os::IExternalVibratorService> getExternalVibratorService() {
137 if (sExternalVibratorService == 0) {
138 sp <IBinder> binder = defaultServiceManager()->getService(
139 String16("external_vibrator_service"));
140 if (binder != 0) {
141 sExternalVibratorService =
142 interface_cast<os::IExternalVibratorService>(binder);
143 }
144 }
145 return sExternalVibratorService;
146}
147
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000148class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
149 public:
150 void onNewDevicesAvailable() override {
151 // Start a detached thread to execute notification in parallel.
152 // This is done to prevent mutual blocking of audio_flinger and
153 // audio_policy services during system initialization.
154 std::thread notifier([]() {
155 AudioSystem::onNewAudioModulesAvailable();
156 });
157 notifier.detach();
158 }
159};
160
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161// ----------------------------------------------------------------------------
162
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700163std::string formatToString(audio_format_t format) {
164 std::string result;
165 FormatConverter::toString(format, result);
166 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800167}
168
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169// ----------------------------------------------------------------------------
170
171AudioFlinger::AudioFlinger()
172 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800173 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800174 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800175 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700176 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800177 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800178 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700179 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800180 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700181 mBtNrecIsOff(false),
182 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700183 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800184 mTotalMemory(0),
185 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700186 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700187 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800188 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700189 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700190{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700191 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
192 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
193 // zero ID has a special meaning, so unavailable
194 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
195 }
196
Glenn Kastenae0cff12016-02-24 13:57:49 -0800197 const bool doLog = property_get_bool("ro.test_harness", false);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800198 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800199 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
200 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700201 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800202 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700203
Wei Jia3f273d12015-11-24 09:06:49 -0800204 // reset battery stats.
205 // if the audio service has crashed, battery stats could be left
206 // in bad state, reset the state upon service start.
207 BatteryNotifier::getInstance().noteResetAudio();
208
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700209 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700210 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
211
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800212 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700213 std::vector<pid_t> halPids;
214 mDevicesFactoryHal->getHalPids(&halPids);
215 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800216
217 // Notify that we have started (also called when audioserver service restarts)
218 mediametrics::LogItem(mMetricsId)
219 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
220 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221}
222
223void AudioFlinger::onFirstRef()
224{
Eric Laurent93575202011-01-18 18:39:02 -0800225 Mutex::Autolock _l(mLock);
226
Dima Zavin799a70e2011-04-18 16:57:27 -0700227 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 char val_str[PROPERTY_VALUE_MAX] = { 0 };
229 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
230 uint32_t int_val;
231 if (1 == sscanf(val_str, "%u", &int_val)) {
232 mStandbyTimeInNsecs = milliseconds(int_val);
233 ALOGI("Using %u mSec as standby time.", int_val);
234 } else {
235 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
236 ALOGI("Using default %u mSec as standby time.",
237 (uint32_t)(mStandbyTimeInNsecs / 1000000));
238 }
239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700240
Eric Laurenta4c5a552012-03-29 10:12:40 -0700241 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800242
243 gAudioFlinger = this;
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000244
245 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
246 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Eric Laurent42896a02019-09-27 15:40:33 -0700249status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
250 TimeCheck::setAudioHalPids(pids);
251 return NO_ERROR;
252}
253
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254AudioFlinger::~AudioFlinger()
255{
256 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700257 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700258 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259 }
260 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700261 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
Andy Hungb4946b62019-03-14 11:19:28 -0700264 while (!mMmapThreads.isEmpty()) {
265 const audio_io_handle_t io = mMmapThreads.keyAt(0);
266 if (mMmapThreads.valueAt(0)->isOutput()) {
267 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
268 } else {
269 closeInput_nonvirtual(io); // removes entry from mMmapThreads
270 }
271 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700272
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800273 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
274 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700275 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700276 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700277
278 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700279 if (sMediaLogService != 0) {
280 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
281 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
282 mUnregisteredWriters.pop();
283 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700284 }
285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700286}
287
Eric Laurentfc235202016-12-20 18:48:17 -0800288//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800289__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800290status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
291 const audio_attributes_t *attr,
292 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700293 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800294 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800295 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800296 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700297 sp<MmapStreamInterface>& interface,
298 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800299{
300 sp<AudioFlinger> af;
301 {
302 Mutex::Autolock _l(gLock);
303 af = gAudioFlinger.promote();
304 }
305 status_t ret = NO_INIT;
306 if (af != 0) {
307 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800308 direction, attr, config, client, deviceId,
309 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800310 }
311 return ret;
312}
313
Eric Laurent6acd1d42017-01-04 14:23:29 -0800314status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
315 const audio_attributes_t *attr,
316 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700317 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800318 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800319 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800320 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700321 sp<MmapStreamInterface>& interface,
322 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800323{
324 status_t ret = initCheck();
325 if (ret != NO_ERROR) {
326 return ret;
327 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800328 audio_session_t actualSessionId = *sessionId;
329 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
330 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
331 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800332 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700333 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800334 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700335 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800336 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
337 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
338 fullConfig.sample_rate = config->sample_rate;
339 fullConfig.channel_mask = config->channel_mask;
340 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800341 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700342
343 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800344 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200345 &streamType, client.clientPid, client.clientUid,
Ricardo Correa57a37692020-03-23 17:27:25 -0700346 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800347 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
348 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800349 deviceId, &portId, &secondaryOutputs);
350 ALOGW_IF(!secondaryOutputs.empty(),
351 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800352 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700353 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700354 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800355 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800356 client.clientPid,
357 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800358 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800359 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700360 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800361 }
362 if (ret != NO_ERROR) {
363 return ret;
364 }
365
366 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
367 // audio policy manager and we can retrieve it
368 sp<MmapThread> thread = mMmapThreads.valueFor(io);
369 if (thread != 0) {
370 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700371 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700372 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800373 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800374 config->sample_rate = thread->sampleRate();
375 config->channel_mask = thread->channelMask();
376 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800377 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700378 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700379 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700380 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800381 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700382 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800383 ret = NO_INIT;
384 }
385
386 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
387
Eric Laurentfc235202016-12-20 18:48:17 -0800388 return ret;
389}
390
jiabin57303cc2018-12-18 15:45:57 -0800391/* static */
392int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
393 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
394 if (evs != 0) {
395 int32_t ret;
396 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
397 if (status.isOk()) {
398 return ret;
399 }
400 }
jiabinbf6b0ec2019-02-12 12:30:12 -0800401 return AudioMixer::HAPTIC_SCALE_MUTE;
jiabin57303cc2018-12-18 15:45:57 -0800402}
403
404/* static */
405void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
406 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
407 if (evs != 0) {
408 evs->onExternalVibrationStop(*externalVibration);
409 }
410}
411
Eric Laurentb82e6b72019-11-22 17:25:04 -0800412status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
413 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
414 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
415 if (audioHwDevice == nullptr) {
416 return NO_INIT;
417 }
418 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
419}
420
421status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
422 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
423 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
424 if (audioHwDevice == nullptr) {
425 return NO_INIT;
426 }
427 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
428}
429
Eric Laurenta4c5a552012-03-29 10:12:40 -0700430static const char * const audio_interfaces[] = {
431 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
432 AUDIO_HARDWARE_MODULE_ID_A2DP,
433 AUDIO_HARDWARE_MODULE_ID_USB,
434};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700435
Phil Burk062e67a2015-02-11 13:40:50 -0800436AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700437 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700438 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700439{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700440 // if module is 0, the request comes from an old policy manager and we should load
441 // well known modules
442 if (module == 0) {
443 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700444 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700445 loadHwModule_l(audio_interfaces[i]);
446 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700447 // then try to find a module supporting the requested device.
448 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
449 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700450 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
451 uint32_t supportedDevices;
452 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700453 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700454 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700455 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700456 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700457 } else {
458 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700459 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
460 if (audioHwDevice != NULL) {
461 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700462 }
463 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700464
Dima Zavin799a70e2011-04-18 16:57:27 -0700465 return NULL;
466}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467
Glenn Kasten0f11b512014-01-31 16:18:54 -0800468void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700469{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 String8 result;
471
472 result.append("Clients:\n");
473 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800474 sp<Client> client = mClients.valueAt(i).promote();
475 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800476 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477 }
478 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700479
Eric Laurentd1b28d42013-09-18 18:47:13 -0700480 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800481 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700482 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800483 const pid_t pid = mNotificationClients[i]->getPid();
484 const uid_t uid = mNotificationClients[i]->getUid();
485 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
486 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700487 }
488
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700489 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800490 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700491 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
492 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800493 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
494 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
495 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498}
499
500
Glenn Kasten0f11b512014-01-31 16:18:54 -0800501void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502{
503 const size_t SIZE = 256;
504 char buffer[SIZE];
505 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800506 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507
John Grossman4ff14ba2012-02-08 16:37:41 -0800508 snprintf(buffer, SIZE, "Hardware status: %d\n"
509 "Standby Time mSec: %u\n",
510 hardwareStatus,
511 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512 result.append(buffer);
513 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514}
515
Glenn Kasten0f11b512014-01-31 16:18:54 -0800516void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517{
518 const size_t SIZE = 256;
519 char buffer[SIZE];
520 String8 result;
521 snprintf(buffer, SIZE, "Permission Denial: "
522 "can't dump AudioFlinger from pid=%d, uid=%d\n",
523 IPCThreadState::self()->getCallingPid(),
524 IPCThreadState::self()->getCallingUid());
525 result.append(buffer);
526 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527}
528
Eric Laurent81784c32012-11-19 14:55:58 -0800529bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700531 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
532 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533}
534
535status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
536{
Glenn Kasten44deb052012-02-05 18:09:08 -0800537 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538 dumpPermissionDenial(fd, args);
539 } else {
540 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800541 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 if (!hardwareLocked) {
543 String8 result(kHardwareLockedString);
544 write(fd, result.string(), result.size());
545 } else {
546 mHardwareLock.unlock();
547 }
548
Eric Tan7b651152018-07-13 10:17:19 -0700549 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550
551 // failed to lock - AudioFlinger is probably deadlocked
552 if (!locked) {
553 String8 result(kDeadlockedString);
554 write(fd, result.string(), result.size());
555 }
556
Eric Laurent021cf962014-05-13 10:18:14 -0700557 bool clientLocked = dumpTryLock(mClientLock);
558 if (!clientLocked) {
559 String8 result(kClientLockedString);
560 write(fd, result.string(), result.size());
561 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700562
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700563 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700564 mEffectsFactoryHal->dumpEffects(fd);
565 } else {
566 String8 result(kNoEffectsFactory);
567 write(fd, result.string(), result.size());
568 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700569
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700571 if (clientLocked) {
572 mClientLock.unlock();
573 }
574
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 dumpInternals(fd, args);
576
577 // dump playback threads
578 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
579 mPlaybackThreads.valueAt(i)->dump(fd, args);
580 }
581
582 // dump record threads
583 for (size_t i = 0; i < mRecordThreads.size(); i++) {
584 mRecordThreads.valueAt(i)->dump(fd, args);
585 }
586
Eric Laurent6acd1d42017-01-04 14:23:29 -0800587 // dump mmap threads
588 for (size_t i = 0; i < mMmapThreads.size(); i++) {
589 mMmapThreads.valueAt(i)->dump(fd, args);
590 }
591
Eric Laurentaaa44472014-09-12 17:41:50 -0700592 // dump orphan effect chains
593 if (mOrphanEffectChains.size() != 0) {
594 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
595 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
596 mOrphanEffectChains.valueAt(i)->dump(fd, args);
597 }
598 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700599 // dump all hardware devs
600 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700601 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
602 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700604
Mikhail Naganov201369b2018-05-16 16:52:32 -0700605 mPatchPanel.dump(fd);
606
Eric Laurentb82e6b72019-11-22 17:25:04 -0800607 mDeviceEffectManager.dump(fd);
608
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700609 // dump external setParameters
610 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
611 dprintf(fd, "\n%s setParameters:\n", name);
612 logger.dump(fd, " " /* prefix */);
613 };
614 dumpLogger(mRejectedSetParameterLog, "Rejected");
615 dumpLogger(mAppSetParameterLog, "App");
616 dumpLogger(mSystemSetParameterLog, "System");
617
Andy Hunga8115dc2018-08-24 15:51:59 -0700618 // dump historical threads in the last 10 seconds
619 const std::string threadLog = mThreadLog.dumpToString(
620 "Historical Thread Log ", 0 /* lines */,
621 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
622 write(fd, threadLog.c_str(), threadLog.size());
623
rago3bd1c872016-09-26 12:58:14 -0700624 BUFLOG_RESET;
625
Glenn Kastend65d73c2012-06-22 17:21:07 -0700626 if (locked) {
627 mLock.unlock();
628 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800629
Andy Hung8946a282018-04-19 20:04:56 -0700630#ifdef TEE_SINK
631 // NBAIO_Tee dump is safe to call outside of AF lock.
632 NBAIO_Tee::dumpAll(fd, "_DUMP");
633#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800634 // append a copy of media.log here by forwarding fd to it, but don't attempt
635 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700636 if (sMediaLogServiceAsBinder != 0) {
637 dprintf(fd, "\nmedia.log:\n");
638 Vector<String16> args;
639 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800640 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700641
642 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700643 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700644 bool unreachableMemory = false;
645 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700646 if (arg == String16("-m")) {
647 dumpMem = true;
648 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700649 unreachableMemory = true;
650 }
651 }
652
Andy Hung07b745e2016-05-23 16:21:07 -0700653 if (dumpMem) {
654 dprintf(fd, "\nDumping memory:\n");
655 std::string s = dumpMemoryAddresses(100 /* limit */);
656 write(fd, s.c_str(), s.size());
657 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700658 if (unreachableMemory) {
659 dprintf(fd, "\nDumping unreachable memory:\n");
660 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700661 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700662 write(fd, s.c_str(), s.size());
663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 }
665 return NO_ERROR;
666}
667
Eric Laurent021cf962014-05-13 10:18:14 -0700668sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800669{
Eric Laurent021cf962014-05-13 10:18:14 -0700670 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800671 // If pid is already in the mClients wp<> map, then use that entry
672 // (for which promote() is always != 0), otherwise create a new entry and Client.
673 sp<Client> client = mClients.valueFor(pid).promote();
674 if (client == 0) {
675 client = new Client(this, pid);
676 mClients.add(pid, client);
677 }
678
679 return client;
680}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681
Glenn Kasten9e58b552013-01-18 15:09:48 -0800682sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
683{
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700684 // If there is no memory allocated for logs, return a dummy writer that does nothing.
685 // Similarly if we can't contact the media.log service, also return a dummy writer.
686 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800687 return new NBLog::Writer();
688 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700689 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
690 // If allocation fails, consult the vector of previously unregistered writers
691 // and garbage-collect one or more them until an allocation succeeds
692 if (shared == 0) {
693 Mutex::Autolock _l(mUnregisteredWritersLock);
694 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
695 {
696 // Pick the oldest stale writer to garbage-collect
697 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
698 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700699 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700700 // Now the media.log remote reference to IMemory is gone. When our last local
701 // reference to IMemory also drops to zero at end of this block,
702 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
703 }
704 // Re-attempt the allocation
705 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
706 if (shared != 0) {
707 goto success;
708 }
709 }
710 // Even after garbage-collecting all old writers, there is still not enough memory,
711 // so return a dummy writer
712 return new NBLog::Writer();
713 }
714success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700715 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800716 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
717 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700718 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800719 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800720}
721
722void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
723{
Glenn Kasten685ef092013-02-04 08:15:34 -0800724 if (writer == 0) {
725 return;
726 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800727 sp<IMemory> iMemory(writer->getIMemory());
728 if (iMemory == 0) {
729 return;
730 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700731 // Rather than removing the writer immediately, append it to a queue of old writers to
732 // be garbage-collected later. This allows us to continue to view old logs for a while.
733 Mutex::Autolock _l(mUnregisteredWritersLock);
734 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800735}
736
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737// IAudioFlinger interface
738
Eric Laurent21da6472017-11-09 16:29:26 -0800739sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
740 CreateTrackOutput& output,
741 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742{
743 sp<PlaybackThread::Track> track;
744 sp<TrackHandle> trackHandle;
745 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800747 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800748 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800749 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
Eric Laurent21da6472017-11-09 16:29:26 -0800751 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700752 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800753 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700754 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
755 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700756 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700757
Andy Hung4ef19fa2018-05-15 19:35:29 -0700758 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800759 ALOGW_IF(clientUid != callingUid,
760 "%s uid %d tried to pass itself off as %d",
761 __FUNCTION__, callingUid, clientUid);
762 clientUid = callingUid;
763 updatePid = true;
764 }
765 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700766 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800767 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800768 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700769 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800770 __func__, callingUid, callingPid, clientPid);
771 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700772 }
773
Eric Laurent21da6472017-11-09 16:29:26 -0800774 audio_session_t sessionId = input.sessionId;
775 if (sessionId == AUDIO_SESSION_ALLOCATE) {
776 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800777 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
778 lStatus = BAD_VALUE;
779 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800780 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800781
Eric Laurent21da6472017-11-09 16:29:26 -0800782 output.sessionId = sessionId;
783 output.outputId = AUDIO_IO_HANDLE_NONE;
784 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700785 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Ricardo Correa57a37692020-03-23 17:27:25 -0700786 clientPid, clientUid, &input.config, input.flags,
787 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800788
789 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
790 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
791 goto Exit;
792 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800793 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
794 // but if someone uses binder directly they could bypass that and cause us to crash
795 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000796 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 lStatus = BAD_VALUE;
798 goto Exit;
799 }
800
Glenn Kasten53b5d092014-02-05 10:00:23 -0800801 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800802 if (!audio_is_output_channel(input.config.channel_mask)) {
803 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800804 lStatus = BAD_VALUE;
805 goto Exit;
806 }
807
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700808 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800809 if (!audio_is_valid_format(input.config.format)) {
810 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700811 lStatus = BAD_VALUE;
812 goto Exit;
813 }
814
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 {
816 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800817 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800819 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 lStatus = BAD_VALUE;
821 goto Exit;
822 }
823
Eric Laurent21da6472017-11-09 16:29:26 -0800824 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825
Glenn Kastene848bd92014-03-13 15:00:32 -0700826 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800827 // check if an effect chain with the same session ID is present on another
828 // output thread and move it here.
829 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
830 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
831 if (mPlaybackThreads.keyAt(i) != output.outputId) {
832 uint32_t sessions = t->hasAudioSession(sessionId);
833 if (sessions & ThreadBase::EFFECT_SESSION) {
834 effectThread = t.get();
835 break;
Eric Laurentde070132010-07-13 04:45:46 -0700836 }
837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 }
Eric Laurent21da6472017-11-09 16:29:26 -0800839 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840
Eric Laurent21da6472017-11-09 16:29:26 -0800841 output.sampleRate = input.config.sample_rate;
842 output.frameCount = input.frameCount;
843 output.notificationFrameCount = input.notificationFrameCount;
844 output.flags = input.flags;
845
Eric Laurent42984412019-05-09 17:57:03 -0700846 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700847 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800848 &output.frameCount, &output.notificationFrameCount,
849 input.notificationsPerBuffer, input.speed,
850 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700851 callingPid, input.clientInfo.clientTid, clientUid,
jiabinf6eb4c32020-02-25 14:06:25 -0800852 &lStatus, portId, input.audioTrackCallback);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800853 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700854 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700855
Eric Laurent21da6472017-11-09 16:29:26 -0800856 output.afFrameCount = thread->frameCount();
857 output.afSampleRate = thread->sampleRate();
858 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800859 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800860
Kevin Rocard153f92d2018-12-18 18:33:28 -0800861 if (lStatus == NO_ERROR) {
862 // Connect secondary outputs. Failure on a secondary output must not imped the primary
863 // Any secondary output setup failure will lead to a desync between the AP and AF until
864 // the track is destroyed.
865 TeePatches teePatches;
866 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
867 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
868 if (secondaryThread == NULL) {
869 ALOGE("no playback thread found for secondary output %d", output.outputId);
870 continue;
871 }
872
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100873 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
874 / thread->sampleRate();
875 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
876 / secondaryThread->sampleRate();
877 // If the secondary output has just been opened, the first secondaryThread write
878 // will not block as it will fill the empty startup buffer of the HAL,
879 // so a second sink buffer needs to be ready for the immediate next blocking write.
880 // Additionally, have a margin of one main thread buffer as the scheduling jitter
881 // can reorder the writes (eg if thread A&B have the same write intervale,
882 // the scheduler could schedule AB...BA)
883 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
884 // Total secondary output buffer must be at least as the read frames plus
885 // the margin of a few buffers on both sides in case the
886 // threads scheduling has some jitter.
887 // That value should not impact latency as the secondary track is started before
888 // its buffer is full, see frameCountToBeReady.
889 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
890 // The frameCount should also not be smaller than the secondary thread min frame
891 // count
892 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
893 [&] { Mutex::Autolock _l(secondaryThread->mLock);
894 return secondaryThread->latency_l(); }(),
895 secondaryThread->mNormalFrameCount,
896 secondaryThread->mSampleRate,
897 output.sampleRate,
898 input.speed);
899 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800900
901 using namespace std::chrono_literals;
902 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
903 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
904 output.sampleRate,
905 inChannelMask,
906 input.config.format,
907 frameCount,
908 NULL /* buffer */,
909 (size_t)0 /* bufferSize */,
910 AUDIO_INPUT_FLAG_DIRECT,
911 0ns /* timeout */);
912 status_t status = patchRecord->initCheck();
913 if (status != NO_ERROR) {
914 ALOGE("Secondary output patchRecord init failed: %d", status);
915 continue;
916 }
Andy Hungae22b482019-05-09 15:38:55 -0700917
918 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
919 // for fast usage: thread has fast mixer, sample rate matches, etc.;
920 // for now, we exclude fast tracks by removing the Fast flag.
921 const audio_output_flags_t outputFlags =
922 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800923 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
924 streamType,
925 output.sampleRate,
926 input.config.channel_mask,
927 input.config.format,
928 frameCount,
929 patchRecord->buffer(),
930 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700931 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100932 0ns /* timeout */,
933 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800934 status = patchTrack->initCheck();
935 if (status != NO_ERROR) {
936 ALOGE("Secondary output patchTrack init failed: %d", status);
937 continue;
938 }
939 teePatches.push_back({patchRecord, patchTrack});
940 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800941 // In case the downstream patchTrack on the secondaryThread temporarily outlives
942 // our created track, ensure the corresponding patchRecord is still alive.
943 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
944 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800945 }
946 track->setTeePatches(std::move(teePatches));
947 }
948
Eric Laurent39e94f82010-07-28 01:32:47 -0700949 // move effect chain to this output thread if an effect on same session was waiting
950 // for a track to be created
951 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700952 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700953 Mutex::Autolock _dl(thread->mLock);
954 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700955 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
956 effectThreadId = thread->id();
957 effectIds = thread->getEffectIds_l(sessionId);
958 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700959 }
Eric Laurenta011e352012-03-29 15:51:43 -0700960
961 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700962 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800963 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700964 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700965 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700966 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700967 } else {
968 mPendingSyncEvents[i]->cancel();
969 }
Eric Laurenta011e352012-03-29 15:51:43 -0700970 mPendingSyncEvents.removeAt(i);
971 i--;
972 }
973 }
974 }
Glenn Kastene198c362013-08-13 09:13:36 -0700975
Eric Laurent21da6472017-11-09 16:29:26 -0800976 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700977 }
Glenn Kastene198c362013-08-13 09:13:36 -0700978
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700979 if (lStatus != NO_ERROR) {
980 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700981 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700982 // Don't hold mClientLock when releasing the reference on the track as the
983 // destructor will acquire it.
984 {
985 Mutex::Autolock _cl(mClientLock);
986 client.clear();
987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700989 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 }
991
Eric Laurent6c796322019-04-09 14:13:17 -0700992 // effectThreadId is not NONE if an effect chain corresponding to the track session
993 // was found on another thread and must be moved on this thread
994 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
995 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
996 }
997
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700998 // return handle to client
999 trackHandle = new TrackHandle(track);
1000
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001002 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001003 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001004 }
Glenn Kasten9156ef32013-08-06 15:39:08 -07001005 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 return trackHandle;
1007}
1008
Glenn Kasten2c073da2016-02-26 09:14:08 -08001009uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010{
1011 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001012 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001014 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 return 0;
1016 }
1017 return thread->sampleRate();
1018}
1019
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001020audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021{
1022 Mutex::Autolock _l(mLock);
1023 PlaybackThread *thread = checkPlaybackThread_l(output);
1024 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001025 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001026 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 }
1028 return thread->format();
1029}
1030
Glenn Kasten2c073da2016-02-26 09:14:08 -08001031size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032{
1033 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001034 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001036 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037 return 0;
1038 }
Glenn Kasten58912562012-04-03 10:45:00 -07001039 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1040 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 return thread->frameCount();
1042}
1043
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001044size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1045{
1046 Mutex::Autolock _l(mLock);
1047 ThreadBase *thread = checkThread_l(ioHandle);
1048 if (thread == NULL) {
1049 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1050 return 0;
1051 }
1052 return thread->frameCountHAL();
1053}
1054
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001055uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056{
1057 Mutex::Autolock _l(mLock);
1058 PlaybackThread *thread = checkPlaybackThread_l(output);
1059 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001060 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 return 0;
1062 }
1063 return thread->latency();
1064}
1065
1066status_t AudioFlinger::setMasterVolume(float value)
1067{
Eric Laurenta1884f92011-08-23 08:25:03 -07001068 status_t ret = initCheck();
1069 if (ret != NO_ERROR) {
1070 return ret;
1071 }
1072
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 // check calling permissions
1074 if (!settingsAllowed()) {
1075 return PERMISSION_DENIED;
1076 }
1077
Eric Laurenta4c5a552012-03-29 10:12:40 -07001078 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001079 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001080
John Grossmanee578c02012-07-23 17:05:46 -07001081 // Set master volume in the HALs which support it.
1082 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1083 AutoMutex lock(mHardwareLock);
1084 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001085
John Grossmanee578c02012-07-23 17:05:46 -07001086 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1087 if (dev->canSetMasterVolume()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001088 dev->hwDevice()->setMasterVolume(value);
Eric Laurent93575202011-01-18 18:39:02 -08001089 }
John Grossmanee578c02012-07-23 17:05:46 -07001090 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092
John Grossmanee578c02012-07-23 17:05:46 -07001093 // Now set the master volume in each playback thread. Playback threads
1094 // assigned to HALs which do not have master volume support will apply
1095 // master volume during the mix operation. Threads with HALs which do
1096 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001097 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1098 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1099 continue;
1100 }
John Grossmanee578c02012-07-23 17:05:46 -07001101 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103
1104 return NO_ERROR;
1105}
1106
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001107status_t AudioFlinger::setMasterBalance(float balance)
1108{
1109 status_t ret = initCheck();
1110 if (ret != NO_ERROR) {
1111 return ret;
1112 }
1113
1114 // check calling permissions
1115 if (!settingsAllowed()) {
1116 return PERMISSION_DENIED;
1117 }
1118
1119 // check range
1120 if (isnan(balance) || fabs(balance) > 1.f) {
1121 return BAD_VALUE;
1122 }
1123
1124 Mutex::Autolock _l(mLock);
1125
1126 // short cut.
1127 if (mMasterBalance == balance) return NO_ERROR;
1128
1129 mMasterBalance = balance;
1130
1131 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1132 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1133 continue;
1134 }
1135 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1136 }
1137
1138 return NO_ERROR;
1139}
1140
Glenn Kastenf78aee72012-01-04 11:00:47 -08001141status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142{
Eric Laurenta1884f92011-08-23 08:25:03 -07001143 status_t ret = initCheck();
1144 if (ret != NO_ERROR) {
1145 return ret;
1146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147
1148 // check calling permissions
1149 if (!settingsAllowed()) {
1150 return PERMISSION_DENIED;
1151 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001152 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001153 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 return BAD_VALUE;
1155 }
1156
1157 { // scope for the lock
1158 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001159 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001161 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mHardwareStatus = AUDIO_HW_IDLE;
1163 }
1164
1165 if (NO_ERROR == ret) {
1166 Mutex::Autolock _l(mLock);
1167 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001168 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001169 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 }
1171
1172 return ret;
1173}
1174
1175status_t AudioFlinger::setMicMute(bool state)
1176{
Eric Laurenta1884f92011-08-23 08:25:03 -07001177 status_t ret = initCheck();
1178 if (ret != NO_ERROR) {
1179 return ret;
1180 }
1181
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 // check calling permissions
1183 if (!settingsAllowed()) {
1184 return PERMISSION_DENIED;
1185 }
1186
1187 AutoMutex lock(mHardwareLock);
Eric Laurent2325bf02020-04-08 19:38:13 -07001188 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1189 if (primaryDev == nullptr) {
1190 ALOGW("%s: no primary HAL device", __func__);
1191 return INVALID_OPERATION;
1192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001194 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001196 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001197 if (dev != primaryDev) {
1198 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001199 }
1200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001202 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 return ret;
1204}
1205
1206bool AudioFlinger::getMicMute() const
1207{
Eric Laurenta1884f92011-08-23 08:25:03 -07001208 status_t ret = initCheck();
1209 if (ret != NO_ERROR) {
1210 return false;
1211 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001212 AutoMutex lock(mHardwareLock);
Eric Laurent2325bf02020-04-08 19:38:13 -07001213 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1214 if (primaryDev == nullptr) {
1215 ALOGW("%s: no primary HAL device", __func__);
1216 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001217 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001218 bool state;
1219 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1220 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001222 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1223 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224}
1225
Eric Laurent5ada82e2019-08-29 17:53:54 -07001226void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001227{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001228 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001229
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001230 AutoMutex lock(mLock);
1231 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001232 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001233 }
1234 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001235 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001236 }
1237}
1238
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239status_t AudioFlinger::setMasterMute(bool muted)
1240{
John Grossmand8f178d2012-07-20 14:51:35 -07001241 status_t ret = initCheck();
1242 if (ret != NO_ERROR) {
1243 return ret;
1244 }
1245
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 // check calling permissions
1247 if (!settingsAllowed()) {
1248 return PERMISSION_DENIED;
1249 }
1250
John Grossmanee578c02012-07-23 17:05:46 -07001251 Mutex::Autolock _l(mLock);
1252 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001253
John Grossmanee578c02012-07-23 17:05:46 -07001254 // Set master mute in the HALs which support it.
1255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1256 AutoMutex lock(mHardwareLock);
1257 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001258
John Grossmanee578c02012-07-23 17:05:46 -07001259 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1260 if (dev->canSetMasterMute()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001261 dev->hwDevice()->setMasterMute(muted);
John Grossmand8f178d2012-07-20 14:51:35 -07001262 }
John Grossmanee578c02012-07-23 17:05:46 -07001263 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001264 }
1265
John Grossmanee578c02012-07-23 17:05:46 -07001266 // Now set the master mute in each playback thread. Playback threads
1267 // assigned to HALs which do not have master mute support will apply master
1268 // mute during the mix operation. Threads with HALs which do support master
1269 // mute will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001270 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1271 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1272 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001273 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274
1275 return NO_ERROR;
1276}
1277
1278float AudioFlinger::masterVolume() const
1279{
Glenn Kasten98067102011-12-13 11:47:54 -08001280 Mutex::Autolock _l(mLock);
1281 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282}
1283
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001284status_t AudioFlinger::getMasterBalance(float *balance) const
1285{
1286 Mutex::Autolock _l(mLock);
1287 *balance = getMasterBalance_l();
1288 return NO_ERROR; // if called through binder, may return a transactional error
1289}
1290
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291bool AudioFlinger::masterMute() const
1292{
Glenn Kasten98067102011-12-13 11:47:54 -08001293 Mutex::Autolock _l(mLock);
1294 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295}
1296
John Grossman4ff14ba2012-02-08 16:37:41 -08001297float AudioFlinger::masterVolume_l() const
1298{
John Grossman4ff14ba2012-02-08 16:37:41 -08001299 return mMasterVolume;
1300}
1301
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001302float AudioFlinger::getMasterBalance_l() const
1303{
1304 return mMasterBalance;
1305}
1306
John Grossmand8f178d2012-07-20 14:51:35 -07001307bool AudioFlinger::masterMute_l() const
1308{
John Grossmanee578c02012-07-23 17:05:46 -07001309 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001310}
1311
Eric Laurent223fd5c2014-11-11 13:43:36 -08001312status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1313{
1314 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001315 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001316 return BAD_VALUE;
1317 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001318 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1319 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1320 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001321 return PERMISSION_DENIED;
1322 }
1323
1324 return NO_ERROR;
1325}
1326
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001327status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1328 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329{
1330 // check calling permissions
1331 if (!settingsAllowed()) {
1332 return PERMISSION_DENIED;
1333 }
1334
Eric Laurent223fd5c2014-11-11 13:43:36 -08001335 status_t status = checkStreamType(stream);
1336 if (status != NO_ERROR) {
1337 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338 }
Eric Laurent98e38192018-02-15 18:31:53 -08001339 if (output == AUDIO_IO_HANDLE_NONE) {
1340 return BAD_VALUE;
1341 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001342 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1343 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344
1345 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001346 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1347 if (volumeInterface == NULL) {
1348 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349 }
Eric Laurent98e38192018-02-15 18:31:53 -08001350 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351
1352 return NO_ERROR;
1353}
1354
Glenn Kastenfff6d712012-01-12 16:38:12 -08001355status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356{
1357 // check calling permissions
1358 if (!settingsAllowed()) {
1359 return PERMISSION_DENIED;
1360 }
1361
Eric Laurent223fd5c2014-11-11 13:43:36 -08001362 status_t status = checkStreamType(stream);
1363 if (status != NO_ERROR) {
1364 return status;
1365 }
1366 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1367
1368 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001369 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370 return BAD_VALUE;
1371 }
1372
Eric Laurent93575202011-01-18 18:39:02 -08001373 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001375 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1376 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1377 volumeInterfaces[i]->setStreamMute(stream, muted);
1378 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379
1380 return NO_ERROR;
1381}
1382
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001383float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001385 status_t status = checkStreamType(stream);
1386 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 return 0.0f;
1388 }
Eric Laurent98e38192018-02-15 18:31:53 -08001389 if (output == AUDIO_IO_HANDLE_NONE) {
1390 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 }
1392
Eric Laurent98e38192018-02-15 18:31:53 -08001393 AutoMutex lock(mLock);
1394 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1395 if (volumeInterface == NULL) {
1396 return 0.0f;
1397 }
1398
1399 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400}
1401
Glenn Kastenfff6d712012-01-12 16:38:12 -08001402bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001404 status_t status = checkStreamType(stream);
1405 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 return true;
1407 }
1408
Glenn Kasten6637baa2012-01-09 09:40:36 -08001409 AutoMutex lock(mLock);
1410 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411}
1412
Eric Laurent054d9d32015-04-24 08:48:48 -07001413
1414void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1415{
1416 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1417 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1418 }
1419}
1420
jiabinc52b1ff2019-10-31 17:20:42 -07001421void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1422{
1423 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1424 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1425 }
1426}
1427
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001428// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1429void AudioFlinger::forwardParametersToDownstreamPatches_l(
1430 audio_io_handle_t upStream, const String8& keyValuePairs,
1431 std::function<bool(const sp<PlaybackThread>&)> useThread)
1432{
1433 std::vector<PatchPanel::SoftwarePatch> swPatches;
1434 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1435 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1436 __func__, swPatches.size(), upStream);
1437 for (const auto& swPatch : swPatches) {
1438 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1439 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1440 downStream->setParameters(keyValuePairs);
1441 }
1442 }
1443}
1444
Eric Laurentf1047e82018-04-16 19:18:20 -07001445// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1446// Some keys are used for audio routing and audio path configuration and should be reserved for use
1447// by audio policy and audio flinger for functional, privacy and security reasons.
1448void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1449{
1450 static const String8 kReservedParameters[] = {
1451 String8(AudioParameter::keyRouting),
1452 String8(AudioParameter::keySamplingRate),
1453 String8(AudioParameter::keyFormat),
1454 String8(AudioParameter::keyChannels),
1455 String8(AudioParameter::keyFrameCount),
1456 String8(AudioParameter::keyInputSource),
1457 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001458 String8(AudioParameter::keyDeviceConnect),
1459 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001460 String8(AudioParameter::keyStreamSupportedFormats),
1461 String8(AudioParameter::keyStreamSupportedChannels),
1462 String8(AudioParameter::keyStreamSupportedSamplingRates),
1463 };
1464
Andy Hung4ef19fa2018-05-15 19:35:29 -07001465 if (isAudioServerUid(callingUid)) {
1466 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001467 }
1468
1469 AudioParameter param = AudioParameter(keyValuePairs);
1470 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001471 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001472 for (auto& key : kReservedParameters) {
1473 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001474 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001475 param.remove(key);
1476 }
1477 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001478 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1479 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001480 keyValuePairs = param.toString();
1481}
1482
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001483void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1484 size_t rejectedKVPSize, const String8& rejectedKVPs,
1485 uid_t callingUid) {
1486 auto prefix = String8::format("UID %5d", callingUid);
1487 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1488 if (rejectedKVPSize != 0) {
1489 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1490 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1491 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1492 } else {
1493 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1494 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1495 }
1496}
1497
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001498status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499{
Eric Laurentf1047e82018-04-16 19:18:20 -07001500 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1501 ioHandle, keyValuePairs.string(),
1502 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001503
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 // check calling permissions
1505 if (!settingsAllowed()) {
1506 return PERMISSION_DENIED;
1507 }
1508
Eric Laurentf1047e82018-04-16 19:18:20 -07001509 String8 filteredKeyValuePairs = keyValuePairs;
1510 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1511
1512 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1513
Glenn Kasten142f5192014-03-25 17:44:59 -07001514 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1515 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001516 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001517 // result will remain NO_INIT if no audio device is present
1518 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001519 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001520 AutoMutex lock(mHardwareLock);
1521 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1522 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001523 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001524 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001525 // return success if at least one audio device accepts the parameters as not all
1526 // HALs are requested to support all parameters. If no audio device supports the
1527 // requested parameters, the last error is reported.
1528 if (final_result != NO_ERROR) {
1529 final_result = result;
1530 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001531 }
1532 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001533 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001534 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001535 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001536 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001537 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1538 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001539 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001540 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001541 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001542 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001543 }
1544 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001545 String8 screenState;
1546 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001547 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001548 if (isOff != (AudioFlinger::mScreenState & 1)) {
1549 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001550 }
1551 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001552 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 }
1554
1555 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1556 // and the thread is exited once the lock is released
1557 sp<ThreadBase> thread;
1558 {
1559 Mutex::Autolock _l(mLock);
1560 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001561 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001563 if (thread == 0) {
1564 thread = checkMmapThread_l(ioHandle);
1565 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001566 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001567 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001568 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001569 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001570 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1571 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001572 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001574 }
1575 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001576 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001577 status_t result = thread->setParameters(filteredKeyValuePairs);
1578 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1579 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 }
1581 return BAD_VALUE;
1582}
1583
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001584String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001585{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001586 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1587 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588
Eric Laurenta4c5a552012-03-29 10:12:40 -07001589 Mutex::Autolock _l(mLock);
1590
Glenn Kasten142f5192014-03-25 17:44:59 -07001591 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001592 String8 out_s8;
1593
Dima Zavin799a70e2011-04-18 16:57:27 -07001594 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001595 String8 s;
1596 status_t result;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001597 {
1598 AutoMutex lock(mHardwareLock);
1599 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001600 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1601 result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001602 mHardwareStatus = AUDIO_HW_IDLE;
1603 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001604 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001605 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001606 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 }
1608
Eric Laurent6acd1d42017-01-04 14:23:29 -08001609 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1610 if (thread == NULL) {
1611 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1612 if (thread == NULL) {
1613 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1614 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001615 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001616 }
1617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001619 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620}
1621
Glenn Kastendd8104c2012-07-02 12:42:44 -07001622size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1623 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624{
Eric Laurenta1884f92011-08-23 08:25:03 -07001625 status_t ret = initCheck();
1626 if (ret != NO_ERROR) {
1627 return 0;
1628 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001629 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001630 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001631 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001632 return 0;
1633 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001634
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001635 AutoMutex lock(mHardwareLock);
1636 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001637
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001638 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001639 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1640 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1641 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1642 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1643 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1644
1645 std::vector<audio_format_t> formats = {format};
1646 if (format != AUDIO_FORMAT_PCM_16_BIT)
1647 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1648
1649 std::vector<uint32_t> sampleRates = {sampleRate};
1650 static const uint32_t SR_44100 = 44100;
1651 static const uint32_t SR_48000 = 48000;
1652
1653 if (sampleRate != SR_48000)
1654 sampleRates.push_back(SR_48000);
1655 if (sampleRate != SR_44100)
1656 sampleRates.push_back(SR_44100);
1657
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001658 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001659
Robin Lee9899ff72019-12-24 22:02:08 +01001660 // Change parameters of the configuration each iteration until we find a
1661 // configuration that the device will support.
1662 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001663 for (auto testChannelMask : channelMasks) {
1664 config.channel_mask = testChannelMask;
1665 for (auto testFormat : formats) {
1666 config.format = testFormat;
1667 for (auto testSampleRate : sampleRates) {
1668 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001669
Judy Hsiaoabab5222019-11-09 18:14:58 +08001670 size_t bytes = 0;
1671 status_t result = dev->getInputBufferSize(&config, &bytes);
1672 if (result != OK || bytes == 0) {
1673 continue;
1674 }
1675
1676 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1677 config.format != format) {
1678 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1679 uint32_t srcChannelCount =
1680 audio_channel_count_from_in_mask(config.channel_mask);
1681 size_t srcFrames =
1682 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1683 size_t dstFrames = destinationFramesPossible(
1684 srcFrames, config.sample_rate, sampleRate);
1685 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1686 }
1687 return bytes;
1688 }
1689 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001690 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001691
1692 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1693 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1694 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Glenn Kasten5f972c02014-01-13 09:59:31 -08001697uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 Mutex::Autolock _l(mLock);
1700
1701 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1702 if (recordThread != NULL) {
1703 return recordThread->getInputFramesLost();
1704 }
1705 return 0;
1706}
1707
1708status_t AudioFlinger::setVoiceVolume(float value)
1709{
Eric Laurenta1884f92011-08-23 08:25:03 -07001710 status_t ret = initCheck();
1711 if (ret != NO_ERROR) {
1712 return ret;
1713 }
1714
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 // check calling permissions
1716 if (!settingsAllowed()) {
1717 return PERMISSION_DENIED;
1718 }
1719
1720 AutoMutex lock(mHardwareLock);
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001721 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001722 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001723 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 mHardwareStatus = AUDIO_HW_IDLE;
1725
1726 return ret;
1727}
1728
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001729status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001730 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 Mutex::Autolock _l(mLock);
1733
1734 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1735 if (playbackThread != NULL) {
1736 return playbackThread->getRenderPosition(halFrames, dspFrames);
1737 }
1738
1739 return BAD_VALUE;
1740}
1741
1742void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1743{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001745 if (client == 0) {
1746 return;
1747 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001748 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001749 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001750 {
1751 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001752 if (mNotificationClients.indexOfKey(pid) < 0) {
1753 sp<NotificationClient> notificationClient = new NotificationClient(this,
1754 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001755 pid,
1756 uid);
1757 ALOGV("registerClient() client %p, pid %d, uid %u",
1758 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759
Eric Laurent021cf962014-05-13 10:18:14 -07001760 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761
Marco Nelissen06b46062014-11-14 07:58:25 -08001762 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001763 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001764 }
1765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766
Eric Laurent021cf962014-05-13 10:18:14 -07001767 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001768 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001769 // the config change is always sent from playback or record threads to avoid deadlock
1770 // with AudioSystem::gLock
1771 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001772 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001773 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001775 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001776 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 }
1778}
1779
1780void AudioFlinger::removeNotificationClient(pid_t pid)
1781{
Eric Laurent6c796322019-04-09 14:13:17 -07001782 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001783 {
Eric Laurent6c796322019-04-09 14:13:17 -07001784 Mutex::Autolock _l(mLock);
1785 {
1786 Mutex::Autolock _cl(mClientLock);
1787 mNotificationClients.removeItem(pid);
1788 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001789
Eric Laurent6c796322019-04-09 14:13:17 -07001790 ALOGV("%d died, releasing its sessions", pid);
1791 size_t num = mAudioSessionRefs.size();
1792 bool removed = false;
1793 for (size_t i = 0; i < num; ) {
1794 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1795 ALOGV(" pid %d @ %zu", ref->mPid, i);
1796 if (ref->mPid == pid) {
1797 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1798 mAudioSessionRefs.removeAt(i);
1799 delete ref;
1800 removed = true;
1801 num--;
1802 } else {
1803 i++;
1804 }
1805 }
1806 if (removed) {
1807 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001808 }
1809 }
Eric Laurent6c796322019-04-09 14:13:17 -07001810 for (auto& effect : removedEffects) {
1811 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813}
1814
Eric Laurent73e26b62015-04-27 16:55:58 -07001815void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001816 const sp<AudioIoDescriptor>& ioDesc,
1817 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818{
Eric Laurent021cf962014-05-13 10:18:14 -07001819 Mutex::Autolock _l(mClientLock);
1820 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001822 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1823 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 }
1826}
1827
Eric Laurent021cf962014-05-13 10:18:14 -07001828// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001829void AudioFlinger::removeClient_l(pid_t pid)
1830{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001831 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001832 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 mClients.removeItem(pid);
1834}
1835
Eric Laurent717e1282012-06-29 16:36:52 -07001836// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001837sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1838 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001839{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001840 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001841
1842 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001843 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001844 ALOG_ASSERT(thread == 0);
1845 thread = mPlaybackThreads.valueAt(i);
1846 }
1847 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001848 if (thread != nullptr) {
1849 return thread;
1850 }
1851 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1852 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1853 ALOG_ASSERT(thread == 0);
1854 thread = mRecordThreads.valueAt(i);
1855 }
1856 }
1857 if (thread != nullptr) {
1858 return thread;
1859 }
1860 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1861 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1862 ALOG_ASSERT(thread == 0);
1863 thread = mMmapThreads.valueAt(i);
1864 }
1865 }
Eric Laurent717e1282012-06-29 16:36:52 -07001866 return thread;
1867}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870
1871// ----------------------------------------------------------------------------
1872
1873AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1874 : RefBase(),
1875 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001876 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877{
Andy Hung6f248bb2018-01-23 14:04:37 -08001878 mMemoryDealer = new MemoryDealer(
1879 audioFlinger->getClientSharedHeapSize(),
1880 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881}
1882
Eric Laurent021cf962014-05-13 10:18:14 -07001883// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884AudioFlinger::Client::~Client()
1885{
1886 mAudioFlinger->removeClient_l(mPid);
1887}
1888
Glenn Kasten435dbe62012-01-30 10:15:48 -08001889sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890{
1891 return mMemoryDealer;
1892}
1893
1894// ----------------------------------------------------------------------------
1895
1896AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1897 const sp<IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001898 pid_t pid,
1899 uid_t uid)
1900 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901{
1902}
1903
1904AudioFlinger::NotificationClient::~NotificationClient()
1905{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906}
1907
Glenn Kasten0f11b512014-01-31 16:18:54 -08001908void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909{
1910 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001911 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912}
1913
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001914// ----------------------------------------------------------------------------
1915AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1916 : mPendingRequests(false) {}
1917
1918
1919void AudioFlinger::MediaLogNotifier::requestMerge() {
1920 AutoMutex _l(mMutex);
1921 mPendingRequests = true;
1922 mCond.signal();
1923}
1924
1925bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001926 // Should already have been checked, but just in case
1927 if (sMediaLogService == 0) {
1928 return false;
1929 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001930 // Wait until there are pending requests
1931 {
1932 AutoMutex _l(mMutex);
1933 mPendingRequests = false; // to ignore past requests
1934 while (!mPendingRequests) {
1935 mCond.wait(mMutex);
1936 // TODO may also need an exitPending check
1937 }
1938 mPendingRequests = false;
1939 }
1940 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001941 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001942 usleep(kPostTriggerSleepPeriod);
1943 return true;
1944}
1945
1946void AudioFlinger::requestLogMerge() {
1947 mMediaLogNotifier->requestMerge();
1948}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949
1950// ----------------------------------------------------------------------------
1951
Eric Laurentf14db3c2017-12-08 14:20:36 -08001952sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1953 CreateRecordOutput& output,
1954 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955{
1956 sp<RecordThread::RecordTrack> recordTrack;
1957 sp<RecordHandle> recordHandle;
1958 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08001960 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08001961 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962
Eric Laurentf14db3c2017-12-08 14:20:36 -08001963 output.cblk.clear();
1964 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08001965 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07001966
Eric Laurentf14db3c2017-12-08 14:20:36 -08001967 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001968 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08001969 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07001970 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001971 ALOGW_IF(clientUid != callingUid,
1972 "%s uid %d tried to pass itself off as %d",
1973 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07001974 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001975 updatePid = true;
1976 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001977 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07001978 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001979 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08001980 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001981 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08001982 __func__, callingUid, callingPid, clientPid);
1983 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07001984 }
1985
Andy Hung6770c6f2015-04-07 13:43:36 -07001986 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08001987 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
1988 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07001989 lStatus = BAD_VALUE;
1990 goto Exit;
1991 }
1992
Glenn Kasten53b5d092014-02-05 10:00:23 -08001993 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08001994 if (!audio_is_input_channel(input.config.channel_mask)) {
1995 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001996 lStatus = BAD_VALUE;
1997 goto Exit;
1998 }
1999
Eric Laurentf14db3c2017-12-08 14:20:36 -08002000 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2001 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2002 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2003 lStatus = BAD_VALUE;
2004 goto Exit;
2005 }
2006
2007 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002008 output.selectedDeviceId = input.selectedDeviceId;
2009 output.flags = input.flags;
2010
2011 client = registerPid(clientPid);
2012
2013 // Not a conventional loop, but a retry loop for at most two iterations total.
2014 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2015 // Exits loop via break on no error of got exit on error
2016 // The sp<> references will be dropped when re-entering scope.
2017 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2018 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002019 // release previously opened input if retrying.
2020 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2021 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002022 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002023 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002024 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002025 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002026 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002027 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002028 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002029 sessionId,
2030 // FIXME compare to AudioTrack
2031 clientPid,
2032 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002033 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002034 &input.config,
2035 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002036 if (lStatus != NO_ERROR) {
2037 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2038 goto Exit;
2039 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002040
Glenn Kasten05997e22014-03-13 15:08:33 -07002041 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002043 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 if (thread == NULL) {
jiabinc1de2df2019-05-07 14:26:40 -07002045 ALOGE("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 lStatus = BAD_VALUE;
2047 goto Exit;
2048 }
2049
Eric Laurentf14db3c2017-12-08 14:20:36 -08002050 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051
Eric Laurentf14db3c2017-12-08 14:20:36 -08002052 output.sampleRate = input.config.sample_rate;
2053 output.frameCount = input.frameCount;
2054 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002055
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002056 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002057 input.config.format, input.config.channel_mask,
2058 &output.frameCount, sessionId,
2059 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002060 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002061 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002062 &lStatus, portId,
2063 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002064 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002065
Eric Laurentf14db3c2017-12-08 14:20:36 -08002066 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2067 // audio policy manager without FAST constraint
2068 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002069 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002070 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002071
2072 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002073 goto Exit;
2074 }
2075
2076 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2077 // session and move it to this thread.
2078 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2079 if (chain != 0) {
2080 Mutex::Autolock _l(thread->mLock);
2081 thread->addEffectChain_l(chain);
2082 }
2083 break;
2084 }
2085 // End of retry loop.
2086 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 }
Glenn Kastene198c362013-08-13 09:13:36 -07002088
Eric Laurentf14db3c2017-12-08 14:20:36 -08002089 output.cblk = recordTrack->getCblk();
2090 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002091 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002092
2093 // return handle to client
2094 recordHandle = new RecordHandle(recordTrack);
2095
2096Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002097 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002098 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002099 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002100 // Don't hold mClientLock when releasing the reference on the track as the
2101 // destructor will acquire it.
2102 {
2103 Mutex::Autolock _cl(mClientLock);
2104 client.clear();
2105 }
Eric Laurent896c9672017-12-08 14:08:45 -08002106 recordTrack.clear();
2107 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002108 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 }
2111
Glenn Kasten9156ef32013-08-06 15:39:08 -07002112 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 return recordHandle;
2114}
2115
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002116
2117
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118// ----------------------------------------------------------------------------
2119
Eric Laurenta4c5a552012-03-29 10:12:40 -07002120audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2121{
Eric Laurent44622db2014-08-01 19:00:33 -07002122 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002123 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002124 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002125 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002126 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002127 }
2128 Mutex::Autolock _l(mLock);
2129 return loadHwModule_l(name);
2130}
2131
2132// loadHwModule_l() must be called with AudioFlinger::mLock held
2133audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2134{
2135 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2136 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2137 ALOGW("loadHwModule() module %s already loaded", name);
2138 return mAudioHwDevs.keyAt(i);
2139 }
2140 }
2141
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002142 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002143
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002144 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002145 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002146 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002147 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002148 }
2149
2150 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002151 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002152 mHardwareStatus = AUDIO_HW_IDLE;
2153 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002154 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002155 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002156 }
2157
John Grossmanee578c02012-07-23 17:05:46 -07002158 // Check and cache this HAL's level of support for master mute and master
2159 // volume. If this is the first HAL opened, and it supports the get
2160 // methods, use the initial values provided by the HAL as the current
2161 // master mute and volume settings.
2162
2163 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2164 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07002165 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07002166
2167 if (0 == mAudioHwDevs.size()) {
2168 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002169 float mv;
2170 if (OK == dev->getMasterVolume(&mv)) {
2171 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002172 }
2173
2174 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002175 bool mm;
2176 if (OK == dev->getMasterMute(&mm)) {
2177 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002178 }
2179 }
2180
Eric Laurenta4c5a552012-03-29 10:12:40 -07002181 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002182 if (OK == dev->setMasterVolume(mMasterVolume)) {
John Grossmanee578c02012-07-23 17:05:46 -07002183 flags = static_cast<AudioHwDevice::Flags>(flags |
2184 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2185 }
2186
2187 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002188 if (OK == dev->setMasterMute(mMasterMute)) {
John Grossmanee578c02012-07-23 17:05:46 -07002189 flags = static_cast<AudioHwDevice::Flags>(flags |
2190 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2191 }
2192
Eric Laurenta4c5a552012-03-29 10:12:40 -07002193 mHardwareStatus = AUDIO_HW_IDLE;
2194 }
Mikhail Naganov97373b02018-07-23 13:27:24 -07002195 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002196 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2197 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2198 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002199
Glenn Kastena13cde92016-03-28 15:26:02 -07002200 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent83b88082014-06-20 18:31:16 -07002201 mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07002202
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002203 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002204
2205 return handle;
2206
2207}
2208
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002209// ----------------------------------------------------------------------------
2210
Glenn Kasten3b16c762012-11-14 08:44:39 -08002211uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002212{
2213 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002214 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002215 return thread != NULL ? thread->sampleRate() : 0;
2216}
2217
Glenn Kastene33054e2012-11-14 12:54:39 -08002218size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002219{
2220 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002221 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002222 return thread != NULL ? thread->frameCountHAL() : 0;
2223}
2224
2225// ----------------------------------------------------------------------------
2226
Andy Hung6f248bb2018-01-23 14:04:37 -08002227status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002228{
2229 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002230 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002231 return PERMISSION_DENIED;
2232 }
2233 Mutex::Autolock _l(mLock);
2234 if (mIsDeviceTypeKnown) {
2235 return INVALID_OPERATION;
2236 }
2237 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002238 mTotalMemory = totalMemory;
2239 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2240 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2241 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2242 // though actual setting is determined through device configuration.
2243 constexpr int64_t GB = 1024 * 1024 * 1024;
2244 mClientSharedHeapSize =
2245 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2246 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2247 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2248 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2249 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002250 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002251
2252 // TODO: Cache the client shared heap size in a persistent property.
2253 // It's possible that a native process or Java service or app accesses audioserver
2254 // after it is registered by system server, but before AudioService updates
2255 // the memory info. This would occur immediately after boot or an audioserver
2256 // crash and restore. Before update from AudioService, the client would get the
2257 // minimum heap size.
2258
2259 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2260 (isLowRamDevice ? "true" : "false"),
2261 (long long)mTotalMemory,
2262 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002263 return NO_ERROR;
2264}
2265
Andy Hung6f248bb2018-01-23 14:04:37 -08002266size_t AudioFlinger::getClientSharedHeapSize() const
2267{
2268 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2269 if (heapSizeInBytes != 0) { // read-only property overrides all.
2270 return heapSizeInBytes;
2271 }
2272 return mClientSharedHeapSize;
2273}
2274
Mikhail Naganovdea53042018-04-26 13:10:21 -07002275status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2276{
2277 ALOGV(__func__);
2278
2279 audio_module_handle_t module;
2280 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2281 module = config->ext.device.hw_module;
2282 } else {
2283 module = config->ext.mix.hw_module;
2284 }
2285
2286 Mutex::Autolock _l(mLock);
2287 ssize_t index = mAudioHwDevs.indexOfKey(module);
2288 if (index < 0) {
2289 ALOGW("%s() bad hw module %d", __func__, module);
2290 return BAD_VALUE;
2291 }
2292
2293 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2294 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2295}
2296
Eric Laurent93c3d412014-08-01 14:48:35 -07002297audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2298{
2299 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002300
2301 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2302 if (index >= 0) {
2303 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2304 mHwAvSyncIds.valueAt(index), sessionId);
2305 return mHwAvSyncIds.valueAt(index);
2306 }
2307
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002308 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Eric Laurentfa90e842014-10-17 18:12:31 -07002309 if (dev == NULL) {
2310 return AUDIO_HW_SYNC_INVALID;
2311 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002312 String8 reply;
2313 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002314 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002315 param = AudioParameter(reply);
2316 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002317
2318 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002319 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002320 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2321 return AUDIO_HW_SYNC_INVALID;
2322 }
2323
2324 // allow only one session for a given HW A/V sync ID.
2325 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2326 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2327 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2328 value, mHwAvSyncIds.keyAt(i));
2329 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002330 break;
2331 }
2332 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002333
2334 mHwAvSyncIds.add(sessionId, value);
2335
2336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2337 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2338 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002339 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002340 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002341 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002342 String8 keyValuePairs = param.toString();
2343 thread->setParameters(keyValuePairs);
2344 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2345 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002346 break;
2347 }
2348 }
2349
2350 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2351 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002352}
2353
Eric Laurent72e3f392015-05-20 14:43:50 -07002354status_t AudioFlinger::systemReady()
2355{
2356 Mutex::Autolock _l(mLock);
2357 ALOGI("%s", __FUNCTION__);
2358 if (mSystemReady) {
2359 ALOGW("%s called twice", __FUNCTION__);
2360 return NO_ERROR;
2361 }
2362 mSystemReady = true;
2363 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2364 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2365 thread->systemReady();
2366 }
2367 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2368 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2369 thread->systemReady();
2370 }
2371 return NO_ERROR;
2372}
2373
jiabin46a76fa2018-01-05 10:18:21 -08002374status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2375{
jiabin9ff780e2018-03-19 18:19:52 -07002376 AutoMutex lock(mHardwareLock);
2377 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
2378 status_t status = dev->getMicrophones(microphones);
2379 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002380}
2381
Eric Laurentfa90e842014-10-17 18:12:31 -07002382// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2383void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2384{
2385 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2386 if (index >= 0) {
2387 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2388 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2389 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002390 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002391 String8 keyValuePairs = param.toString();
2392 thread->setParameters(keyValuePairs);
2393 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2394 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002395 }
2396}
2397
2398
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002399// ----------------------------------------------------------------------------
2400
Eric Laurent83b88082014-06-20 18:31:16 -07002401
Eric Laurent6acd1d42017-01-04 14:23:29 -08002402sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002403 audio_io_handle_t *output,
2404 audio_config_t *config,
2405 audio_devices_t deviceType,
2406 const String8& address,
2407 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002408{
jiabin43810402019-10-24 14:58:31 -07002409 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002410 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002411 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002412 }
2413
Eric Laurentcf2c0212014-07-25 16:20:43 -07002414 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002415 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2416 } else {
2417 // Audio Policy does not currently request a specific output handle.
2418 // If this is ever needed, see openInput_l() for example code.
2419 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2420 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002421 }
Eric Laurent83b88082014-06-20 18:31:16 -07002422
2423 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2424
Eric Laurent83b88082014-06-20 18:31:16 -07002425 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002426 // This if statement allows overriding the audio policy settings
2427 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2428 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2429 // Check only for Normal Mixing mode
2430 if (kEnableExtendedPrecision) {
2431 // Specify format (uncomment one below to choose)
2432 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2433 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2434 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2435 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002436 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002437 }
2438 if (kEnableExtendedChannels) {
2439 // Specify channel mask (uncomment one below to choose)
2440 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2441 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2442 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2443 }
Eric Laurent83b88082014-06-20 18:31:16 -07002444 }
2445
Phil Burk062e67a2015-02-11 13:40:50 -08002446 AudioStreamOut *outputStream = NULL;
2447 status_t status = outHwDev->openOutputStream(
2448 &outputStream,
2449 *output,
jiabin43810402019-10-24 14:58:31 -07002450 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002451 flags,
2452 config,
2453 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002454
2455 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002456
Phil Burk062e67a2015-02-11 13:40:50 -08002457 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002458 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2459 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002460 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002461 mMmapThreads.add(*output, thread);
2462 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2463 *output, thread.get());
2464 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002465 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002466 sp<PlaybackThread> thread;
2467 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002468 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002469 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2470 *output, thread.get());
2471 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2472 || !isValidPcmSinkFormat(config->format)
2473 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002474 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002475 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2476 *output, thread.get());
2477 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002478 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002479 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2480 *output, thread.get());
2481 }
2482 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002483 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002484 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002485 }
Eric Laurent83b88082014-06-20 18:31:16 -07002486 }
2487
2488 return 0;
2489}
2490
Eric Laurentcf2c0212014-07-25 16:20:43 -07002491status_t AudioFlinger::openOutput(audio_module_handle_t module,
2492 audio_io_handle_t *output,
2493 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002494 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002495 uint32_t *latencyMs,
2496 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497{
jiabin43810402019-10-24 14:58:31 -07002498 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002499 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002500 this, module,
jiabin43810402019-10-24 14:58:31 -07002501 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002502 config->sample_rate,
2503 config->format,
2504 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002505 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506
jiabin43810402019-10-24 14:58:31 -07002507 audio_devices_t deviceType = device->type();
2508 const String8 address = String8(device->address().c_str());
2509
2510 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002511 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002513
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 Mutex::Autolock _l(mLock);
2515
jiabin43810402019-10-24 14:58:31 -07002516 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002517 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002518 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2519 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2520 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521
Eric Laurent6acd1d42017-01-04 14:23:29 -08002522 // notify client processes of the new output creation
2523 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002524
Eric Laurent6acd1d42017-01-04 14:23:29 -08002525 // the first primary output opened designates the primary hw device
2526 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002527 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002528 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002529
Eric Laurent6acd1d42017-01-04 14:23:29 -08002530 AutoMutex lock(mHardwareLock);
2531 mHardwareStatus = AUDIO_HW_SET_MODE;
2532 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2533 mHardwareStatus = AUDIO_HW_IDLE;
2534 }
2535 } else {
2536 MmapThread *mmapThread = (MmapThread *)thread.get();
2537 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002538 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002539 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 }
2541
Eric Laurentcf2c0212014-07-25 16:20:43 -07002542 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543}
2544
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002545audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2546 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547{
2548 Mutex::Autolock _l(mLock);
2549 MixerThread *thread1 = checkMixerThread_l(output1);
2550 MixerThread *thread2 = checkMixerThread_l(output2);
2551
2552 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002553 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2554 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002555 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 }
2557
Glenn Kasteneeecb982016-02-26 10:44:04 -08002558 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002559 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560 thread->addOutputTrack(thread2);
2561 mPlaybackThreads.add(id, thread);
2562 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002563 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 return id;
2565}
2566
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002567status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568{
Glenn Kastend96c5722012-04-25 13:44:49 -07002569 return closeOutput_nonvirtual(output);
2570}
2571
2572status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2573{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 // keep strong reference on the playback thread so that
2575 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002576 sp<PlaybackThread> playbackThread;
2577 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 {
2579 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002580 playbackThread = checkPlaybackThread_l(output);
2581 if (playbackThread != NULL) {
2582 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583
Andy Hungdc099c22018-09-18 13:46:39 -07002584 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002585
Eric Laurent6acd1d42017-01-04 14:23:29 -08002586 if (playbackThread->type() == ThreadBase::MIXER) {
2587 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2588 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2589 DuplicatingThread *dupThread =
2590 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2591 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2592 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002593 }
2594 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002595
2596
Eric Laurent6acd1d42017-01-04 14:23:29 -08002597 mPlaybackThreads.removeItem(output);
2598 // save all effects to the default thread
2599 if (mPlaybackThreads.size()) {
2600 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2601 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002602 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002603 Mutex::Autolock _dl(dstThread->mLock);
2604 Mutex::Autolock _sl(playbackThread->mLock);
2605 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2606 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002607 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002608 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 }
2611 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002612 } else {
2613 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2614 if (mmapThread == 0) {
2615 return BAD_VALUE;
2616 }
Andy Hungdc099c22018-09-18 13:46:39 -07002617 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002618 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002619 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002621 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2622 ioDesc->mIoHandle = output;
2623 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002624 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002626 // The thread entity (active unit of execution) is no longer running here,
2627 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628
Eric Laurent6acd1d42017-01-04 14:23:29 -08002629 if (playbackThread != 0) {
2630 playbackThread->exit();
2631 if (!playbackThread->isDuplicating()) {
2632 closeOutputFinish(playbackThread);
2633 }
2634 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002635 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002636 mmapThread->exit();
2637 AudioStreamOut *out = mmapThread->clearOutput();
2638 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2639 // from now on thread->mOutput is NULL
2640 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 }
2642 return NO_ERROR;
2643}
2644
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002645void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002646{
2647 AudioStreamOut *out = thread->clearOutput();
2648 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2649 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002650 delete out;
2651}
2652
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002653void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002654{
2655 mPlaybackThreads.removeItem(thread->mId);
2656 thread->exit();
2657 closeOutputFinish(thread);
2658}
2659
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002660status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661{
2662 Mutex::Autolock _l(mLock);
2663 PlaybackThread *thread = checkPlaybackThread_l(output);
2664
2665 if (thread == NULL) {
2666 return BAD_VALUE;
2667 }
2668
Steve Block3856b092011-10-20 11:56:00 +01002669 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 thread->suspend();
2671
2672 return NO_ERROR;
2673}
2674
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002675status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676{
2677 Mutex::Autolock _l(mLock);
2678 PlaybackThread *thread = checkPlaybackThread_l(output);
2679
2680 if (thread == NULL) {
2681 return BAD_VALUE;
2682 }
2683
Steve Block3856b092011-10-20 11:56:00 +01002684 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685
2686 thread->restore();
2687
2688 return NO_ERROR;
2689}
2690
Eric Laurentcf2c0212014-07-25 16:20:43 -07002691status_t AudioFlinger::openInput(audio_module_handle_t module,
2692 audio_io_handle_t *input,
2693 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002694 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002695 const String8& address,
2696 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002697 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698{
Eric Laurent83b88082014-06-20 18:31:16 -07002699 Mutex::Autolock _l(mLock);
2700
Glenn Kastene7d66712015-03-05 13:46:52 -08002701 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002702 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002703 }
2704
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002705 sp<ThreadBase> thread = openInput_l(
2706 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002707
2708 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002709 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002710 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002711 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002713 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002714}
Dima Zavin799a70e2011-04-18 16:57:27 -07002715
Eric Laurent6acd1d42017-01-04 14:23:29 -08002716sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002717 audio_io_handle_t *input,
2718 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002719 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002720 const String8& address,
2721 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002722 audio_input_flags_t flags,
2723 audio_devices_t outputDevice,
2724 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002725{
Glenn Kastene7d66712015-03-05 13:46:52 -08002726 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002727 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002728 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002729 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002730 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002731
Glenn Kasteneeecb982016-02-26 10:44:04 -08002732 // Audio Policy can request a specific handle for hardware hotword.
2733 // The goal here is not to re-open an already opened input.
2734 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002735 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002736 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2737 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2738 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2739 return 0;
2740 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2741 // This should not happen in a transient state with current design.
2742 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2743 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002744 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002745
Eric Laurentcf2c0212014-07-25 16:20:43 -07002746 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002747 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002748 sp<StreamInHalInterface> inStream;
2749 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002750 *input, devices, &halconfig, flags, address.string(), source,
2751 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002752 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2753 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002754 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002755 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002756 halconfig.sample_rate,
2757 halconfig.format,
2758 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002759 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002760 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002762 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002763 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002764 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002765 audio_is_linear_pcm(config->format) &&
2766 audio_is_linear_pcm(halconfig.format) &&
2767 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002768 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2769 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002770 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002771 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002772 inStream.clear();
2773 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002774 *input, devices, &halconfig, flags, address.string(), source,
2775 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002776 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 }
2778
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002779 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002780 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002781 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2782 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002783 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002784 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002785 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2786 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002787 return thread;
2788 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002789 // Start record thread
2790 // RecordThread requires both input and output device indication to forward to audio
2791 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002792 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002793 mRecordThreads.add(*input, thread);
2794 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2795 return thread;
2796 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 }
2798
Eric Laurentcf2c0212014-07-25 16:20:43 -07002799 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 return 0;
2801}
2802
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002803status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804{
Glenn Kastend96c5722012-04-25 13:44:49 -07002805 return closeInput_nonvirtual(input);
2806}
2807
2808status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2809{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 // keep strong reference on the record thread so that
2811 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002812 sp<RecordThread> recordThread;
2813 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 {
2815 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002816 recordThread = checkRecordThread_l(input);
2817 if (recordThread != 0) {
2818 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819
Andy Hungdc099c22018-09-18 13:46:39 -07002820 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002821
Eric Laurent6acd1d42017-01-04 14:23:29 -08002822 // If we still have effect chains, it means that a client still holds a handle
2823 // on at least one effect. We must either move the chain to an existing thread with the
2824 // same session ID or put it aside in case a new record thread is opened for a
2825 // new capture on the same session
2826 sp<EffectChain> chain;
2827 {
2828 Mutex::Autolock _sl(recordThread->mLock);
2829 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2830 // Note: maximum one chain per record thread
2831 if (effectChains.size() != 0) {
2832 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002833 }
2834 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002835 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002836 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002837 // This should only happen in case of overlap between one thread tear down and the
2838 // creation of its replacement
2839 size_t i;
2840 for (i = 0; i < mRecordThreads.size(); i++) {
2841 sp<RecordThread> t = mRecordThreads.valueAt(i);
2842 if (t == recordThread) {
2843 continue;
2844 }
2845 if (t->hasAudioSession(chain->sessionId()) != 0) {
2846 Mutex::Autolock _l(t->mLock);
2847 ALOGV("closeInput() found thread %d for effect session %d",
2848 t->id(), chain->sessionId());
2849 t->addEffectChain_l(chain);
2850 break;
2851 }
2852 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002853 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002854 if (i == mRecordThreads.size()) {
2855 putOrphanEffectChain_l(chain);
2856 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002857 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002858 mRecordThreads.removeItem(input);
2859 } else {
2860 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2861 if (mmapThread == 0) {
2862 return BAD_VALUE;
2863 }
Andy Hungdc099c22018-09-18 13:46:39 -07002864 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002865 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002866 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002867 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2868 ioDesc->mIoHandle = input;
2869 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 }
Eric Laurent83b88082014-06-20 18:31:16 -07002871 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2872 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002873 if (recordThread != 0) {
2874 closeInputFinish(recordThread);
2875 } else if (mmapThread != 0) {
2876 mmapThread->exit();
2877 AudioStreamIn *in = mmapThread->clearInput();
2878 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2879 // from now on thread->mInput is NULL
2880 delete in;
2881 }
Eric Laurent83b88082014-06-20 18:31:16 -07002882 return NO_ERROR;
2883}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002885void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002886{
2887 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002888 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002889 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002890 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002891 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002892}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002894void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002895{
2896 mRecordThreads.removeItem(thread->mId);
2897 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898}
2899
Glenn Kastend2304db2014-02-03 07:40:31 -08002900status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901{
2902 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002903 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904
2905 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2906 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002907 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002908 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002909 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2910 mMmapThreads[i]->invalidateTracks(stream);
2911 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 return NO_ERROR;
2913}
2914
2915
Glenn Kasteneeecb982016-02-26 10:44:04 -08002916audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917{
Glenn Kasten9d003132016-04-06 14:38:09 -07002918 // This is a binder API, so a malicious client could pass in a bad parameter.
2919 // Check for that before calling the internal API nextUniqueId().
2920 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2921 ALOGE("newAudioUniqueId invalid use %d", use);
2922 return AUDIO_UNIQUE_ID_ALLOCATE;
2923 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002924 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925}
2926
Andy Hung8b0bfd92019-12-23 13:11:11 -08002927void AudioFlinger::acquireAudioSessionId(
2928 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002929{
2930 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08002931 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08002932 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07002933 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08002934 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
2935 caller = pid; // check must match releaseAudioSessionId()
2936 }
2937 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
2938 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08002939 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002940
Eric Laurent021cf962014-05-13 10:18:14 -07002941 {
2942 Mutex::Autolock _cl(mClientLock);
2943 // Ignore requests received from processes not known as notification client. The request
2944 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
2945 // called from a different pid leaving a stale session reference. Also we don't know how
2946 // to clear this reference if the client process dies.
2947 if (mNotificationClients.indexOfKey(caller) < 0) {
2948 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
2949 return;
2950 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07002951 }
2952
Glenn Kasten8d6a2442012-02-08 14:04:28 -08002953 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08002954 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002955 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08002956 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2957 ref->mCnt++;
2958 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002959 return;
2960 }
2961 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08002962 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002963 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002964}
2965
Glenn Kastend848eb42016-03-08 13:42:11 -08002966void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002967{
Eric Laurent6c796322019-04-09 14:13:17 -07002968 std::vector< sp<EffectModule> > removedEffects;
2969 {
2970 Mutex::Autolock _l(mLock);
2971 pid_t caller = IPCThreadState::self()->getCallingPid();
2972 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
2973 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08002974 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
2975 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002976 }
Eric Laurent6c796322019-04-09 14:13:17 -07002977 size_t num = mAudioSessionRefs.size();
2978 for (size_t i = 0; i < num; i++) {
2979 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2980 if (ref->mSessionid == audioSession && ref->mPid == caller) {
2981 ref->mCnt--;
2982 ALOGV(" decremented refcount to %d", ref->mCnt);
2983 if (ref->mCnt == 0) {
2984 mAudioSessionRefs.removeAt(i);
2985 delete ref;
2986 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
2987 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
2988 }
2989 goto Exit;
2990 }
2991 }
2992 // If the caller is audioserver it is likely that the session being released was acquired
2993 // on behalf of a process not in notification clients and we ignore the warning.
2994 ALOGW_IF(!isAudioServerUid(callerUid),
2995 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002996 }
Eric Laurent6c796322019-04-09 14:13:17 -07002997
2998Exit:
2999 for (auto& effect : removedEffects) {
3000 effect->updatePolicyState();
3001 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003002}
3003
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003004bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3005{
3006 size_t num = mAudioSessionRefs.size();
3007 for (size_t i = 0; i < num; i++) {
3008 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3009 if (ref->mSessionid == audioSession) {
3010 return true;
3011 }
3012 }
3013 return false;
3014}
3015
Eric Laurent6c796322019-04-09 14:13:17 -07003016std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003017
Steve Block3856b092011-10-20 11:56:00 +01003018 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003019
3020 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003021 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003022
3023 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3024 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003025 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003026 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3027 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003028 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003029 chains.push(ec);
3030 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003031 }
3032 }
Eric Laurent6c796322019-04-09 14:13:17 -07003033
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003034 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3035 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003036 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003037 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3038 sp<EffectChain> ec = t->mEffectChains[j];
3039 chains.push(ec);
3040 }
3041 }
3042
Eric Laurent6c796322019-04-09 14:13:17 -07003043 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3044 sp<MmapThread> t = mMmapThreads.valueAt(i);
3045 Mutex::Autolock _l(t->mLock);
3046 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3047 sp<EffectChain> ec = t->mEffectChains[j];
3048 chains.push(ec);
3049 }
3050 }
3051
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003052 for (size_t i = 0; i < chains.size(); i++) {
3053 sp<EffectChain> ec = chains[i];
3054 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003055 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003056 if (t == 0) {
3057 continue;
3058 }
3059 size_t numsessionrefs = mAudioSessionRefs.size();
3060 bool found = false;
3061 for (size_t k = 0; k < numsessionrefs; k++) {
3062 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003063 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003064 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003065 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003066 found = true;
3067 break;
3068 }
3069 }
3070 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003071 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003072 // remove all effects from the chain
3073 while (ec->mEffects.size()) {
3074 sp<EffectModule> effect = ec->mEffects[0];
3075 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003076 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003077 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003078 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003079 }
Eric Laurent6c796322019-04-09 14:13:17 -07003080 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003081 }
3082 }
3083 }
Eric Laurent6c796322019-04-09 14:13:17 -07003084 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003085}
3086
Andy Hungdc099c22018-09-18 13:46:39 -07003087// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3088void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3089{
3090 audio_utils::FdToString fdToString;
3091 const int fd = fdToString.fd();
3092 if (fd >= 0) {
3093 thread->dump(fd, {} /* args */);
3094 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3095 }
3096}
3097
Glenn Kasteneeecb982016-02-26 10:44:04 -08003098// checkThread_l() must be called with AudioFlinger::mLock held
3099AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3100{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003101 ThreadBase *thread = checkMmapThread_l(ioHandle);
3102 if (thread == 0) {
3103 switch (audio_unique_id_get_use(ioHandle)) {
3104 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3105 thread = checkPlaybackThread_l(ioHandle);
3106 break;
3107 case AUDIO_UNIQUE_ID_USE_INPUT:
3108 thread = checkRecordThread_l(ioHandle);
3109 break;
3110 default:
3111 break;
3112 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003113 }
3114 return thread;
3115}
3116
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003118AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119{
Glenn Kastena1117922012-01-26 10:53:32 -08003120 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121}
3122
3123// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003124AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125{
3126 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003127 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128}
3129
3130// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003131AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132{
Glenn Kastena1117922012-01-26 10:53:32 -08003133 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134}
3135
Eric Laurent6acd1d42017-01-04 14:23:29 -08003136// checkMmapThread_l() must be called with AudioFlinger::mLock held
3137AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3138{
3139 return mMmapThreads.valueFor(io).get();
3140}
3141
3142
3143// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3144AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3145{
Eric Laurent7459b902017-04-19 18:10:41 -07003146 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003147 if (volumeInterface == nullptr) {
3148 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3149 if (mmapThread != nullptr) {
3150 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003151 MmapPlaybackThread *mmapPlaybackThread =
3152 static_cast<MmapPlaybackThread *>(mmapThread);
3153 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003154 }
3155 }
3156 }
3157 return volumeInterface;
3158}
3159
3160Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3161{
3162 Vector <VolumeInterface *> volumeInterfaces;
3163 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003164 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003165 }
3166 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3167 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003168 MmapPlaybackThread *mmapPlaybackThread =
3169 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3170 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003171 }
3172 }
3173 return volumeInterfaces;
3174}
3175
Glenn Kasteneeecb982016-02-26 10:44:04 -08003176audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177{
Glenn Kasten9d003132016-04-06 14:38:09 -07003178 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003179 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003180 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3181 for (int retry = 0; retry < maxRetries; retry++) {
3182 // The cast allows wraparound from max positive to min negative instead of abort
3183 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3184 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3185 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3186 // allow wrap by skipping 0 and -1 for session ids
3187 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3188 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3189 return (audio_unique_id_t) (base | use);
3190 }
3191 }
3192 // We have no way of recovering from wraparound
3193 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3194 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195}
3196
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003197AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003198{
3199 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3200 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003201 if(thread->isDuplicating()) {
3202 continue;
3203 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003204 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003205 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003206 return thread;
3207 }
3208 }
3209 return NULL;
3210}
3211
jiabinc52b1ff2019-10-31 17:20:42 -07003212DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003213{
3214 PlaybackThread *thread = primaryPlaybackThread_l();
3215
3216 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003217 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003218 }
3219
jiabinc52b1ff2019-10-31 17:20:42 -07003220 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003221}
3222
Glenn Kastena7335632016-06-09 17:09:53 -07003223AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3224{
3225 size_t minFrameCount = 0;
3226 PlaybackThread *minThread = NULL;
3227 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3228 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3229 if (!thread->isDuplicating()) {
3230 size_t frameCount = thread->frameCountHAL();
3231 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3232 (frameCount == minFrameCount && thread->hasFastMixer() &&
3233 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3234 minFrameCount = frameCount;
3235 minThread = thread;
3236 }
3237 }
3238 }
3239 return minThread;
3240}
3241
Eric Laurenta011e352012-03-29 15:51:43 -07003242sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003243 audio_session_t triggerSession,
3244 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003245 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003246 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003247{
3248 Mutex::Autolock _l(mLock);
3249
3250 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3251 status_t playStatus = NAME_NOT_FOUND;
3252 status_t recStatus = NAME_NOT_FOUND;
3253 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3254 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3255 if (playStatus == NO_ERROR) {
3256 return event;
3257 }
3258 }
3259 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3260 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3261 if (recStatus == NO_ERROR) {
3262 return event;
3263 }
3264 }
3265 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3266 mPendingSyncEvents.add(event);
3267 } else {
3268 ALOGV("createSyncEvent() invalid event %d", event->type());
3269 event.clear();
3270 }
3271 return event;
3272}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003273
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274// ----------------------------------------------------------------------------
3275// Effect management
3276// ----------------------------------------------------------------------------
3277
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003278sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3279 return mEffectsFactoryHal;
3280}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281
Glenn Kastenf587ba52012-01-26 16:25:10 -08003282status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283{
3284 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003285 if (mEffectsFactoryHal.get()) {
3286 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3287 } else {
3288 return -ENODEV;
3289 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290}
3291
Glenn Kastenf587ba52012-01-26 16:25:10 -08003292status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293{
3294 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003295 if (mEffectsFactoryHal.get()) {
3296 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3297 } else {
3298 return -ENODEV;
3299 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300}
3301
Glenn Kasten5e92a782012-01-30 07:40:52 -08003302status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003303 const effect_uuid_t *pTypeUuid,
3304 uint32_t preferredTypeFlag,
3305 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003307 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3308 return BAD_VALUE;
3309 }
3310
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003312
3313 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003314 return -ENODEV;
3315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003317 status_t status = NO_ERROR;
3318 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3319 // If uuid is specified, request effect descriptor from that.
3320 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3321 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3322 // If uuid is not specified, look for an available implementation
3323 // of the required type instead.
3324
3325 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3326 effect_descriptor_t desc;
3327 desc.flags = 0; // prevent compiler warning
3328
3329 uint32_t numEffects = 0;
3330 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3331 if (status < 0) {
3332 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3333 return status;
3334 }
3335
3336 bool found = false;
3337 for (uint32_t i = 0; i < numEffects; i++) {
3338 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3339 if (status < 0) {
3340 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3341 continue;
3342 }
3343 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3344 // If matching type found save effect descriptor.
3345 found = true;
3346 *descriptor = desc;
3347
3348 // If there's no preferred flag or this descriptor matches the preferred
3349 // flag, success! If this descriptor doesn't match the preferred
3350 // flag, continue enumeration in case a better matching version of this
3351 // effect type is available. Note that this means if no effect with a
3352 // correct flag is found, the descriptor returned will correspond to the
3353 // last effect that at least had a matching type uuid (if any).
3354 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3355 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3356 break;
3357 }
3358 }
3359 }
3360
3361 if (!found) {
3362 status = NAME_NOT_FOUND;
3363 ALOGW("getEffectDescriptor(): Effect not found by type.");
3364 }
3365 } else {
3366 status = BAD_VALUE;
3367 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3368 }
3369 return status;
3370}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003372sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 effect_descriptor_t *pDesc,
3374 const sp<IEffectClient>& effectClient,
3375 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003376 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003377 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003378 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003379 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003380 pid_t pid,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003381 bool probe,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 status_t *status,
3383 int *id,
3384 int *enabled)
3385{
3386 status_t lStatus = NO_ERROR;
3387 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389
Eric Laurentb6436272016-12-07 19:24:50 -08003390 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003391 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003392 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3393 ALOGW_IF(pid != -1 && pid != callingPid,
3394 "%s uid %d pid %d tried to pass itself off as pid %d",
3395 __func__, callingUid, callingPid, pid);
3396 pid = callingPid;
3397 }
3398
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003399 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3400 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401
3402 if (pDesc == NULL) {
3403 lStatus = BAD_VALUE;
3404 goto Exit;
3405 }
3406
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003407 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003408 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003409 lStatus = NO_INIT;
3410 goto Exit;
3411 }
3412
Andy Hung6096dcd2019-03-13 13:20:30 -07003413 // check audio settings permission for global effects
3414 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3415 if (!settingsAllowed()) {
3416 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3417 lStatus = PERMISSION_DENIED;
3418 goto Exit;
3419 }
3420 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3421 if (!isAudioServerUid(callingUid)) {
3422 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3423 lStatus = PERMISSION_DENIED;
3424 goto Exit;
3425 }
3426
3427 if (io == AUDIO_IO_HANDLE_NONE) {
3428 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3429 lStatus = BAD_VALUE;
3430 goto Exit;
3431 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003432 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3433 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3434 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3435 lStatus = PERMISSION_DENIED;
3436 goto Exit;
3437 }
Eric Laurent94876032019-11-13 12:45:28 -08003438 if (io != AUDIO_IO_HANDLE_NONE) {
3439 ALOGE("%s: io handle should not be specified for device effect", __func__);
3440 lStatus = BAD_VALUE;
3441 goto Exit;
3442 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003443 } else {
3444 // general sessionId.
3445
3446 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3447 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3448 lStatus = BAD_VALUE;
3449 goto Exit;
3450 }
3451
3452 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3453 // to prevent creating an effect when one doesn't actually have track with that session?
3454 }
3455
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003457 // Get the full effect descriptor from the uuid/type.
3458 // If the session is the output mix, prefer an auxiliary effect,
3459 // otherwise no preference.
3460 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3461 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3462 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3463 if (lStatus < 0) {
3464 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3465 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 }
3467
3468 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003469 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3471 lStatus = INVALID_OPERATION;
3472 goto Exit;
3473 }
3474
Eric Laurent59255e42011-07-27 19:49:51 -07003475 // check recording permission for visualizer
3476 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003477 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003478 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003479 lStatus = PERMISSION_DENIED;
3480 goto Exit;
3481 }
3482
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003484 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003485 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003486 // if the output returned by getOutputForEffect() is removed before we lock the
3487 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3488 // and we will exit safely
3489 io = AudioSystem::getOutputForEffect(&desc);
3490 ALOGV("createEffect got output %d", io);
3491 }
3492
3493 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494
Eric Laurentb82e6b72019-11-22 17:25:04 -08003495 if (sessionId == AUDIO_SESSION_DEVICE) {
3496 sp<Client> client = registerPid(pid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003497 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003498 handle = mDeviceEffectManager.createEffect_l(
3499 &desc, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003500 enabled, &lStatus, probe);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003501 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3502 // remove local strong reference to Client with mClientLock held
3503 Mutex::Autolock _cl(mClientLock);
3504 client.clear();
3505 } else {
3506 // handle must be valid here, but check again to be safe.
3507 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3508 }
3509 goto Register;
3510 }
3511
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 // If output is not specified try to find a matching audio session ID in one of the
3513 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003514 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3515 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003516 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3517 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003518 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003519 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003520 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3521 if (io == AUDIO_IO_HANDLE_NONE) {
3522 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003524 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003525 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003526 }
Andy Hung444bb552019-03-14 17:06:39 -07003527
3528 // If you wish to create a Record preprocessing AudioEffect in Java,
3529 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3530 // Otherwise it will fail when created on a Playback thread by legacy
3531 // handling below. Ditto with Mmap, the associated Mmap track must be created
3532 // before creating the AudioEffect or the io handle must be specified.
3533 //
3534 // Detect if the effect is created after an AudioRecord is destroyed.
3535 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3536 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3537 " for session %d no longer exists",
3538 __func__, desc.name, sessionId);
3539 lStatus = PERMISSION_DENIED;
3540 goto Exit;
3541 }
3542
3543 // Legacy handling of creating an effect on an expired or made-up
3544 // session id. We think that it is a Playback effect.
3545 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003546 // If no output thread contains the requested session ID, default to
3547 // first output. The effect chain will be moved to the correct output
3548 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003549 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003550 io = mPlaybackThreads.keyAt(0);
3551 }
Steve Block3856b092011-10-20 11:56:00 +01003552 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003553 } else if (checkPlaybackThread_l(io) != nullptr) {
3554 // allow only one effect chain per sessionId on mPlaybackThreads.
3555 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3556 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3557 if (io == checkIo) continue;
3558 const uint32_t sessionType =
3559 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3560 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3561 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3562 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3563 android_errorWriteLog(0x534e4554, "123237974");
3564 lStatus = BAD_VALUE;
3565 goto Exit;
3566 }
3567 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003568 }
3569 ThreadBase *thread = checkRecordThread_l(io);
3570 if (thread == NULL) {
3571 thread = checkPlaybackThread_l(io);
3572 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003573 thread = checkMmapThread_l(io);
3574 if (thread == NULL) {
3575 ALOGE("createEffect() unknown output thread");
3576 lStatus = BAD_VALUE;
3577 goto Exit;
3578 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003579 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003580 } else {
3581 // Check if one effect chain was awaiting for an effect to be created on this
3582 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003583 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003584 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003585 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003586 thread->addEffectChain_l(chain);
3587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003589
Eric Laurent021cf962014-05-13 10:18:14 -07003590 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003592 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003593 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003594 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003595 &desc, enabled, &lStatus, pinned, probe);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003596 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003597 // remove local strong reference to Client with mClientLock held
3598 Mutex::Autolock _cl(mClientLock);
3599 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003600 } else {
3601 // handle must be valid here, but check again to be safe.
3602 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
3605
Eric Laurentb82e6b72019-11-22 17:25:04 -08003606Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003607 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003608 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003609 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003610 if (effect != nullptr) {
3611 status_t rStatus = effect->updatePolicyState();
3612 if (rStatus != NO_ERROR) {
3613 lStatus = rStatus;
3614 }
3615 }
3616 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003617 handle.clear();
3618 }
3619
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003621 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 return handle;
3623}
3624
Glenn Kastend848eb42016-03-08 13:42:11 -08003625status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003626 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003627{
Steve Block3856b092011-10-20 11:56:00 +01003628 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003629 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003630 Mutex::Autolock _l(mLock);
3631 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003632 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003633 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634 }
Eric Laurentde070132010-07-13 04:45:46 -07003635 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3636 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003637 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003638 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639 }
Eric Laurentde070132010-07-13 04:45:46 -07003640 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3641 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003642 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003643 return BAD_VALUE;
3644 }
3645
3646 Mutex::Autolock _dl(dstThread->mLock);
3647 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003648 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649}
3650
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003651
3652void AudioFlinger::setEffectSuspended(int effectId,
3653 audio_session_t sessionId,
3654 bool suspended)
3655{
3656 Mutex::Autolock _l(mLock);
3657
3658 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3659 if (thread == nullptr) {
3660 return;
3661 }
3662 Mutex::Autolock _sl(thread->mLock);
3663 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3664 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3665}
3666
3667
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003668// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003669status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003670 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003671 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003672{
Steve Block3856b092011-10-20 11:56:00 +01003673 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003674 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003675
Eric Laurent59255e42011-07-27 19:49:51 -07003676 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003677 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003678 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003679 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003680 return INVALID_OPERATION;
3681 }
3682
Eric Laurent4c415062016-06-17 16:14:16 -07003683 // Check whether the destination thread and all effects in the chain are compatible
3684 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003685 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003686 " destination thread %p is not compatible with effects in the chain",
3687 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003688 return INVALID_OPERATION;
3689 }
3690
Eric Laurent39e94f82010-07-28 01:32:47 -07003691 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003692 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003693 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003694 // removed.
3695 srcThread->removeEffectChain_l(chain);
3696
3697 // transfer all effects one by one so that new effect chain is created on new thread with
3698 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003699 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003700 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003701 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003702 Vector< sp<EffectModule> > removed;
3703 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003704 while (effect != 0) {
3705 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003706 removed.add(effect);
3707 status = dstThread->addEffect_l(effect);
3708 if (status != NO_ERROR) {
3709 break;
3710 }
Eric Laurentec35a142011-10-05 17:42:25 -07003711 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3712 if (effect->state() == EffectModule::ACTIVE ||
3713 effect->state() == EffectModule::STOPPING) {
3714 effect->start();
3715 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003716 // if the move request is not received from audio policy manager, the effect must be
3717 // re-registered with the new strategy and output
3718 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003719 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003720 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003721 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003722 status = NO_INIT;
3723 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003724 }
3725 strategy = dstChain->strategy();
3726 }
Eric Laurentde070132010-07-13 04:45:46 -07003727 effect = chain->getEffectFromId_l(0);
3728 }
3729
Eric Laurent5baf2af2013-09-12 17:37:00 -07003730 if (status != NO_ERROR) {
3731 for (size_t i = 0; i < removed.size(); i++) {
3732 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003733 }
3734 }
3735
3736 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737}
3738
Eric Laurent6c796322019-04-09 14:13:17 -07003739status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3740 const sp<PlaybackThread>& dstThread,
3741 sp<PlaybackThread> *srcThread)
3742{
3743 status_t status = NO_ERROR;
3744 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003745 sp<PlaybackThread> thread =
3746 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003747
3748 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3749 Mutex::Autolock _dl(dstThread->mLock);
3750 Mutex::Autolock _sl(thread->mLock);
3751 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3752 sp<EffectChain> dstChain;
3753 if (srcChain == 0) {
3754 return INVALID_OPERATION;
3755 }
3756
3757 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3758 if (effect == 0) {
3759 return INVALID_OPERATION;
3760 }
3761 thread->removeEffect_l(effect);
3762 status = dstThread->addEffect_l(effect);
3763 if (status != NO_ERROR) {
3764 thread->addEffect_l(effect);
3765 status = INVALID_OPERATION;
3766 goto Exit;
3767 }
3768
Eric Laurent6b446ce2019-12-13 10:56:31 -08003769 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003770 if (dstChain == 0) {
3771 thread->addEffect_l(effect);
3772 status = INVALID_OPERATION;
3773 }
3774
3775Exit:
3776 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3777 if (effect->state() == EffectModule::ACTIVE ||
3778 effect->state() == EffectModule::STOPPING) {
3779 effect->start();
3780 }
3781 }
3782
3783 if (status == NO_ERROR && srcThread != nullptr) {
3784 *srcThread = thread;
3785 }
3786 return status;
3787}
3788
Eric Laurent5baf2af2013-09-12 17:37:00 -07003789bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003790{
3791 if (mGlobalEffectEnableTime != 0 &&
3792 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3793 return true;
3794 }
3795
3796 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3797 sp<EffectChain> ec =
3798 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003799 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003800 return true;
3801 }
3802 }
3803 return false;
3804}
3805
Eric Laurent5baf2af2013-09-12 17:37:00 -07003806void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003807{
3808 Mutex::Autolock _l(mLock);
3809
3810 mGlobalEffectEnableTime = systemTime();
3811
3812 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3813 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3814 if (t->mType == ThreadBase::OFFLOAD) {
3815 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3816 }
3817 }
3818
3819}
3820
Eric Laurentaaa44472014-09-12 17:41:50 -07003821status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3822{
Eric Laurentd8365c52017-07-16 15:27:05 -07003823 // clear possible suspended state before parking the chain so that it starts in default state
3824 // when attached to a new record thread
3825 chain->setEffectSuspended_l(FX_IID_AEC, false);
3826 chain->setEffectSuspended_l(FX_IID_NS, false);
3827
Glenn Kastend848eb42016-03-08 13:42:11 -08003828 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003829 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003830 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003831 if (index >= 0) {
3832 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3833 return ALREADY_EXISTS;
3834 }
3835 mOrphanEffectChains.add(session, chain);
3836 return NO_ERROR;
3837}
3838
3839sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3840{
3841 sp<EffectChain> chain;
3842 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003843 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003844 if (index >= 0) {
3845 chain = mOrphanEffectChains.valueAt(index);
3846 mOrphanEffectChains.removeItemsAt(index);
3847 }
3848 return chain;
3849}
3850
3851bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3852{
3853 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003854 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003855 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003856 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003857 if (index >= 0) {
3858 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003859 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003860 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003861 mOrphanEffectChains.removeItemsAt(index);
3862 }
3863 return true;
3864 }
3865 return false;
3866}
3867
3868
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869// ----------------------------------------------------------------------------
3870
3871status_t AudioFlinger::onTransact(
3872 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3873{
3874 return BnAudioFlinger::onTransact(code, data, reply, flags);
3875}
3876
Glenn Kasten63238ef2015-03-02 15:50:29 -08003877} // namespace android