blob: b8782d7f03364a368dac9895647038babe8b4a7d [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
jiabin8cb192f2019-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 Naganov3de4f262020-03-06 17:02:19 -080032#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 Laurentb680e952019-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) {
Eric Laurent488d5002020-05-14 09:13:30 -0700138 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800139 String16("external_vibrator_service"));
140 if (binder != 0) {
141 sExternalVibratorService =
142 interface_cast<os::IExternalVibratorService>(binder);
143 }
144 }
145 return sExternalVibratorService;
146}
147
Mikhail Naganov3de4f262020-03-06 17:02:19 -0800148class 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 Laurent9b2064c2019-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 Laurentb680e952019-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 Naganov3de4f262020-03-06 17:02:19 -0800244
245 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
246 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Eric Laurentb680e952019-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,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800346 &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 Laurent9b2064c2019-11-22 17:25:04 -0800412status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
413 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent488d5002020-05-14 09:13:30 -0700414 AutoMutex lock(mHardwareLock);
Eric Laurent9b2064c2019-11-22 17:25:04 -0800415 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
416 if (audioHwDevice == nullptr) {
417 return NO_INIT;
418 }
419 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
420}
421
422status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
423 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent488d5002020-05-14 09:13:30 -0700424 AutoMutex lock(mHardwareLock);
Eric Laurent9b2064c2019-11-22 17:25:04 -0800425 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
426 if (audioHwDevice == nullptr) {
427 return NO_INIT;
428 }
429 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
430}
431
Eric Laurenta4c5a552012-03-29 10:12:40 -0700432static const char * const audio_interfaces[] = {
433 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
434 AUDIO_HARDWARE_MODULE_ID_A2DP,
435 AUDIO_HARDWARE_MODULE_ID_USB,
436};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700437
Phil Burk062e67a2015-02-11 13:40:50 -0800438AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700439 audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -0700440 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700441{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700442 // if module is 0, the request comes from an old policy manager and we should load
443 // well known modules
Eric Laurent488d5002020-05-14 09:13:30 -0700444 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700445 if (module == 0) {
446 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700447 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700448 loadHwModule_l(audio_interfaces[i]);
449 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700450 // then try to find a module supporting the requested device.
451 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
452 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700453 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
454 uint32_t supportedDevices;
455 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabinc0106832019-10-24 14:58:31 -0700456 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700457 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700458 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700459 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700460 } else {
461 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700462 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
463 if (audioHwDevice != NULL) {
464 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700465 }
466 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700467
Dima Zavin799a70e2011-04-18 16:57:27 -0700468 return NULL;
469}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470
Glenn Kasten0f11b512014-01-31 16:18:54 -0800471void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 String8 result;
474
475 result.append("Clients:\n");
476 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800477 sp<Client> client = mClients.valueAt(i).promote();
478 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800479 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 }
481 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700482
Eric Laurentd1b28d42013-09-18 18:47:13 -0700483 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800484 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700485 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800486 const pid_t pid = mNotificationClients[i]->getPid();
487 const uid_t uid = mNotificationClients[i]->getUid();
488 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
489 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700490 }
491
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700492 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800493 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700494 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
495 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800496 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
497 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
498 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700499 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501}
502
503
Glenn Kasten0f11b512014-01-31 16:18:54 -0800504void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505{
506 const size_t SIZE = 256;
507 char buffer[SIZE];
508 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800509 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510
John Grossman4ff14ba2012-02-08 16:37:41 -0800511 snprintf(buffer, SIZE, "Hardware status: %d\n"
512 "Standby Time mSec: %u\n",
513 hardwareStatus,
514 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 result.append(buffer);
516 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517}
518
Glenn Kasten0f11b512014-01-31 16:18:54 -0800519void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520{
521 const size_t SIZE = 256;
522 char buffer[SIZE];
523 String8 result;
524 snprintf(buffer, SIZE, "Permission Denial: "
525 "can't dump AudioFlinger from pid=%d, uid=%d\n",
526 IPCThreadState::self()->getCallingPid(),
527 IPCThreadState::self()->getCallingUid());
528 result.append(buffer);
529 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530}
531
Eric Laurent81784c32012-11-19 14:55:58 -0800532bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700534 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
535 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536}
537
538status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
539{
Glenn Kasten44deb052012-02-05 18:09:08 -0800540 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 dumpPermissionDenial(fd, args);
542 } else {
543 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800544 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 if (!hardwareLocked) {
546 String8 result(kHardwareLockedString);
547 write(fd, result.string(), result.size());
548 } else {
549 mHardwareLock.unlock();
550 }
551
Eric Tan7b651152018-07-13 10:17:19 -0700552 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553
554 // failed to lock - AudioFlinger is probably deadlocked
555 if (!locked) {
556 String8 result(kDeadlockedString);
557 write(fd, result.string(), result.size());
558 }
559
Eric Laurent021cf962014-05-13 10:18:14 -0700560 bool clientLocked = dumpTryLock(mClientLock);
561 if (!clientLocked) {
562 String8 result(kClientLockedString);
563 write(fd, result.string(), result.size());
564 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700565
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700566 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700567 mEffectsFactoryHal->dumpEffects(fd);
568 } else {
569 String8 result(kNoEffectsFactory);
570 write(fd, result.string(), result.size());
571 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700572
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700574 if (clientLocked) {
575 mClientLock.unlock();
576 }
577
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 dumpInternals(fd, args);
579
580 // dump playback threads
581 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
582 mPlaybackThreads.valueAt(i)->dump(fd, args);
583 }
584
585 // dump record threads
586 for (size_t i = 0; i < mRecordThreads.size(); i++) {
587 mRecordThreads.valueAt(i)->dump(fd, args);
588 }
589
Eric Laurent6acd1d42017-01-04 14:23:29 -0800590 // dump mmap threads
591 for (size_t i = 0; i < mMmapThreads.size(); i++) {
592 mMmapThreads.valueAt(i)->dump(fd, args);
593 }
594
Eric Laurentaaa44472014-09-12 17:41:50 -0700595 // dump orphan effect chains
596 if (mOrphanEffectChains.size() != 0) {
597 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
598 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
599 mOrphanEffectChains.valueAt(i)->dump(fd, args);
600 }
601 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700602 // dump all hardware devs
603 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700604 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
605 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700607
Mikhail Naganov201369b2018-05-16 16:52:32 -0700608 mPatchPanel.dump(fd);
609
Eric Laurent9b2064c2019-11-22 17:25:04 -0800610 mDeviceEffectManager.dump(fd);
611
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700612 // dump external setParameters
613 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
614 dprintf(fd, "\n%s setParameters:\n", name);
615 logger.dump(fd, " " /* prefix */);
616 };
617 dumpLogger(mRejectedSetParameterLog, "Rejected");
618 dumpLogger(mAppSetParameterLog, "App");
619 dumpLogger(mSystemSetParameterLog, "System");
620
Andy Hunga8115dc2018-08-24 15:51:59 -0700621 // dump historical threads in the last 10 seconds
622 const std::string threadLog = mThreadLog.dumpToString(
623 "Historical Thread Log ", 0 /* lines */,
624 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
625 write(fd, threadLog.c_str(), threadLog.size());
626
rago3bd1c872016-09-26 12:58:14 -0700627 BUFLOG_RESET;
628
Glenn Kastend65d73c2012-06-22 17:21:07 -0700629 if (locked) {
630 mLock.unlock();
631 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800632
Andy Hung8946a282018-04-19 20:04:56 -0700633#ifdef TEE_SINK
634 // NBAIO_Tee dump is safe to call outside of AF lock.
635 NBAIO_Tee::dumpAll(fd, "_DUMP");
636#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800637 // append a copy of media.log here by forwarding fd to it, but don't attempt
638 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700639 if (sMediaLogServiceAsBinder != 0) {
640 dprintf(fd, "\nmedia.log:\n");
641 Vector<String16> args;
642 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800643 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700644
645 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700646 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700647 bool unreachableMemory = false;
648 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700649 if (arg == String16("-m")) {
650 dumpMem = true;
651 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700652 unreachableMemory = true;
653 }
654 }
655
Andy Hung07b745e2016-05-23 16:21:07 -0700656 if (dumpMem) {
657 dprintf(fd, "\nDumping memory:\n");
658 std::string s = dumpMemoryAddresses(100 /* limit */);
659 write(fd, s.c_str(), s.size());
660 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700661 if (unreachableMemory) {
662 dprintf(fd, "\nDumping unreachable memory:\n");
663 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700664 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700665 write(fd, s.c_str(), s.size());
666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 }
668 return NO_ERROR;
669}
670
Eric Laurent021cf962014-05-13 10:18:14 -0700671sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800672{
Eric Laurent021cf962014-05-13 10:18:14 -0700673 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800674 // If pid is already in the mClients wp<> map, then use that entry
675 // (for which promote() is always != 0), otherwise create a new entry and Client.
676 sp<Client> client = mClients.valueFor(pid).promote();
677 if (client == 0) {
678 client = new Client(this, pid);
679 mClients.add(pid, client);
680 }
681
682 return client;
683}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684
Glenn Kasten9e58b552013-01-18 15:09:48 -0800685sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
686{
Jiabin Huang60766082020-07-28 22:03:56 +0000687 // If there is no memory allocated for logs, return a no-op writer that does nothing.
688 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700689 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800690 return new NBLog::Writer();
691 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700692 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
693 // If allocation fails, consult the vector of previously unregistered writers
694 // and garbage-collect one or more them until an allocation succeeds
695 if (shared == 0) {
696 Mutex::Autolock _l(mUnregisteredWritersLock);
697 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
698 {
699 // Pick the oldest stale writer to garbage-collect
700 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
701 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700702 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700703 // Now the media.log remote reference to IMemory is gone. When our last local
704 // reference to IMemory also drops to zero at end of this block,
705 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
706 }
707 // Re-attempt the allocation
708 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
709 if (shared != 0) {
710 goto success;
711 }
712 }
713 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000714 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700715 return new NBLog::Writer();
716 }
717success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700718 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800719 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
720 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700721 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800722 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800723}
724
725void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
726{
Glenn Kasten685ef092013-02-04 08:15:34 -0800727 if (writer == 0) {
728 return;
729 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800730 sp<IMemory> iMemory(writer->getIMemory());
731 if (iMemory == 0) {
732 return;
733 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700734 // Rather than removing the writer immediately, append it to a queue of old writers to
735 // be garbage-collected later. This allows us to continue to view old logs for a while.
736 Mutex::Autolock _l(mUnregisteredWritersLock);
737 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800738}
739
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740// IAudioFlinger interface
741
Eric Laurent21da6472017-11-09 16:29:26 -0800742sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
743 CreateTrackOutput& output,
744 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700745{
746 sp<PlaybackThread::Track> track;
747 sp<TrackHandle> trackHandle;
748 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800750 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800751 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800752 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753
Eric Laurent21da6472017-11-09 16:29:26 -0800754 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700755 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800756 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700757 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
758 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700759 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700760
Andy Hung4ef19fa2018-05-15 19:35:29 -0700761 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800762 ALOGW_IF(clientUid != callingUid,
763 "%s uid %d tried to pass itself off as %d",
764 __FUNCTION__, callingUid, clientUid);
765 clientUid = callingUid;
766 updatePid = true;
767 }
768 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700769 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800770 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800771 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700772 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800773 __func__, callingUid, callingPid, clientPid);
774 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700775 }
776
Eric Laurent21da6472017-11-09 16:29:26 -0800777 audio_session_t sessionId = input.sessionId;
778 if (sessionId == AUDIO_SESSION_ALLOCATE) {
779 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800780 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
781 lStatus = BAD_VALUE;
782 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800783 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800784
Eric Laurent21da6472017-11-09 16:29:26 -0800785 output.sessionId = sessionId;
786 output.outputId = AUDIO_IO_HANDLE_NONE;
787 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700788 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Nadav Bar766fb022018-01-07 12:18:03 +0200789 clientPid, clientUid, &input.config, input.flags,
Kevin Rocard153f92d2018-12-18 18:33:28 -0800790 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800791
792 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
793 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
794 goto Exit;
795 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800796 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
797 // but if someone uses binder directly they could bypass that and cause us to crash
798 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000799 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 lStatus = BAD_VALUE;
801 goto Exit;
802 }
803
Glenn Kasten53b5d092014-02-05 10:00:23 -0800804 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800805 if (!audio_is_output_channel(input.config.channel_mask)) {
806 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800807 lStatus = BAD_VALUE;
808 goto Exit;
809 }
810
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700811 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800812 if (!audio_is_valid_format(input.config.format)) {
813 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700814 lStatus = BAD_VALUE;
815 goto Exit;
816 }
817
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 {
819 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800820 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800822 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 lStatus = BAD_VALUE;
824 goto Exit;
825 }
826
Eric Laurent21da6472017-11-09 16:29:26 -0800827 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828
Glenn Kastene848bd92014-03-13 15:00:32 -0700829 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800830 // check if an effect chain with the same session ID is present on another
831 // output thread and move it here.
832 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
833 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
834 if (mPlaybackThreads.keyAt(i) != output.outputId) {
835 uint32_t sessions = t->hasAudioSession(sessionId);
836 if (sessions & ThreadBase::EFFECT_SESSION) {
837 effectThread = t.get();
838 break;
Eric Laurentde070132010-07-13 04:45:46 -0700839 }
840 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 }
Eric Laurent21da6472017-11-09 16:29:26 -0800842 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843
Eric Laurent21da6472017-11-09 16:29:26 -0800844 output.sampleRate = input.config.sample_rate;
845 output.frameCount = input.frameCount;
846 output.notificationFrameCount = input.notificationFrameCount;
847 output.flags = input.flags;
848
Eric Laurent42984412019-05-09 17:57:03 -0700849 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700850 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800851 &output.frameCount, &output.notificationFrameCount,
852 input.notificationsPerBuffer, input.speed,
853 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700854 callingPid, input.clientInfo.clientTid, clientUid,
jiabin375283d2020-08-21 18:14:43 -0700855 &lStatus, portId, input.audioTrackCallback,
856 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800857 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700858 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700859
Eric Laurent21da6472017-11-09 16:29:26 -0800860 output.afFrameCount = thread->frameCount();
861 output.afSampleRate = thread->sampleRate();
862 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800863 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800864
Kevin Rocard153f92d2018-12-18 18:33:28 -0800865 if (lStatus == NO_ERROR) {
866 // Connect secondary outputs. Failure on a secondary output must not imped the primary
867 // Any secondary output setup failure will lead to a desync between the AP and AF until
868 // the track is destroyed.
869 TeePatches teePatches;
870 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
871 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
872 if (secondaryThread == NULL) {
873 ALOGE("no playback thread found for secondary output %d", output.outputId);
874 continue;
875 }
876
Kevin Rocard20a44f82019-09-18 11:24:52 +0100877 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
878 / thread->sampleRate();
879 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
880 / secondaryThread->sampleRate();
881 // If the secondary output has just been opened, the first secondaryThread write
882 // will not block as it will fill the empty startup buffer of the HAL,
883 // so a second sink buffer needs to be ready for the immediate next blocking write.
884 // Additionally, have a margin of one main thread buffer as the scheduling jitter
885 // can reorder the writes (eg if thread A&B have the same write intervale,
886 // the scheduler could schedule AB...BA)
887 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
888 // Total secondary output buffer must be at least as the read frames plus
889 // the margin of a few buffers on both sides in case the
890 // threads scheduling has some jitter.
891 // That value should not impact latency as the secondary track is started before
892 // its buffer is full, see frameCountToBeReady.
893 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
894 // The frameCount should also not be smaller than the secondary thread min frame
895 // count
896 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
897 [&] { Mutex::Autolock _l(secondaryThread->mLock);
898 return secondaryThread->latency_l(); }(),
899 secondaryThread->mNormalFrameCount,
900 secondaryThread->mSampleRate,
901 output.sampleRate,
902 input.speed);
903 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800904
905 using namespace std::chrono_literals;
906 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
907 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
908 output.sampleRate,
909 inChannelMask,
910 input.config.format,
911 frameCount,
912 NULL /* buffer */,
913 (size_t)0 /* bufferSize */,
914 AUDIO_INPUT_FLAG_DIRECT,
915 0ns /* timeout */);
916 status_t status = patchRecord->initCheck();
917 if (status != NO_ERROR) {
918 ALOGE("Secondary output patchRecord init failed: %d", status);
919 continue;
920 }
Andy Hungae22b482019-05-09 15:38:55 -0700921
922 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
923 // for fast usage: thread has fast mixer, sample rate matches, etc.;
924 // for now, we exclude fast tracks by removing the Fast flag.
925 const audio_output_flags_t outputFlags =
926 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800927 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
928 streamType,
929 output.sampleRate,
930 input.config.channel_mask,
931 input.config.format,
932 frameCount,
933 patchRecord->buffer(),
934 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700935 outputFlags,
Kevin Rocard20a44f82019-09-18 11:24:52 +0100936 0ns /* timeout */,
937 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800938 status = patchTrack->initCheck();
939 if (status != NO_ERROR) {
940 ALOGE("Secondary output patchTrack init failed: %d", status);
941 continue;
942 }
943 teePatches.push_back({patchRecord, patchTrack});
944 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800945 // In case the downstream patchTrack on the secondaryThread temporarily outlives
946 // our created track, ensure the corresponding patchRecord is still alive.
947 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
948 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800949 }
950 track->setTeePatches(std::move(teePatches));
951 }
952
Eric Laurent39e94f82010-07-28 01:32:47 -0700953 // move effect chain to this output thread if an effect on same session was waiting
954 // for a track to be created
955 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700956 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700957 Mutex::Autolock _dl(thread->mLock);
958 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700959 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
960 effectThreadId = thread->id();
961 effectIds = thread->getEffectIds_l(sessionId);
962 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700963 }
Eric Laurenta011e352012-03-29 15:51:43 -0700964
965 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700966 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800967 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700968 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700969 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700970 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700971 } else {
972 mPendingSyncEvents[i]->cancel();
973 }
Eric Laurenta011e352012-03-29 15:51:43 -0700974 mPendingSyncEvents.removeAt(i);
975 i--;
976 }
977 }
978 }
Andy Hung6eff0ff2021-07-30 19:01:48 -0700979 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
980 setAudioHwSyncForSession_l(thread, sessionId);
981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 }
Glenn Kastene198c362013-08-13 09:13:36 -0700983
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700984 if (lStatus != NO_ERROR) {
985 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -0700986 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -0700987 // Don't hold mClientLock when releasing the reference on the track as the
988 // destructor will acquire it.
989 {
990 Mutex::Autolock _cl(mClientLock);
991 client.clear();
992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700994 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995 }
996
Eric Laurent6c796322019-04-09 14:13:17 -0700997 // effectThreadId is not NONE if an effect chain corresponding to the track session
998 // was found on another thread and must be moved on this thread
999 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1000 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1001 }
1002
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001003 // return handle to client
1004 trackHandle = new TrackHandle(track);
1005
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001007 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001008 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001009 }
Glenn Kasten9156ef32013-08-06 15:39:08 -07001010 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 return trackHandle;
1012}
1013
Glenn Kasten2c073da2016-02-26 09:14:08 -08001014uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015{
1016 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001017 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001019 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 return 0;
1021 }
1022 return thread->sampleRate();
1023}
1024
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001025audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026{
1027 Mutex::Autolock _l(mLock);
1028 PlaybackThread *thread = checkPlaybackThread_l(output);
1029 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001030 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001031 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 }
1033 return thread->format();
1034}
1035
Glenn Kasten2c073da2016-02-26 09:14:08 -08001036size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037{
1038 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001039 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001041 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 return 0;
1043 }
Glenn Kasten58912562012-04-03 10:45:00 -07001044 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1045 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 return thread->frameCount();
1047}
1048
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001049size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1050{
1051 Mutex::Autolock _l(mLock);
1052 ThreadBase *thread = checkThread_l(ioHandle);
1053 if (thread == NULL) {
1054 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1055 return 0;
1056 }
1057 return thread->frameCountHAL();
1058}
1059
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001060uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061{
1062 Mutex::Autolock _l(mLock);
1063 PlaybackThread *thread = checkPlaybackThread_l(output);
1064 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001065 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 return 0;
1067 }
1068 return thread->latency();
1069}
1070
1071status_t AudioFlinger::setMasterVolume(float value)
1072{
Eric Laurenta1884f92011-08-23 08:25:03 -07001073 status_t ret = initCheck();
1074 if (ret != NO_ERROR) {
1075 return ret;
1076 }
1077
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 // check calling permissions
1079 if (!settingsAllowed()) {
1080 return PERMISSION_DENIED;
1081 }
1082
Eric Laurenta4c5a552012-03-29 10:12:40 -07001083 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001084 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001085
John Grossmanee578c02012-07-23 17:05:46 -07001086 // Set master volume in the HALs which support it.
Eric Laurent488d5002020-05-14 09:13:30 -07001087 {
John Grossmanee578c02012-07-23 17:05:46 -07001088 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001089 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1090 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001091
Eric Laurent488d5002020-05-14 09:13:30 -07001092 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1093 if (dev->canSetMasterVolume()) {
1094 dev->hwDevice()->setMasterVolume(value);
1095 }
1096 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 }
John Grossmanee578c02012-07-23 17:05:46 -07001099 // Now set the master volume in each playback thread. Playback threads
1100 // assigned to HALs which do not have master volume support will apply
1101 // master volume during the mix operation. Threads with HALs which do
1102 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1104 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1105 continue;
1106 }
John Grossmanee578c02012-07-23 17:05:46 -07001107 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109
1110 return NO_ERROR;
1111}
1112
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001113status_t AudioFlinger::setMasterBalance(float balance)
1114{
1115 status_t ret = initCheck();
1116 if (ret != NO_ERROR) {
1117 return ret;
1118 }
1119
1120 // check calling permissions
1121 if (!settingsAllowed()) {
1122 return PERMISSION_DENIED;
1123 }
1124
1125 // check range
1126 if (isnan(balance) || fabs(balance) > 1.f) {
1127 return BAD_VALUE;
1128 }
1129
1130 Mutex::Autolock _l(mLock);
1131
1132 // short cut.
1133 if (mMasterBalance == balance) return NO_ERROR;
1134
1135 mMasterBalance = balance;
1136
1137 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1138 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1139 continue;
1140 }
1141 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1142 }
1143
1144 return NO_ERROR;
1145}
1146
Glenn Kastenf78aee72012-01-04 11:00:47 -08001147status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148{
Eric Laurenta1884f92011-08-23 08:25:03 -07001149 status_t ret = initCheck();
1150 if (ret != NO_ERROR) {
1151 return ret;
1152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153
1154 // check calling permissions
1155 if (!settingsAllowed()) {
1156 return PERMISSION_DENIED;
1157 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001158 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001159 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 return BAD_VALUE;
1161 }
1162
1163 { // scope for the lock
1164 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001165 if (mPrimaryHardwareDev == nullptr) {
1166 return INVALID_OPERATION;
1167 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001168 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001170 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mHardwareStatus = AUDIO_HW_IDLE;
1172 }
1173
1174 if (NO_ERROR == ret) {
1175 Mutex::Autolock _l(mLock);
1176 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001177 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001178 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 }
1180
Joey Poomarin52989982020-03-05 17:40:49 +08001181 mediametrics::LogItem(mMetricsId)
1182 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1183 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1184 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 return ret;
1186}
1187
1188status_t AudioFlinger::setMicMute(bool state)
1189{
Eric Laurenta1884f92011-08-23 08:25:03 -07001190 status_t ret = initCheck();
1191 if (ret != NO_ERROR) {
1192 return ret;
1193 }
1194
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 // check calling permissions
1196 if (!settingsAllowed()) {
1197 return PERMISSION_DENIED;
1198 }
1199
1200 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001201 if (mPrimaryHardwareDev == nullptr) {
1202 return INVALID_OPERATION;
1203 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001204 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1205 if (primaryDev == nullptr) {
1206 ALOGW("%s: no primary HAL device", __func__);
1207 return INVALID_OPERATION;
1208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001210 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001211 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001212 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurenta135dd82020-05-14 09:07:39 -07001213 if (dev != primaryDev) {
1214 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001215 }
1216 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001218 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 return ret;
1220}
1221
1222bool AudioFlinger::getMicMute() const
1223{
Eric Laurenta1884f92011-08-23 08:25:03 -07001224 status_t ret = initCheck();
1225 if (ret != NO_ERROR) {
1226 return false;
1227 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001228 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001229 if (mPrimaryHardwareDev == nullptr) {
1230 return false;
1231 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001232 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1233 if (primaryDev == nullptr) {
1234 ALOGW("%s: no primary HAL device", __func__);
1235 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001236 }
Eric Laurenta135dd82020-05-14 09:07:39 -07001237 bool state;
1238 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1239 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta135dd82020-05-14 09:07:39 -07001241 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1242 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243}
1244
Eric Laurent5ada82e2019-08-29 17:53:54 -07001245void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001246{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001247 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001248
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001249 AutoMutex lock(mLock);
1250 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001251 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001252 }
1253 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001254 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001255 }
1256}
1257
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258status_t AudioFlinger::setMasterMute(bool muted)
1259{
John Grossmand8f178d2012-07-20 14:51:35 -07001260 status_t ret = initCheck();
1261 if (ret != NO_ERROR) {
1262 return ret;
1263 }
1264
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 // check calling permissions
1266 if (!settingsAllowed()) {
1267 return PERMISSION_DENIED;
1268 }
1269
John Grossmanee578c02012-07-23 17:05:46 -07001270 Mutex::Autolock _l(mLock);
1271 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001272
John Grossmanee578c02012-07-23 17:05:46 -07001273 // Set master mute in the HALs which support it.
Eric Laurent488d5002020-05-14 09:13:30 -07001274 {
John Grossmanee578c02012-07-23 17:05:46 -07001275 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001276 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1277 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001278
Eric Laurent488d5002020-05-14 09:13:30 -07001279 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1280 if (dev->canSetMasterMute()) {
1281 dev->hwDevice()->setMasterMute(muted);
1282 }
1283 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001284 }
John Grossmand8f178d2012-07-20 14:51:35 -07001285 }
1286
John Grossmanee578c02012-07-23 17:05:46 -07001287 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001288 // assigned to HALs which do not have master mute support will apply master mute
1289 // during the mix operation. Threads with HALs which do support master mute
1290 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001291 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1292 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1293 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295
1296 return NO_ERROR;
1297}
1298
1299float AudioFlinger::masterVolume() const
1300{
Glenn Kasten98067102011-12-13 11:47:54 -08001301 Mutex::Autolock _l(mLock);
1302 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303}
1304
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001305status_t AudioFlinger::getMasterBalance(float *balance) const
1306{
1307 Mutex::Autolock _l(mLock);
1308 *balance = getMasterBalance_l();
1309 return NO_ERROR; // if called through binder, may return a transactional error
1310}
1311
Mathias Agopian65ab4712010-07-14 17:59:35 -07001312bool AudioFlinger::masterMute() const
1313{
Glenn Kasten98067102011-12-13 11:47:54 -08001314 Mutex::Autolock _l(mLock);
1315 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316}
1317
John Grossman4ff14ba2012-02-08 16:37:41 -08001318float AudioFlinger::masterVolume_l() const
1319{
John Grossman4ff14ba2012-02-08 16:37:41 -08001320 return mMasterVolume;
1321}
1322
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001323float AudioFlinger::getMasterBalance_l() const
1324{
1325 return mMasterBalance;
1326}
1327
John Grossmand8f178d2012-07-20 14:51:35 -07001328bool AudioFlinger::masterMute_l() const
1329{
John Grossmanee578c02012-07-23 17:05:46 -07001330 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001331}
1332
Eric Laurent223fd5c2014-11-11 13:43:36 -08001333status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1334{
1335 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001336 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001337 return BAD_VALUE;
1338 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001339 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1340 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1341 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001342 return PERMISSION_DENIED;
1343 }
1344
1345 return NO_ERROR;
1346}
1347
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001348status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1349 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350{
1351 // check calling permissions
1352 if (!settingsAllowed()) {
1353 return PERMISSION_DENIED;
1354 }
1355
Eric Laurent223fd5c2014-11-11 13:43:36 -08001356 status_t status = checkStreamType(stream);
1357 if (status != NO_ERROR) {
1358 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359 }
Eric Laurent98e38192018-02-15 18:31:53 -08001360 if (output == AUDIO_IO_HANDLE_NONE) {
1361 return BAD_VALUE;
1362 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001363 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1364 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365
1366 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001367 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1368 if (volumeInterface == NULL) {
1369 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370 }
Eric Laurent98e38192018-02-15 18:31:53 -08001371 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372
1373 return NO_ERROR;
1374}
1375
Glenn Kastenfff6d712012-01-12 16:38:12 -08001376status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
1378 // check calling permissions
1379 if (!settingsAllowed()) {
1380 return PERMISSION_DENIED;
1381 }
1382
Eric Laurent223fd5c2014-11-11 13:43:36 -08001383 status_t status = checkStreamType(stream);
1384 if (status != NO_ERROR) {
1385 return status;
1386 }
1387 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1388
1389 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001390 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 return BAD_VALUE;
1392 }
1393
Eric Laurent93575202011-01-18 18:39:02 -08001394 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001396 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1397 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1398 volumeInterfaces[i]->setStreamMute(stream, muted);
1399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400
1401 return NO_ERROR;
1402}
1403
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001404float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001406 status_t status = checkStreamType(stream);
1407 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408 return 0.0f;
1409 }
Eric Laurent98e38192018-02-15 18:31:53 -08001410 if (output == AUDIO_IO_HANDLE_NONE) {
1411 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 }
1413
Eric Laurent98e38192018-02-15 18:31:53 -08001414 AutoMutex lock(mLock);
1415 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1416 if (volumeInterface == NULL) {
1417 return 0.0f;
1418 }
1419
1420 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421}
1422
Glenn Kastenfff6d712012-01-12 16:38:12 -08001423bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001425 status_t status = checkStreamType(stream);
1426 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 return true;
1428 }
1429
Glenn Kasten6637baa2012-01-09 09:40:36 -08001430 AutoMutex lock(mLock);
1431 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432}
1433
Eric Laurent054d9d32015-04-24 08:48:48 -07001434
1435void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1436{
1437 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1438 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1439 }
1440}
1441
jiabin10d86fd2019-10-31 17:20:42 -07001442void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1443{
1444 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1445 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1446 }
1447}
1448
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001449// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1450void AudioFlinger::forwardParametersToDownstreamPatches_l(
1451 audio_io_handle_t upStream, const String8& keyValuePairs,
1452 std::function<bool(const sp<PlaybackThread>&)> useThread)
1453{
1454 std::vector<PatchPanel::SoftwarePatch> swPatches;
1455 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1456 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1457 __func__, swPatches.size(), upStream);
1458 for (const auto& swPatch : swPatches) {
1459 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1460 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1461 downStream->setParameters(keyValuePairs);
1462 }
1463 }
1464}
1465
Eric Laurent029e33e2020-12-23 18:19:44 +01001466// Update downstream patches for all playback threads attached to an MSD module
1467void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
1468 const std::set<audio_io_handle_t> streams)
1469{
1470 for (const audio_io_handle_t stream : streams) {
1471 PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
1472 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1473 continue;
1474 }
1475 playbackThread->setDownStreamPatch(patch);
1476 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1477 }
1478}
1479
Eric Laurentf1047e82018-04-16 19:18:20 -07001480// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1481// Some keys are used for audio routing and audio path configuration and should be reserved for use
1482// by audio policy and audio flinger for functional, privacy and security reasons.
1483void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1484{
1485 static const String8 kReservedParameters[] = {
1486 String8(AudioParameter::keyRouting),
1487 String8(AudioParameter::keySamplingRate),
1488 String8(AudioParameter::keyFormat),
1489 String8(AudioParameter::keyChannels),
1490 String8(AudioParameter::keyFrameCount),
1491 String8(AudioParameter::keyInputSource),
1492 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovbb3b1602019-07-08 15:28:43 -07001493 String8(AudioParameter::keyDeviceConnect),
1494 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001495 String8(AudioParameter::keyStreamSupportedFormats),
1496 String8(AudioParameter::keyStreamSupportedChannels),
1497 String8(AudioParameter::keyStreamSupportedSamplingRates),
1498 };
1499
Andy Hung4ef19fa2018-05-15 19:35:29 -07001500 if (isAudioServerUid(callingUid)) {
1501 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001502 }
1503
1504 AudioParameter param = AudioParameter(keyValuePairs);
1505 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001506 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001507 for (auto& key : kReservedParameters) {
1508 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001509 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001510 param.remove(key);
1511 }
1512 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001513 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1514 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001515 keyValuePairs = param.toString();
1516}
1517
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001518void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1519 size_t rejectedKVPSize, const String8& rejectedKVPs,
1520 uid_t callingUid) {
1521 auto prefix = String8::format("UID %5d", callingUid);
1522 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1523 if (rejectedKVPSize != 0) {
1524 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1525 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1526 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1527 } else {
1528 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1529 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1530 }
1531}
1532
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001533status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534{
Eric Laurentf1047e82018-04-16 19:18:20 -07001535 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1536 ioHandle, keyValuePairs.string(),
1537 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 // check calling permissions
1540 if (!settingsAllowed()) {
1541 return PERMISSION_DENIED;
1542 }
1543
Eric Laurentf1047e82018-04-16 19:18:20 -07001544 String8 filteredKeyValuePairs = keyValuePairs;
1545 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1546
1547 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1548
Glenn Kasten142f5192014-03-25 17:44:59 -07001549 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1550 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001551 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001552 // result will remain NO_INIT if no audio device is present
1553 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001554 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001555 AutoMutex lock(mHardwareLock);
1556 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1557 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001558 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001559 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001560 // return success if at least one audio device accepts the parameters as not all
1561 // HALs are requested to support all parameters. If no audio device supports the
1562 // requested parameters, the last error is reported.
1563 if (final_result != NO_ERROR) {
1564 final_result = result;
1565 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001566 }
1567 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001568 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001569 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001570 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001571 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001572 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1573 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001574 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001575 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001576 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001577 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001578 }
1579 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001580 String8 screenState;
1581 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001582 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001583 if (isOff != (AudioFlinger::mScreenState & 1)) {
1584 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001585 }
1586 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001587 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 }
1589
1590 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1591 // and the thread is exited once the lock is released
1592 sp<ThreadBase> thread;
1593 {
1594 Mutex::Autolock _l(mLock);
1595 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001596 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001598 if (thread == 0) {
1599 thread = checkMmapThread_l(ioHandle);
1600 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001601 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001602 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001603 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001604 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001605 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1606 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001607 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001608 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 }
1610 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001611 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001612 status_t result = thread->setParameters(filteredKeyValuePairs);
1613 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1614 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 }
1616 return BAD_VALUE;
1617}
1618
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001619String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001621 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1622 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623
Eric Laurenta4c5a552012-03-29 10:12:40 -07001624 Mutex::Autolock _l(mLock);
1625
Glenn Kasten142f5192014-03-25 17:44:59 -07001626 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001627 String8 out_s8;
1628
Eric Laurent488d5002020-05-14 09:13:30 -07001629 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001630 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001631 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001632 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001633 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent488d5002020-05-14 09:13:30 -07001634 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001635 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001636 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001637 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001638 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 }
1640
Eric Laurent6acd1d42017-01-04 14:23:29 -08001641 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1642 if (thread == NULL) {
1643 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1644 if (thread == NULL) {
1645 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1646 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001647 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001648 }
1649 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001651 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652}
1653
Glenn Kastendd8104c2012-07-02 12:42:44 -07001654size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1655 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656{
Eric Laurenta1884f92011-08-23 08:25:03 -07001657 status_t ret = initCheck();
1658 if (ret != NO_ERROR) {
1659 return 0;
1660 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001661 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001662 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001663 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001664 return 0;
1665 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001666
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001667 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001668 if (mPrimaryHardwareDev == nullptr) {
1669 return 0;
1670 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001671 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001672
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001673 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001674 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1675 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1676 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1677 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1678 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1679
1680 std::vector<audio_format_t> formats = {format};
1681 if (format != AUDIO_FORMAT_PCM_16_BIT)
1682 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1683
1684 std::vector<uint32_t> sampleRates = {sampleRate};
1685 static const uint32_t SR_44100 = 44100;
1686 static const uint32_t SR_48000 = 48000;
1687
1688 if (sampleRate != SR_48000)
1689 sampleRates.push_back(SR_48000);
1690 if (sampleRate != SR_44100)
1691 sampleRates.push_back(SR_44100);
1692
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001693 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001694
Robin Lee9899ff72019-12-24 22:02:08 +01001695 // Change parameters of the configuration each iteration until we find a
1696 // configuration that the device will support.
1697 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001698 for (auto testChannelMask : channelMasks) {
1699 config.channel_mask = testChannelMask;
1700 for (auto testFormat : formats) {
1701 config.format = testFormat;
1702 for (auto testSampleRate : sampleRates) {
1703 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001704
Judy Hsiaoabab5222019-11-09 18:14:58 +08001705 size_t bytes = 0;
1706 status_t result = dev->getInputBufferSize(&config, &bytes);
1707 if (result != OK || bytes == 0) {
1708 continue;
1709 }
1710
1711 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1712 config.format != format) {
1713 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1714 uint32_t srcChannelCount =
1715 audio_channel_count_from_in_mask(config.channel_mask);
1716 size_t srcFrames =
1717 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1718 size_t dstFrames = destinationFramesPossible(
1719 srcFrames, config.sample_rate, sampleRate);
1720 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1721 }
1722 return bytes;
1723 }
1724 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001725 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001726
1727 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1728 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1729 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730}
1731
Glenn Kasten5f972c02014-01-13 09:59:31 -08001732uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734 Mutex::Autolock _l(mLock);
1735
1736 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1737 if (recordThread != NULL) {
1738 return recordThread->getInputFramesLost();
1739 }
1740 return 0;
1741}
1742
1743status_t AudioFlinger::setVoiceVolume(float value)
1744{
Eric Laurenta1884f92011-08-23 08:25:03 -07001745 status_t ret = initCheck();
1746 if (ret != NO_ERROR) {
1747 return ret;
1748 }
1749
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 // check calling permissions
1751 if (!settingsAllowed()) {
1752 return PERMISSION_DENIED;
1753 }
1754
1755 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07001756 if (mPrimaryHardwareDev == nullptr) {
1757 return INVALID_OPERATION;
1758 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001759 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001760 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001761 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 mHardwareStatus = AUDIO_HW_IDLE;
1763
Joey Poomarin52989982020-03-05 17:40:49 +08001764 mediametrics::LogItem(mMetricsId)
1765 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1766 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1767 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 return ret;
1769}
1770
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001771status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001772 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774 Mutex::Autolock _l(mLock);
1775
1776 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1777 if (playbackThread != NULL) {
1778 return playbackThread->getRenderPosition(halFrames, dspFrames);
1779 }
1780
1781 return BAD_VALUE;
1782}
1783
1784void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1785{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001787 if (client == 0) {
1788 return;
1789 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001790 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001791 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001792 {
1793 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001794 if (mNotificationClients.indexOfKey(pid) < 0) {
1795 sp<NotificationClient> notificationClient = new NotificationClient(this,
1796 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001797 pid,
1798 uid);
1799 ALOGV("registerClient() client %p, pid %d, uid %u",
1800 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801
Eric Laurent021cf962014-05-13 10:18:14 -07001802 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803
Marco Nelissen06b46062014-11-14 07:58:25 -08001804 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001805 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001806 }
1807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808
Eric Laurent021cf962014-05-13 10:18:14 -07001809 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001810 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001811 // the config change is always sent from playback or record threads to avoid deadlock
1812 // with AudioSystem::gLock
1813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001814 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001815 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001817 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001818 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 }
1820}
1821
1822void AudioFlinger::removeNotificationClient(pid_t pid)
1823{
Eric Laurent6c796322019-04-09 14:13:17 -07001824 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001825 {
Eric Laurent6c796322019-04-09 14:13:17 -07001826 Mutex::Autolock _l(mLock);
1827 {
1828 Mutex::Autolock _cl(mClientLock);
1829 mNotificationClients.removeItem(pid);
1830 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001831
Eric Laurent6c796322019-04-09 14:13:17 -07001832 ALOGV("%d died, releasing its sessions", pid);
1833 size_t num = mAudioSessionRefs.size();
1834 bool removed = false;
1835 for (size_t i = 0; i < num; ) {
1836 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1837 ALOGV(" pid %d @ %zu", ref->mPid, i);
1838 if (ref->mPid == pid) {
1839 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1840 mAudioSessionRefs.removeAt(i);
1841 delete ref;
1842 removed = true;
1843 num--;
1844 } else {
1845 i++;
1846 }
1847 }
1848 if (removed) {
1849 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001850 }
1851 }
Eric Laurent6c796322019-04-09 14:13:17 -07001852 for (auto& effect : removedEffects) {
1853 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001854 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855}
1856
Eric Laurent73e26b62015-04-27 16:55:58 -07001857void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001858 const sp<AudioIoDescriptor>& ioDesc,
1859 pid_t pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860{
Eric Laurent021cf962014-05-13 10:18:14 -07001861 Mutex::Autolock _l(mClientLock);
1862 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001864 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
1865 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioDesc);
1866 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 }
1868}
1869
Eric Laurent021cf962014-05-13 10:18:14 -07001870// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871void AudioFlinger::removeClient_l(pid_t pid)
1872{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001873 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001874 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 mClients.removeItem(pid);
1876}
1877
Eric Laurent717e1282012-06-29 16:36:52 -07001878// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001879sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1880 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001881{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001882 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001883
1884 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001885 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001886 ALOG_ASSERT(thread == 0);
1887 thread = mPlaybackThreads.valueAt(i);
1888 }
1889 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001890 if (thread != nullptr) {
1891 return thread;
1892 }
1893 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1894 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1895 ALOG_ASSERT(thread == 0);
1896 thread = mRecordThreads.valueAt(i);
1897 }
1898 }
1899 if (thread != nullptr) {
1900 return thread;
1901 }
1902 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1903 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1904 ALOG_ASSERT(thread == 0);
1905 thread = mMmapThreads.valueAt(i);
1906 }
1907 }
Eric Laurent717e1282012-06-29 16:36:52 -07001908 return thread;
1909}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912
1913// ----------------------------------------------------------------------------
1914
1915AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1916 : RefBase(),
1917 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001918 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919{
Andy Hung6f248bb2018-01-23 14:04:37 -08001920 mMemoryDealer = new MemoryDealer(
1921 audioFlinger->getClientSharedHeapSize(),
1922 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923}
1924
Eric Laurent021cf962014-05-13 10:18:14 -07001925// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926AudioFlinger::Client::~Client()
1927{
1928 mAudioFlinger->removeClient_l(mPid);
1929}
1930
Glenn Kasten435dbe62012-01-30 10:15:48 -08001931sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932{
1933 return mMemoryDealer;
1934}
1935
1936// ----------------------------------------------------------------------------
1937
1938AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
1939 const sp<IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001940 pid_t pid,
1941 uid_t uid)
1942 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943{
1944}
1945
1946AudioFlinger::NotificationClient::~NotificationClient()
1947{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948}
1949
Glenn Kasten0f11b512014-01-31 16:18:54 -08001950void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951{
1952 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001953 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954}
1955
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001956// ----------------------------------------------------------------------------
1957AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1958 : mPendingRequests(false) {}
1959
1960
1961void AudioFlinger::MediaLogNotifier::requestMerge() {
1962 AutoMutex _l(mMutex);
1963 mPendingRequests = true;
1964 mCond.signal();
1965}
1966
1967bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001968 // Should already have been checked, but just in case
1969 if (sMediaLogService == 0) {
1970 return false;
1971 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001972 // Wait until there are pending requests
1973 {
1974 AutoMutex _l(mMutex);
1975 mPendingRequests = false; // to ignore past requests
1976 while (!mPendingRequests) {
1977 mCond.wait(mMutex);
1978 // TODO may also need an exitPending check
1979 }
1980 mPendingRequests = false;
1981 }
1982 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001983 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001984 usleep(kPostTriggerSleepPeriod);
1985 return true;
1986}
1987
1988void AudioFlinger::requestLogMerge() {
1989 mMediaLogNotifier->requestMerge();
1990}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991
1992// ----------------------------------------------------------------------------
1993
Eric Laurentf14db3c2017-12-08 14:20:36 -08001994sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
1995 CreateRecordOutput& output,
1996 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997{
1998 sp<RecordThread::RecordTrack> recordTrack;
1999 sp<RecordHandle> recordHandle;
2000 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002002 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002003 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004
Eric Laurentf14db3c2017-12-08 14:20:36 -08002005 output.cblk.clear();
2006 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002007 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002008
Eric Laurentf14db3c2017-12-08 14:20:36 -08002009 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002010 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08002011 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07002012 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002013 ALOGW_IF(clientUid != callingUid,
2014 "%s uid %d tried to pass itself off as %d",
2015 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002016 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002017 updatePid = true;
2018 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002019 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002020 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002021 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002022 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002023 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08002024 __func__, callingUid, callingPid, clientPid);
2025 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07002026 }
2027
Andy Hung6770c6f2015-04-07 13:43:36 -07002028 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002029 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2030 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002031 lStatus = BAD_VALUE;
2032 goto Exit;
2033 }
2034
Glenn Kasten53b5d092014-02-05 10:00:23 -08002035 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002036 if (!audio_is_input_channel(input.config.channel_mask)) {
2037 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002038 lStatus = BAD_VALUE;
2039 goto Exit;
2040 }
2041
Eric Laurentf14db3c2017-12-08 14:20:36 -08002042 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2043 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2044 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2045 lStatus = BAD_VALUE;
2046 goto Exit;
2047 }
2048
2049 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002050 output.selectedDeviceId = input.selectedDeviceId;
2051 output.flags = input.flags;
2052
2053 client = registerPid(clientPid);
2054
2055 // Not a conventional loop, but a retry loop for at most two iterations total.
2056 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2057 // Exits loop via break on no error of got exit on error
2058 // The sp<> references will be dropped when re-entering scope.
2059 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2060 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002061 // release previously opened input if retrying.
2062 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2063 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002064 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002065 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002066 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002067 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002068 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002069 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002070 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002071 sessionId,
2072 // FIXME compare to AudioTrack
2073 clientPid,
2074 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002075 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002076 &input.config,
2077 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002078 if (lStatus != NO_ERROR) {
2079 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2080 goto Exit;
2081 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002082
Glenn Kasten05997e22014-03-13 15:08:33 -07002083 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002085 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 if (thread == NULL) {
Eric Laurent717bc282020-08-21 17:10:39 -07002087 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2088 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 goto Exit;
2090 }
2091
Eric Laurentf14db3c2017-12-08 14:20:36 -08002092 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093
Eric Laurentf14db3c2017-12-08 14:20:36 -08002094 output.sampleRate = input.config.sample_rate;
2095 output.frameCount = input.frameCount;
2096 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002097
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002098 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002099 input.config.format, input.config.channel_mask,
2100 &output.frameCount, sessionId,
2101 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002102 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002103 input.clientInfo.clientTid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07002104 &lStatus, portId,
2105 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002106 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002107
Eric Laurentf14db3c2017-12-08 14:20:36 -08002108 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2109 // audio policy manager without FAST constraint
2110 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002111 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002112 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002113
2114 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002115 goto Exit;
2116 }
2117
2118 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2119 // session and move it to this thread.
2120 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2121 if (chain != 0) {
2122 Mutex::Autolock _l(thread->mLock);
2123 thread->addEffectChain_l(chain);
2124 }
2125 break;
2126 }
2127 // End of retry loop.
2128 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 }
Glenn Kastene198c362013-08-13 09:13:36 -07002130
Eric Laurentf14db3c2017-12-08 14:20:36 -08002131 output.cblk = recordTrack->getCblk();
2132 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002133 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002134
2135 // return handle to client
2136 recordHandle = new RecordHandle(recordTrack);
2137
2138Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002139 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002140 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002141 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002142 // Don't hold mClientLock when releasing the reference on the track as the
2143 // destructor will acquire it.
2144 {
2145 Mutex::Autolock _cl(mClientLock);
2146 client.clear();
2147 }
Eric Laurent896c9672017-12-08 14:08:45 -08002148 recordTrack.clear();
2149 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002150 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002151 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 }
2153
Glenn Kasten9156ef32013-08-06 15:39:08 -07002154 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 return recordHandle;
2156}
2157
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002158
2159
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160// ----------------------------------------------------------------------------
2161
Eric Laurenta4c5a552012-03-29 10:12:40 -07002162audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2163{
Eric Laurent44622db2014-08-01 19:00:33 -07002164 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002165 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002166 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002167 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002168 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002169 }
2170 Mutex::Autolock _l(mLock);
Eric Laurent488d5002020-05-14 09:13:30 -07002171 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002172 return loadHwModule_l(name);
2173}
2174
Eric Laurent488d5002020-05-14 09:13:30 -07002175// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002176audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2177{
2178 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2179 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2180 ALOGW("loadHwModule() module %s already loaded", name);
2181 return mAudioHwDevs.keyAt(i);
2182 }
2183 }
2184
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002185 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002186
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002187 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002188 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002189 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002190 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002191 }
2192
2193 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002194 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002195 mHardwareStatus = AUDIO_HW_IDLE;
2196 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002197 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002198 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002199 }
2200
John Grossmanee578c02012-07-23 17:05:46 -07002201 // Check and cache this HAL's level of support for master mute and master
2202 // volume. If this is the first HAL opened, and it supports the get
2203 // methods, use the initial values provided by the HAL as the current
2204 // master mute and volume settings.
2205
2206 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent488d5002020-05-14 09:13:30 -07002207 if (0 == mAudioHwDevs.size()) {
2208 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2209 float mv;
2210 if (OK == dev->getMasterVolume(&mv)) {
2211 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002212 }
2213
Eric Laurent488d5002020-05-14 09:13:30 -07002214 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2215 bool mm;
2216 if (OK == dev->getMasterMute(&mm)) {
2217 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002218 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002219 }
Eric Laurent488d5002020-05-14 09:13:30 -07002220
2221 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2222 if (OK == dev->setMasterVolume(mMasterVolume)) {
2223 flags = static_cast<AudioHwDevice::Flags>(flags |
2224 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2225 }
2226
2227 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2228 if (OK == dev->setMasterMute(mMasterMute)) {
2229 flags = static_cast<AudioHwDevice::Flags>(flags |
2230 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2231 }
2232
2233 mHardwareStatus = AUDIO_HW_IDLE;
2234
Mikhail Naganov97373b02018-07-23 13:27:24 -07002235 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002236 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2237 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2238 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002239
Glenn Kastena13cde92016-03-28 15:26:02 -07002240 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent488d5002020-05-14 09:13:30 -07002241 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2242 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2243 mPrimaryHardwareDev = audioDevice;
2244 mHardwareStatus = AUDIO_HW_SET_MODE;
2245 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2246 mHardwareStatus = AUDIO_HW_IDLE;
2247 }
2248
2249 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002250
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002251 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002252
2253 return handle;
2254
2255}
2256
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002257// ----------------------------------------------------------------------------
2258
Glenn Kasten3b16c762012-11-14 08:44:39 -08002259uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002260{
2261 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002262 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002263 return thread != NULL ? thread->sampleRate() : 0;
2264}
2265
Glenn Kastene33054e2012-11-14 12:54:39 -08002266size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002267{
2268 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002269 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002270 return thread != NULL ? thread->frameCountHAL() : 0;
2271}
2272
2273// ----------------------------------------------------------------------------
2274
Andy Hung6f248bb2018-01-23 14:04:37 -08002275status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002276{
2277 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002278 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002279 return PERMISSION_DENIED;
2280 }
2281 Mutex::Autolock _l(mLock);
2282 if (mIsDeviceTypeKnown) {
2283 return INVALID_OPERATION;
2284 }
2285 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002286 mTotalMemory = totalMemory;
2287 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2288 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2289 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2290 // though actual setting is determined through device configuration.
2291 constexpr int64_t GB = 1024 * 1024 * 1024;
2292 mClientSharedHeapSize =
2293 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2294 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2295 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2296 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2297 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002298 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002299
2300 // TODO: Cache the client shared heap size in a persistent property.
2301 // It's possible that a native process or Java service or app accesses audioserver
2302 // after it is registered by system server, but before AudioService updates
2303 // the memory info. This would occur immediately after boot or an audioserver
2304 // crash and restore. Before update from AudioService, the client would get the
2305 // minimum heap size.
2306
2307 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2308 (isLowRamDevice ? "true" : "false"),
2309 (long long)mTotalMemory,
2310 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002311 return NO_ERROR;
2312}
2313
Andy Hung6f248bb2018-01-23 14:04:37 -08002314size_t AudioFlinger::getClientSharedHeapSize() const
2315{
2316 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2317 if (heapSizeInBytes != 0) { // read-only property overrides all.
2318 return heapSizeInBytes;
2319 }
2320 return mClientSharedHeapSize;
2321}
2322
Mikhail Naganovdea53042018-04-26 13:10:21 -07002323status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2324{
2325 ALOGV(__func__);
2326
2327 audio_module_handle_t module;
2328 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2329 module = config->ext.device.hw_module;
2330 } else {
2331 module = config->ext.mix.hw_module;
2332 }
2333
2334 Mutex::Autolock _l(mLock);
Eric Laurent488d5002020-05-14 09:13:30 -07002335 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002336 ssize_t index = mAudioHwDevs.indexOfKey(module);
2337 if (index < 0) {
2338 ALOGW("%s() bad hw module %d", __func__, module);
2339 return BAD_VALUE;
2340 }
2341
2342 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2343 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2344}
2345
Eric Laurent93c3d412014-08-01 14:48:35 -07002346audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2347{
2348 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002349
2350 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2351 if (index >= 0) {
2352 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2353 mHwAvSyncIds.valueAt(index), sessionId);
2354 return mHwAvSyncIds.valueAt(index);
2355 }
2356
Eric Laurent488d5002020-05-14 09:13:30 -07002357 sp<DeviceHalInterface> dev;
2358 {
2359 AutoMutex lock(mHardwareLock);
2360 if (mPrimaryHardwareDev == nullptr) {
2361 return AUDIO_HW_SYNC_INVALID;
2362 }
2363 dev = mPrimaryHardwareDev->hwDevice();
2364 }
2365 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002366 return AUDIO_HW_SYNC_INVALID;
2367 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002368 String8 reply;
2369 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002370 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002371 param = AudioParameter(reply);
2372 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002373
2374 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002375 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002376 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2377 return AUDIO_HW_SYNC_INVALID;
2378 }
2379
2380 // allow only one session for a given HW A/V sync ID.
2381 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2382 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2383 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2384 value, mHwAvSyncIds.keyAt(i));
2385 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002386 break;
2387 }
2388 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002389
2390 mHwAvSyncIds.add(sessionId, value);
2391
2392 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2393 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2394 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002395 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002396 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002397 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002398 String8 keyValuePairs = param.toString();
2399 thread->setParameters(keyValuePairs);
2400 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2401 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002402 break;
2403 }
2404 }
2405
2406 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2407 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002408}
2409
Eric Laurent72e3f392015-05-20 14:43:50 -07002410status_t AudioFlinger::systemReady()
2411{
2412 Mutex::Autolock _l(mLock);
2413 ALOGI("%s", __FUNCTION__);
2414 if (mSystemReady) {
2415 ALOGW("%s called twice", __FUNCTION__);
2416 return NO_ERROR;
2417 }
2418 mSystemReady = true;
2419 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2420 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2421 thread->systemReady();
2422 }
2423 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2424 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2425 thread->systemReady();
2426 }
2427 return NO_ERROR;
2428}
2429
jiabin46a76fa2018-01-05 10:18:21 -08002430status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2431{
jiabin9ff780e2018-03-19 18:19:52 -07002432 AutoMutex lock(mHardwareLock);
Eric Laurent488d5002020-05-14 09:13:30 -07002433 status_t status = INVALID_OPERATION;
2434
2435 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2436 std::vector<media::MicrophoneInfo> mics;
2437 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2438 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2439 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2440 mHardwareStatus = AUDIO_HW_IDLE;
2441 if (devStatus == NO_ERROR) {
2442 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2443 // report success if at least one HW module supports the function.
2444 status = NO_ERROR;
2445 }
2446 }
2447
jiabin9ff780e2018-03-19 18:19:52 -07002448 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002449}
2450
Eric Laurentfa90e842014-10-17 18:12:31 -07002451// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2452void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2453{
2454 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2455 if (index >= 0) {
2456 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2457 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2458 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002459 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002460 String8 keyValuePairs = param.toString();
2461 thread->setParameters(keyValuePairs);
2462 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2463 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002464 }
2465}
2466
2467
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002468// ----------------------------------------------------------------------------
2469
Eric Laurent83b88082014-06-20 18:31:16 -07002470
Eric Laurent6acd1d42017-01-04 14:23:29 -08002471sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabinc0106832019-10-24 14:58:31 -07002472 audio_io_handle_t *output,
2473 audio_config_t *config,
2474 audio_devices_t deviceType,
2475 const String8& address,
2476 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002477{
jiabinc0106832019-10-24 14:58:31 -07002478 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002479 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002480 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002481 }
2482
Eric Laurentcf2c0212014-07-25 16:20:43 -07002483 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002484 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2485 } else {
2486 // Audio Policy does not currently request a specific output handle.
2487 // If this is ever needed, see openInput_l() for example code.
2488 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2489 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002490 }
Eric Laurent83b88082014-06-20 18:31:16 -07002491
2492 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2493
Eric Laurent83b88082014-06-20 18:31:16 -07002494 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002495 // This if statement allows overriding the audio policy settings
2496 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2497 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2498 // Check only for Normal Mixing mode
2499 if (kEnableExtendedPrecision) {
2500 // Specify format (uncomment one below to choose)
2501 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2502 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2503 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2504 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002505 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002506 }
2507 if (kEnableExtendedChannels) {
2508 // Specify channel mask (uncomment one below to choose)
2509 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2510 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2511 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2512 }
Eric Laurent83b88082014-06-20 18:31:16 -07002513 }
2514
Phil Burk062e67a2015-02-11 13:40:50 -08002515 AudioStreamOut *outputStream = NULL;
2516 status_t status = outHwDev->openOutputStream(
2517 &outputStream,
2518 *output,
jiabinc0106832019-10-24 14:58:31 -07002519 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002520 flags,
2521 config,
2522 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002523
2524 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002525
Phil Burk062e67a2015-02-11 13:40:50 -08002526 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002527 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2528 sp<MmapPlaybackThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002529 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002530 mMmapThreads.add(*output, thread);
2531 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2532 *output, thread.get());
2533 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002534 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002535 sp<PlaybackThread> thread;
2536 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07002537 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002538 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2539 *output, thread.get());
2540 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2541 || !isValidPcmSinkFormat(config->format)
2542 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabin10d86fd2019-10-31 17:20:42 -07002543 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002544 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2545 *output, thread.get());
2546 } else {
jiabin10d86fd2019-10-31 17:20:42 -07002547 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002548 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2549 *output, thread.get());
2550 }
2551 mPlaybackThreads.add(*output, thread);
Eric Laurent029e33e2020-12-23 18:19:44 +01002552 struct audio_patch patch;
2553 mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
2554 if (thread->isMsdDevice()) {
2555 thread->setDownStreamPatch(&patch);
2556 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002557 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002558 }
Eric Laurent83b88082014-06-20 18:31:16 -07002559 }
2560
2561 return 0;
2562}
2563
Eric Laurentcf2c0212014-07-25 16:20:43 -07002564status_t AudioFlinger::openOutput(audio_module_handle_t module,
2565 audio_io_handle_t *output,
2566 audio_config_t *config,
jiabinc0106832019-10-24 14:58:31 -07002567 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002568 uint32_t *latencyMs,
2569 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570{
jiabinc0106832019-10-24 14:58:31 -07002571 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002572 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002573 this, module,
jiabinc0106832019-10-24 14:58:31 -07002574 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002575 config->sample_rate,
2576 config->format,
2577 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002578 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
jiabinc0106832019-10-24 14:58:31 -07002580 audio_devices_t deviceType = device->type();
2581 const String8 address = String8(device->address().c_str());
2582
2583 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002584 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002586
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 Mutex::Autolock _l(mLock);
2588
jiabinc0106832019-10-24 14:58:31 -07002589 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002590 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002591 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2592 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2593 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594
Eric Laurent6acd1d42017-01-04 14:23:29 -08002595 // notify client processes of the new output creation
2596 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002597
Eric Laurent488d5002020-05-14 09:13:30 -07002598 // the first primary output opened designates the primary hw device if no HW module
2599 // named "primary" was already loaded.
2600 AutoMutex lock(mHardwareLock);
2601 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002602 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002603 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002604
Eric Laurent6acd1d42017-01-04 14:23:29 -08002605 mHardwareStatus = AUDIO_HW_SET_MODE;
2606 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2607 mHardwareStatus = AUDIO_HW_IDLE;
2608 }
2609 } else {
2610 MmapThread *mmapThread = (MmapThread *)thread.get();
2611 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002612 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002613 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 }
2615
Eric Laurentcf2c0212014-07-25 16:20:43 -07002616 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617}
2618
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002619audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2620 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621{
2622 Mutex::Autolock _l(mLock);
2623 MixerThread *thread1 = checkMixerThread_l(output1);
2624 MixerThread *thread2 = checkMixerThread_l(output2);
2625
2626 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002627 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2628 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002629 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 }
2631
Glenn Kasteneeecb982016-02-26 10:44:04 -08002632 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002633 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 thread->addOutputTrack(thread2);
2635 mPlaybackThreads.add(id, thread);
2636 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002637 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 return id;
2639}
2640
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002641status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642{
Glenn Kastend96c5722012-04-25 13:44:49 -07002643 return closeOutput_nonvirtual(output);
2644}
2645
2646status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2647{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 // keep strong reference on the playback thread so that
2649 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002650 sp<PlaybackThread> playbackThread;
2651 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 {
2653 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002654 playbackThread = checkPlaybackThread_l(output);
2655 if (playbackThread != NULL) {
2656 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
Andy Hungdc099c22018-09-18 13:46:39 -07002658 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002659
Eric Laurent6acd1d42017-01-04 14:23:29 -08002660 if (playbackThread->type() == ThreadBase::MIXER) {
2661 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2662 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2663 DuplicatingThread *dupThread =
2664 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2665 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 }
2668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669
2670
Eric Laurent6acd1d42017-01-04 14:23:29 -08002671 mPlaybackThreads.removeItem(output);
2672 // save all effects to the default thread
2673 if (mPlaybackThreads.size()) {
2674 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2675 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002676 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002677 Mutex::Autolock _dl(dstThread->mLock);
2678 Mutex::Autolock _sl(playbackThread->mLock);
2679 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2680 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002681 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002682 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 }
2685 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002686 } else {
2687 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2688 if (mmapThread == 0) {
2689 return BAD_VALUE;
2690 }
Andy Hungdc099c22018-09-18 13:46:39 -07002691 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002692 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002693 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002694 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002695 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2696 ioDesc->mIoHandle = output;
2697 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002698 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002700 // The thread entity (active unit of execution) is no longer running here,
2701 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702
Eric Laurent6acd1d42017-01-04 14:23:29 -08002703 if (playbackThread != 0) {
2704 playbackThread->exit();
2705 if (!playbackThread->isDuplicating()) {
2706 closeOutputFinish(playbackThread);
2707 }
2708 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002709 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002710 mmapThread->exit();
2711 AudioStreamOut *out = mmapThread->clearOutput();
2712 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2713 // from now on thread->mOutput is NULL
2714 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 }
2716 return NO_ERROR;
2717}
2718
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002719void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002720{
2721 AudioStreamOut *out = thread->clearOutput();
2722 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2723 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002724 delete out;
2725}
2726
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002727void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002728{
2729 mPlaybackThreads.removeItem(thread->mId);
2730 thread->exit();
2731 closeOutputFinish(thread);
2732}
2733
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002734status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735{
2736 Mutex::Autolock _l(mLock);
2737 PlaybackThread *thread = checkPlaybackThread_l(output);
2738
2739 if (thread == NULL) {
2740 return BAD_VALUE;
2741 }
2742
Steve Block3856b092011-10-20 11:56:00 +01002743 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 thread->suspend();
2745
2746 return NO_ERROR;
2747}
2748
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002749status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750{
2751 Mutex::Autolock _l(mLock);
2752 PlaybackThread *thread = checkPlaybackThread_l(output);
2753
2754 if (thread == NULL) {
2755 return BAD_VALUE;
2756 }
2757
Steve Block3856b092011-10-20 11:56:00 +01002758 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759
2760 thread->restore();
2761
2762 return NO_ERROR;
2763}
2764
Eric Laurentcf2c0212014-07-25 16:20:43 -07002765status_t AudioFlinger::openInput(audio_module_handle_t module,
2766 audio_io_handle_t *input,
2767 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002768 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002769 const String8& address,
2770 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002771 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772{
Eric Laurent83b88082014-06-20 18:31:16 -07002773 Mutex::Autolock _l(mLock);
2774
Glenn Kastene7d66712015-03-05 13:46:52 -08002775 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002776 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002777 }
2778
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002779 sp<ThreadBase> thread = openInput_l(
2780 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002781
2782 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002783 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002784 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002785 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002787 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002788}
Dima Zavin799a70e2011-04-18 16:57:27 -07002789
Eric Laurent6acd1d42017-01-04 14:23:29 -08002790sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002791 audio_io_handle_t *input,
2792 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002793 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002794 const String8& address,
2795 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002796 audio_input_flags_t flags,
2797 audio_devices_t outputDevice,
2798 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002799{
Glenn Kastene7d66712015-03-05 13:46:52 -08002800 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002801 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002802 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002803 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002804 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002805
Glenn Kasteneeecb982016-02-26 10:44:04 -08002806 // Audio Policy can request a specific handle for hardware hotword.
2807 // The goal here is not to re-open an already opened input.
2808 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002809 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002810 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2811 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2812 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2813 return 0;
2814 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2815 // This should not happen in a transient state with current design.
2816 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2817 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002818 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002819
Eric Laurentcf2c0212014-07-25 16:20:43 -07002820 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002821 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002822 sp<StreamInHalInterface> inStream;
2823 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002824 *input, devices, &halconfig, flags, address.string(), source,
2825 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002826 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2827 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002828 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002829 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002830 halconfig.sample_rate,
2831 halconfig.format,
2832 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002833 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002834 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002836 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002837 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002838 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002839 audio_is_linear_pcm(config->format) &&
2840 audio_is_linear_pcm(halconfig.format) &&
2841 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002842 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2843 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002844 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002845 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002846 inStream.clear();
2847 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002848 *input, devices, &halconfig, flags, address.string(), source,
2849 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002850 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 }
2852
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002853 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002854 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002855 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2856 sp<MmapCaptureThread> thread =
jiabin10d86fd2019-10-31 17:20:42 -07002857 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002858 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002859 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2860 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002861 return thread;
2862 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002863 // Start record thread
2864 // RecordThread requires both input and output device indication to forward to audio
2865 // pre processing modules
jiabin10d86fd2019-10-31 17:20:42 -07002866 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002867 mRecordThreads.add(*input, thread);
2868 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2869 return thread;
2870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 }
2872
Eric Laurentcf2c0212014-07-25 16:20:43 -07002873 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 return 0;
2875}
2876
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002877status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878{
Glenn Kastend96c5722012-04-25 13:44:49 -07002879 return closeInput_nonvirtual(input);
2880}
2881
2882status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2883{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 // keep strong reference on the record thread so that
2885 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002886 sp<RecordThread> recordThread;
2887 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 {
2889 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002890 recordThread = checkRecordThread_l(input);
2891 if (recordThread != 0) {
2892 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893
Andy Hungdc099c22018-09-18 13:46:39 -07002894 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002895
Eric Laurent6acd1d42017-01-04 14:23:29 -08002896 // If we still have effect chains, it means that a client still holds a handle
2897 // on at least one effect. We must either move the chain to an existing thread with the
2898 // same session ID or put it aside in case a new record thread is opened for a
2899 // new capture on the same session
2900 sp<EffectChain> chain;
2901 {
2902 Mutex::Autolock _sl(recordThread->mLock);
2903 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2904 // Note: maximum one chain per record thread
2905 if (effectChains.size() != 0) {
2906 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002907 }
2908 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002909 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002910 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002911 // This should only happen in case of overlap between one thread tear down and the
2912 // creation of its replacement
2913 size_t i;
2914 for (i = 0; i < mRecordThreads.size(); i++) {
2915 sp<RecordThread> t = mRecordThreads.valueAt(i);
2916 if (t == recordThread) {
2917 continue;
2918 }
2919 if (t->hasAudioSession(chain->sessionId()) != 0) {
2920 Mutex::Autolock _l(t->mLock);
2921 ALOGV("closeInput() found thread %d for effect session %d",
2922 t->id(), chain->sessionId());
2923 t->addEffectChain_l(chain);
2924 break;
2925 }
2926 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002927 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002928 if (i == mRecordThreads.size()) {
2929 putOrphanEffectChain_l(chain);
2930 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002931 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002932 mRecordThreads.removeItem(input);
2933 } else {
2934 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2935 if (mmapThread == 0) {
2936 return BAD_VALUE;
2937 }
Andy Hungdc099c22018-09-18 13:46:39 -07002938 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002939 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002940 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002941 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2942 ioDesc->mIoHandle = input;
2943 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 }
Eric Laurent83b88082014-06-20 18:31:16 -07002945 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2946 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002947 if (recordThread != 0) {
2948 closeInputFinish(recordThread);
2949 } else if (mmapThread != 0) {
2950 mmapThread->exit();
2951 AudioStreamIn *in = mmapThread->clearInput();
2952 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2953 // from now on thread->mInput is NULL
2954 delete in;
2955 }
Eric Laurent83b88082014-06-20 18:31:16 -07002956 return NO_ERROR;
2957}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002959void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002960{
2961 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002962 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002963 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002964 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002965 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002966}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002968void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002969{
2970 mRecordThreads.removeItem(thread->mId);
2971 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972}
2973
Glenn Kastend2304db2014-02-03 07:40:31 -08002974status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975{
2976 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002977 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978
2979 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2980 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002981 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002982 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002983 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2984 mMmapThreads[i]->invalidateTracks(stream);
2985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 return NO_ERROR;
2987}
2988
2989
Glenn Kasteneeecb982016-02-26 10:44:04 -08002990audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991{
Glenn Kasten9d003132016-04-06 14:38:09 -07002992 // This is a binder API, so a malicious client could pass in a bad parameter.
2993 // Check for that before calling the internal API nextUniqueId().
2994 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2995 ALOGE("newAudioUniqueId invalid use %d", use);
2996 return AUDIO_UNIQUE_ID_ALLOCATE;
2997 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08002998 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002999}
3000
Andy Hung8b0bfd92019-12-23 13:11:11 -08003001void AudioFlinger::acquireAudioSessionId(
3002 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003003{
3004 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003005 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003006 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003007 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003008 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3009 caller = pid; // check must match releaseAudioSessionId()
3010 }
3011 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3012 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003013 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003014
Eric Laurent021cf962014-05-13 10:18:14 -07003015 {
3016 Mutex::Autolock _cl(mClientLock);
3017 // Ignore requests received from processes not known as notification client. The request
3018 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3019 // called from a different pid leaving a stale session reference. Also we don't know how
3020 // to clear this reference if the client process dies.
3021 if (mNotificationClients.indexOfKey(caller) < 0) {
3022 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3023 return;
3024 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003025 }
3026
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003027 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003028 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003029 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003030 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3031 ref->mCnt++;
3032 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003033 return;
3034 }
3035 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003036 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003037 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003038}
3039
Glenn Kastend848eb42016-03-08 13:42:11 -08003040void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003041{
Eric Laurent6c796322019-04-09 14:13:17 -07003042 std::vector< sp<EffectModule> > removedEffects;
3043 {
3044 Mutex::Autolock _l(mLock);
3045 pid_t caller = IPCThreadState::self()->getCallingPid();
3046 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3047 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003048 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3049 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003050 }
Eric Laurent6c796322019-04-09 14:13:17 -07003051 size_t num = mAudioSessionRefs.size();
3052 for (size_t i = 0; i < num; i++) {
3053 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3054 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3055 ref->mCnt--;
3056 ALOGV(" decremented refcount to %d", ref->mCnt);
3057 if (ref->mCnt == 0) {
3058 mAudioSessionRefs.removeAt(i);
3059 delete ref;
3060 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3061 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3062 }
3063 goto Exit;
3064 }
3065 }
3066 // If the caller is audioserver it is likely that the session being released was acquired
3067 // on behalf of a process not in notification clients and we ignore the warning.
3068 ALOGW_IF(!isAudioServerUid(callerUid),
3069 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003070 }
Eric Laurent6c796322019-04-09 14:13:17 -07003071
3072Exit:
3073 for (auto& effect : removedEffects) {
3074 effect->updatePolicyState();
3075 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003076}
3077
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003078bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3079{
3080 size_t num = mAudioSessionRefs.size();
3081 for (size_t i = 0; i < num; i++) {
3082 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3083 if (ref->mSessionid == audioSession) {
3084 return true;
3085 }
3086 }
3087 return false;
3088}
3089
Eric Laurent6c796322019-04-09 14:13:17 -07003090std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003091
Steve Block3856b092011-10-20 11:56:00 +01003092 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003093
3094 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003095 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003096
3097 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3098 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003099 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003100 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3101 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurenta20c4e92019-11-12 15:55:51 -08003102 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003103 chains.push(ec);
3104 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003105 }
3106 }
Eric Laurent6c796322019-04-09 14:13:17 -07003107
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003108 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3109 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003110 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003111 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3112 sp<EffectChain> ec = t->mEffectChains[j];
3113 chains.push(ec);
3114 }
3115 }
3116
Eric Laurent6c796322019-04-09 14:13:17 -07003117 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3118 sp<MmapThread> t = mMmapThreads.valueAt(i);
3119 Mutex::Autolock _l(t->mLock);
3120 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3121 sp<EffectChain> ec = t->mEffectChains[j];
3122 chains.push(ec);
3123 }
3124 }
3125
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003126 for (size_t i = 0; i < chains.size(); i++) {
3127 sp<EffectChain> ec = chains[i];
3128 int sessionid = ec->sessionId();
Eric Laurent5d885392019-12-13 10:56:31 -08003129 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003130 if (t == 0) {
3131 continue;
3132 }
3133 size_t numsessionrefs = mAudioSessionRefs.size();
3134 bool found = false;
3135 for (size_t k = 0; k < numsessionrefs; k++) {
3136 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003137 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003138 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003139 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003140 found = true;
3141 break;
3142 }
3143 }
3144 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003145 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003146 // remove all effects from the chain
3147 while (ec->mEffects.size()) {
3148 sp<EffectModule> effect = ec->mEffects[0];
3149 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003150 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003151 if (effect->purgeHandles()) {
Eric Laurent5d885392019-12-13 10:56:31 -08003152 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003153 }
Eric Laurent6c796322019-04-09 14:13:17 -07003154 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003155 }
3156 }
3157 }
Eric Laurent6c796322019-04-09 14:13:17 -07003158 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003159}
3160
Andy Hungdc099c22018-09-18 13:46:39 -07003161// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3162void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3163{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303164 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3165 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003166 const int fd = fdToString.fd();
3167 if (fd >= 0) {
3168 thread->dump(fd, {} /* args */);
3169 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3170 }
3171}
3172
Glenn Kasteneeecb982016-02-26 10:44:04 -08003173// checkThread_l() must be called with AudioFlinger::mLock held
3174AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3175{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003176 ThreadBase *thread = checkMmapThread_l(ioHandle);
3177 if (thread == 0) {
3178 switch (audio_unique_id_get_use(ioHandle)) {
3179 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3180 thread = checkPlaybackThread_l(ioHandle);
3181 break;
3182 case AUDIO_UNIQUE_ID_USE_INPUT:
3183 thread = checkRecordThread_l(ioHandle);
3184 break;
3185 default:
3186 break;
3187 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003188 }
3189 return thread;
3190}
3191
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003193AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194{
Glenn Kastena1117922012-01-26 10:53:32 -08003195 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196}
3197
3198// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003199AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200{
3201 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003202 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203}
3204
3205// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003206AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207{
Glenn Kastena1117922012-01-26 10:53:32 -08003208 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209}
3210
Eric Laurent6acd1d42017-01-04 14:23:29 -08003211// checkMmapThread_l() must be called with AudioFlinger::mLock held
3212AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3213{
3214 return mMmapThreads.valueFor(io).get();
3215}
3216
3217
3218// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3219AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3220{
Eric Laurent7459b902017-04-19 18:10:41 -07003221 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003222 if (volumeInterface == nullptr) {
3223 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3224 if (mmapThread != nullptr) {
3225 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003226 MmapPlaybackThread *mmapPlaybackThread =
3227 static_cast<MmapPlaybackThread *>(mmapThread);
3228 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003229 }
3230 }
3231 }
3232 return volumeInterface;
3233}
3234
3235Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3236{
3237 Vector <VolumeInterface *> volumeInterfaces;
3238 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003239 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003240 }
3241 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3242 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003243 MmapPlaybackThread *mmapPlaybackThread =
3244 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3245 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003246 }
3247 }
3248 return volumeInterfaces;
3249}
3250
Glenn Kasteneeecb982016-02-26 10:44:04 -08003251audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252{
Glenn Kasten9d003132016-04-06 14:38:09 -07003253 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003254 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003255 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3256 for (int retry = 0; retry < maxRetries; retry++) {
3257 // The cast allows wraparound from max positive to min negative instead of abort
3258 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3259 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3260 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3261 // allow wrap by skipping 0 and -1 for session ids
3262 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3263 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3264 return (audio_unique_id_t) (base | use);
3265 }
3266 }
3267 // We have no way of recovering from wraparound
3268 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3269 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270}
3271
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003272AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003273{
Eric Laurent488d5002020-05-14 09:13:30 -07003274 AutoMutex lock(mHardwareLock);
3275 if (mPrimaryHardwareDev == nullptr) {
3276 return nullptr;
3277 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003278 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3279 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003280 if(thread->isDuplicating()) {
3281 continue;
3282 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003283 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003284 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003285 return thread;
3286 }
3287 }
Eric Laurent488d5002020-05-14 09:13:30 -07003288 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003289}
3290
jiabin10d86fd2019-10-31 17:20:42 -07003291DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003292{
3293 PlaybackThread *thread = primaryPlaybackThread_l();
3294
3295 if (thread == NULL) {
jiabin10d86fd2019-10-31 17:20:42 -07003296 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003297 }
3298
jiabin10d86fd2019-10-31 17:20:42 -07003299 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003300}
3301
Glenn Kastena7335632016-06-09 17:09:53 -07003302AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3303{
3304 size_t minFrameCount = 0;
3305 PlaybackThread *minThread = NULL;
3306 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3307 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3308 if (!thread->isDuplicating()) {
3309 size_t frameCount = thread->frameCountHAL();
3310 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3311 (frameCount == minFrameCount && thread->hasFastMixer() &&
3312 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3313 minFrameCount = frameCount;
3314 minThread = thread;
3315 }
3316 }
3317 }
3318 return minThread;
3319}
3320
Eric Laurenta011e352012-03-29 15:51:43 -07003321sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003322 audio_session_t triggerSession,
3323 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003324 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003325 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003326{
3327 Mutex::Autolock _l(mLock);
3328
3329 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3330 status_t playStatus = NAME_NOT_FOUND;
3331 status_t recStatus = NAME_NOT_FOUND;
3332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3333 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3334 if (playStatus == NO_ERROR) {
3335 return event;
3336 }
3337 }
3338 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3339 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3340 if (recStatus == NO_ERROR) {
3341 return event;
3342 }
3343 }
3344 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3345 mPendingSyncEvents.add(event);
3346 } else {
3347 ALOGV("createSyncEvent() invalid event %d", event->type());
3348 event.clear();
3349 }
3350 return event;
3351}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003352
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353// ----------------------------------------------------------------------------
3354// Effect management
3355// ----------------------------------------------------------------------------
3356
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003357sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3358 return mEffectsFactoryHal;
3359}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360
Glenn Kastenf587ba52012-01-26 16:25:10 -08003361status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362{
3363 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003364 if (mEffectsFactoryHal.get()) {
3365 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3366 } else {
3367 return -ENODEV;
3368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369}
3370
Glenn Kastenf587ba52012-01-26 16:25:10 -08003371status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372{
3373 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003374 if (mEffectsFactoryHal.get()) {
3375 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3376 } else {
3377 return -ENODEV;
3378 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379}
3380
Glenn Kasten5e92a782012-01-30 07:40:52 -08003381status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003382 const effect_uuid_t *pTypeUuid,
3383 uint32_t preferredTypeFlag,
3384 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003386 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3387 return BAD_VALUE;
3388 }
3389
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003391
3392 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003393 return -ENODEV;
3394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003396 status_t status = NO_ERROR;
3397 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3398 // If uuid is specified, request effect descriptor from that.
3399 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3400 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3401 // If uuid is not specified, look for an available implementation
3402 // of the required type instead.
3403
3404 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3405 effect_descriptor_t desc;
3406 desc.flags = 0; // prevent compiler warning
3407
3408 uint32_t numEffects = 0;
3409 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3410 if (status < 0) {
3411 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3412 return status;
3413 }
3414
3415 bool found = false;
3416 for (uint32_t i = 0; i < numEffects; i++) {
3417 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3418 if (status < 0) {
3419 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3420 continue;
3421 }
3422 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3423 // If matching type found save effect descriptor.
3424 found = true;
3425 *descriptor = desc;
3426
3427 // If there's no preferred flag or this descriptor matches the preferred
3428 // flag, success! If this descriptor doesn't match the preferred
3429 // flag, continue enumeration in case a better matching version of this
3430 // effect type is available. Note that this means if no effect with a
3431 // correct flag is found, the descriptor returned will correspond to the
3432 // last effect that at least had a matching type uuid (if any).
3433 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3434 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3435 break;
3436 }
3437 }
3438 }
3439
3440 if (!found) {
3441 status = NAME_NOT_FOUND;
3442 ALOGW("getEffectDescriptor(): Effect not found by type.");
3443 }
3444 } else {
3445 status = BAD_VALUE;
3446 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3447 }
3448 return status;
3449}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450
Glenn Kasten8d6cc842012-02-03 11:06:53 -08003451sp<IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 effect_descriptor_t *pDesc,
3453 const sp<IEffectClient>& effectClient,
3454 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003455 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003456 audio_session_t sessionId,
Eric Laurent9b2064c2019-11-22 17:25:04 -08003457 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003458 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003459 pid_t pid,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003460 bool probe,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 status_t *status,
3462 int *id,
3463 int *enabled)
3464{
3465 status_t lStatus = NO_ERROR;
3466 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468
Eric Laurentb6436272016-12-07 19:24:50 -08003469 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003470 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003471 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3472 ALOGW_IF(pid != -1 && pid != callingPid,
3473 "%s uid %d pid %d tried to pass itself off as pid %d",
3474 __func__, callingUid, callingPid, pid);
3475 pid = callingPid;
3476 }
3477
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003478 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3479 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480
3481 if (pDesc == NULL) {
3482 lStatus = BAD_VALUE;
3483 goto Exit;
3484 }
3485
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003486 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003487 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003488 lStatus = NO_INIT;
3489 goto Exit;
3490 }
3491
Andy Hung6096dcd2019-03-13 13:20:30 -07003492 // check audio settings permission for global effects
3493 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3494 if (!settingsAllowed()) {
3495 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3496 lStatus = PERMISSION_DENIED;
3497 goto Exit;
3498 }
3499 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3500 if (!isAudioServerUid(callingUid)) {
3501 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3502 lStatus = PERMISSION_DENIED;
3503 goto Exit;
3504 }
3505
3506 if (io == AUDIO_IO_HANDLE_NONE) {
3507 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3508 lStatus = BAD_VALUE;
3509 goto Exit;
3510 }
Eric Laurenta20c4e92019-11-12 15:55:51 -08003511 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3512 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3513 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3514 lStatus = PERMISSION_DENIED;
3515 goto Exit;
3516 }
Eric Laurentfefebb52019-11-13 12:45:28 -08003517 if (io != AUDIO_IO_HANDLE_NONE) {
3518 ALOGE("%s: io handle should not be specified for device effect", __func__);
3519 lStatus = BAD_VALUE;
3520 goto Exit;
3521 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003522 } else {
3523 // general sessionId.
3524
3525 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3526 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3527 lStatus = BAD_VALUE;
3528 goto Exit;
3529 }
3530
3531 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3532 // to prevent creating an effect when one doesn't actually have track with that session?
3533 }
3534
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003536 // Get the full effect descriptor from the uuid/type.
3537 // If the session is the output mix, prefer an auxiliary effect,
3538 // otherwise no preference.
3539 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3540 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3541 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3542 if (lStatus < 0) {
3543 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3544 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 }
3546
3547 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003548 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3550 lStatus = INVALID_OPERATION;
3551 goto Exit;
3552 }
3553
Eric Laurent59255e42011-07-27 19:49:51 -07003554 // check recording permission for visualizer
3555 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003556 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurenta20c4e92019-11-12 15:55:51 -08003557 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003558 lStatus = PERMISSION_DENIED;
3559 goto Exit;
3560 }
3561
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003563 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003564 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003565 // if the output returned by getOutputForEffect() is removed before we lock the
3566 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3567 // and we will exit safely
3568 io = AudioSystem::getOutputForEffect(&desc);
3569 ALOGV("createEffect got output %d", io);
3570 }
3571
3572 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573
Eric Laurent9b2064c2019-11-22 17:25:04 -08003574 if (sessionId == AUDIO_SESSION_DEVICE) {
3575 sp<Client> client = registerPid(pid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003576 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurent9b2064c2019-11-22 17:25:04 -08003577 handle = mDeviceEffectManager.createEffect_l(
3578 &desc, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003579 enabled, &lStatus, probe);
Eric Laurent9b2064c2019-11-22 17:25:04 -08003580 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3581 // remove local strong reference to Client with mClientLock held
3582 Mutex::Autolock _cl(mClientLock);
3583 client.clear();
3584 } else {
3585 // handle must be valid here, but check again to be safe.
3586 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3587 }
3588 goto Register;
3589 }
3590
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 // If output is not specified try to find a matching audio session ID in one of the
3592 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003593 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3594 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003595 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3596 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003597 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003598 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003599 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3600 if (io == AUDIO_IO_HANDLE_NONE) {
3601 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003603 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003604 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003605 }
Andy Hung444bb552019-03-14 17:06:39 -07003606
3607 // If you wish to create a Record preprocessing AudioEffect in Java,
3608 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3609 // Otherwise it will fail when created on a Playback thread by legacy
3610 // handling below. Ditto with Mmap, the associated Mmap track must be created
3611 // before creating the AudioEffect or the io handle must be specified.
3612 //
3613 // Detect if the effect is created after an AudioRecord is destroyed.
3614 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3615 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3616 " for session %d no longer exists",
3617 __func__, desc.name, sessionId);
3618 lStatus = PERMISSION_DENIED;
3619 goto Exit;
3620 }
3621
3622 // Legacy handling of creating an effect on an expired or made-up
3623 // session id. We think that it is a Playback effect.
3624 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003625 // If no output thread contains the requested session ID, default to
3626 // first output. The effect chain will be moved to the correct output
3627 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003628 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003629 io = mPlaybackThreads.keyAt(0);
3630 }
Steve Block3856b092011-10-20 11:56:00 +01003631 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003632 } else if (checkPlaybackThread_l(io) != nullptr) {
3633 // allow only one effect chain per sessionId on mPlaybackThreads.
3634 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3635 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
3636 if (io == checkIo) continue;
3637 const uint32_t sessionType =
3638 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3639 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3640 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3641 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3642 android_errorWriteLog(0x534e4554, "123237974");
3643 lStatus = BAD_VALUE;
3644 goto Exit;
3645 }
3646 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003647 }
3648 ThreadBase *thread = checkRecordThread_l(io);
3649 if (thread == NULL) {
3650 thread = checkPlaybackThread_l(io);
3651 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003652 thread = checkMmapThread_l(io);
3653 if (thread == NULL) {
3654 ALOGE("createEffect() unknown output thread");
3655 lStatus = BAD_VALUE;
3656 goto Exit;
3657 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003658 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003659 } else {
3660 // Check if one effect chain was awaiting for an effect to be created on this
3661 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003662 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003663 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003664 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003665 thread->addEffectChain_l(chain);
3666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003668
Eric Laurent021cf962014-05-13 10:18:14 -07003669 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003670
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003671 // create effect on selected output thread
Eric Laurenta20c4e92019-11-12 15:55:51 -08003672 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003673 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003674 &desc, enabled, &lStatus, pinned, probe);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003675 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003676 // remove local strong reference to Client with mClientLock held
3677 Mutex::Autolock _cl(mClientLock);
3678 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003679 } else {
3680 // handle must be valid here, but check again to be safe.
3681 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003682 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 }
3684
Eric Laurent9b2064c2019-11-22 17:25:04 -08003685Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003686 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003687 // Check CPU and memory usage
Eric Laurente0b9a362019-12-16 19:34:05 -08003688 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003689 if (effect != nullptr) {
3690 status_t rStatus = effect->updatePolicyState();
3691 if (rStatus != NO_ERROR) {
3692 lStatus = rStatus;
3693 }
3694 }
3695 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003696 handle.clear();
3697 }
3698
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003700 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701 return handle;
3702}
3703
Glenn Kastend848eb42016-03-08 13:42:11 -08003704status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003705 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003706{
Steve Block3856b092011-10-20 11:56:00 +01003707 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003708 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003709 Mutex::Autolock _l(mLock);
3710 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003711 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003712 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 }
Eric Laurentde070132010-07-13 04:45:46 -07003714 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3715 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003716 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003717 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 }
Eric Laurentde070132010-07-13 04:45:46 -07003719 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3720 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003721 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003722 return BAD_VALUE;
3723 }
3724
3725 Mutex::Autolock _dl(dstThread->mLock);
3726 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003727 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728}
3729
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003730
3731void AudioFlinger::setEffectSuspended(int effectId,
3732 audio_session_t sessionId,
3733 bool suspended)
3734{
3735 Mutex::Autolock _l(mLock);
3736
3737 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3738 if (thread == nullptr) {
3739 return;
3740 }
3741 Mutex::Autolock _sl(thread->mLock);
3742 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3743 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3744}
3745
3746
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003747// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003748status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003749 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003750 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003751{
Steve Block3856b092011-10-20 11:56:00 +01003752 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003753 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003754
Eric Laurent59255e42011-07-27 19:49:51 -07003755 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003756 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003757 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003758 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003759 return INVALID_OPERATION;
3760 }
3761
Eric Laurent4c415062016-06-17 16:14:16 -07003762 // Check whether the destination thread and all effects in the chain are compatible
3763 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003764 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003765 " destination thread %p is not compatible with effects in the chain",
3766 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003767 return INVALID_OPERATION;
3768 }
3769
Eric Laurent39e94f82010-07-28 01:32:47 -07003770 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003771 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003772 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003773 // removed.
3774 srcThread->removeEffectChain_l(chain);
3775
3776 // transfer all effects one by one so that new effect chain is created on new thread with
3777 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003778 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003779 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003780 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003781 Vector< sp<EffectModule> > removed;
3782 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003783 while (effect != 0) {
3784 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003785 removed.add(effect);
3786 status = dstThread->addEffect_l(effect);
3787 if (status != NO_ERROR) {
3788 break;
3789 }
Eric Laurentec35a142011-10-05 17:42:25 -07003790 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3791 if (effect->state() == EffectModule::ACTIVE ||
3792 effect->state() == EffectModule::STOPPING) {
3793 effect->start();
3794 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003795 // if the move request is not received from audio policy manager, the effect must be
3796 // re-registered with the new strategy and output
3797 if (dstChain == 0) {
Eric Laurent5d885392019-12-13 10:56:31 -08003798 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003799 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003800 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003801 status = NO_INIT;
3802 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003803 }
3804 strategy = dstChain->strategy();
3805 }
Eric Laurentde070132010-07-13 04:45:46 -07003806 effect = chain->getEffectFromId_l(0);
3807 }
3808
Eric Laurent5baf2af2013-09-12 17:37:00 -07003809 if (status != NO_ERROR) {
3810 for (size_t i = 0; i < removed.size(); i++) {
3811 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003812 }
3813 }
3814
3815 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816}
3817
Eric Laurent6c796322019-04-09 14:13:17 -07003818status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3819 const sp<PlaybackThread>& dstThread,
3820 sp<PlaybackThread> *srcThread)
3821{
3822 status_t status = NO_ERROR;
3823 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003824 sp<PlaybackThread> thread =
3825 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003826
3827 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3828 Mutex::Autolock _dl(dstThread->mLock);
3829 Mutex::Autolock _sl(thread->mLock);
3830 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3831 sp<EffectChain> dstChain;
3832 if (srcChain == 0) {
3833 return INVALID_OPERATION;
3834 }
3835
3836 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3837 if (effect == 0) {
3838 return INVALID_OPERATION;
3839 }
3840 thread->removeEffect_l(effect);
3841 status = dstThread->addEffect_l(effect);
3842 if (status != NO_ERROR) {
3843 thread->addEffect_l(effect);
3844 status = INVALID_OPERATION;
3845 goto Exit;
3846 }
3847
Eric Laurent5d885392019-12-13 10:56:31 -08003848 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003849 if (dstChain == 0) {
3850 thread->addEffect_l(effect);
3851 status = INVALID_OPERATION;
3852 }
3853
3854Exit:
3855 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3856 if (effect->state() == EffectModule::ACTIVE ||
3857 effect->state() == EffectModule::STOPPING) {
3858 effect->start();
3859 }
3860 }
3861
3862 if (status == NO_ERROR && srcThread != nullptr) {
3863 *srcThread = thread;
3864 }
3865 return status;
3866}
3867
Eric Laurent5baf2af2013-09-12 17:37:00 -07003868bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003869{
3870 if (mGlobalEffectEnableTime != 0 &&
3871 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3872 return true;
3873 }
3874
3875 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3876 sp<EffectChain> ec =
3877 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003878 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003879 return true;
3880 }
3881 }
3882 return false;
3883}
3884
Eric Laurent5baf2af2013-09-12 17:37:00 -07003885void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003886{
3887 Mutex::Autolock _l(mLock);
3888
3889 mGlobalEffectEnableTime = systemTime();
3890
3891 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3892 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3893 if (t->mType == ThreadBase::OFFLOAD) {
3894 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3895 }
3896 }
3897
3898}
3899
Eric Laurentaaa44472014-09-12 17:41:50 -07003900status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3901{
Eric Laurentd8365c52017-07-16 15:27:05 -07003902 // clear possible suspended state before parking the chain so that it starts in default state
3903 // when attached to a new record thread
3904 chain->setEffectSuspended_l(FX_IID_AEC, false);
3905 chain->setEffectSuspended_l(FX_IID_NS, false);
3906
Glenn Kastend848eb42016-03-08 13:42:11 -08003907 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003908 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003909 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003910 if (index >= 0) {
3911 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3912 return ALREADY_EXISTS;
3913 }
3914 mOrphanEffectChains.add(session, chain);
3915 return NO_ERROR;
3916}
3917
3918sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3919{
3920 sp<EffectChain> chain;
3921 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003922 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003923 if (index >= 0) {
3924 chain = mOrphanEffectChains.valueAt(index);
3925 mOrphanEffectChains.removeItemsAt(index);
3926 }
3927 return chain;
3928}
3929
3930bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3931{
3932 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003933 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003934 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003935 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003936 if (index >= 0) {
3937 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003938 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003939 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003940 mOrphanEffectChains.removeItemsAt(index);
3941 }
3942 return true;
3943 }
3944 return false;
3945}
3946
3947
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948// ----------------------------------------------------------------------------
3949
3950status_t AudioFlinger::onTransact(
3951 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3952{
3953 return BnAudioFlinger::onTransact(code, data, reply, flags);
3954}
3955
Glenn Kasten63238ef2015-03-02 15:50:29 -08003956} // namespace android