blob: bc8609f4a50156381dea2f2396c1fe350c48045d [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
jiabina392a552019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -080025#define VALUE_OR_FATAL(result) \
26 ({ \
27 auto _tmp = (result); \
28 LOG_ALWAYS_FATAL_IF(!_tmp.ok(), \
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070029 "Failed result (%d)", \
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -080030 _tmp.error()); \
31 std::move(_tmp.value()); \
32 })
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070033
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -080034#define VALUE_OR_EXIT(expr) \
35 ({ \
36 auto _tmp = (expr); \
37 if (!_tmp.ok()) { \
38 return _tmp.error(); \
39 } \
40 std::move(_tmp.value()); \
41 })
42
Glenn Kasten153b9fe2013-07-15 11:23:36 -070043#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080044#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <math.h>
46#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070047#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include <sys/time.h>
49#include <sys/resource.h>
Mikhail Naganov88b30d22020-03-09 19:43:13 +000050#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051
jiabin57303cc2018-12-18 15:45:57 -080052#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080053#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <binder/IServiceManager.h>
55#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070056#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070058#include <media/audiohal/DeviceHalInterface.h>
59#include <media/audiohal/DevicesFactoryHalInterface.h>
60#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070061#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080062#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070063#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070064#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070065#include <utils/String16.h>
66#include <utils/threads.h>
67
Steven Morelandf0c02ce2018-02-23 14:53:55 -080068#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070069#include <cutils/properties.h>
70
Dima Zavin64760242011-05-11 14:15:23 -070071#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070072#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070073
Mathias Agopian65ab4712010-07-14 17:59:35 -070074#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070075#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
Andy Hung6770c6f2015-04-07 13:43:36 -070077#include <media/AudioResamplerPublic.h>
78
Mikhail Naganov9fe94012016-10-14 14:57:40 -070079#include <system/audio_effects/effect_visualizer.h>
80#include <system/audio_effects/effect_ns.h>
81#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070082#include <system/audio_effects/effect_hapticgenerator.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070083
Glenn Kasten3b21c502011-12-15 09:52:39 -080084#include <audio_utils/primitives.h>
85
Eric Laurentfeb0db62011-07-22 09:04:31 -070086#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080087
Glenn Kasten9e58b552013-01-18 15:09:48 -080088#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070089#include <media/AidlConversion.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080090#include <media/nbaio/Pipe.h>
91#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080092#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070093#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070094#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070095#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070096#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080097
rago3bd1c872016-09-26 12:58:14 -070098//#define BUFLOG_NDEBUG 0
99#include <BufLog.h>
100
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101#include "TypedLogger.h"
102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
John Grossman1c345192012-03-27 14:00:17 -0700105// Note: the following macro is used for extremely verbose logging message. In
106// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
107// 0; but one side effect of this is to turn all LOGV's as well. Some messages
108// are so verbose that we want to suppress them even when we have ALOG_ASSERT
109// turned on. Do not uncomment the #def below unless you really know what you
110// are doing and want to see all of the extremely verbose messages.
111//#define VERY_VERY_VERBOSE_LOGGING
112#ifdef VERY_VERY_VERBOSE_LOGGING
113#define ALOGVV ALOGV
114#else
115#define ALOGVV(a...) do { } while(0)
116#endif
Eric Laurentde070132010-07-13 04:45:46 -0700117
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118namespace android {
119
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700120using media::IEffectClient;
121
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800122static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
123static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700124static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700125static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700126
Glenn Kasten58912562012-04-03 10:45:00 -0700127
John Grossman4ff14ba2012-02-08 16:37:41 -0800128nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800129
Eric Laurent81784c32012-11-19 14:55:58 -0800130uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700131
Eric Laurent813e2a72013-08-31 12:59:48 -0700132// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
133// we define a minimum time during which a global effect is considered enabled.
134static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
135
Eric Laurentfc235202016-12-20 18:48:17 -0800136Mutex gLock;
137wp<AudioFlinger> gAudioFlinger;
138
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700139// Keep a strong reference to media.log service around forever.
140// The service is within our parent process so it can never die in a way that we could observe.
141// These two variables are const after initialization.
142static sp<IBinder> sMediaLogServiceAsBinder;
143static sp<IMediaLogService> sMediaLogService;
144
145static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
146
147static void sMediaLogInit()
148{
149 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
150 if (sMediaLogServiceAsBinder != 0) {
151 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
152 }
153}
154
jiabin57303cc2018-12-18 15:45:57 -0800155// Keep a strong reference to external vibrator service
156static sp<os::IExternalVibratorService> sExternalVibratorService;
157
158static sp<os::IExternalVibratorService> getExternalVibratorService() {
159 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700160 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800161 String16("external_vibrator_service"));
162 if (binder != 0) {
163 sExternalVibratorService =
164 interface_cast<os::IExternalVibratorService>(binder);
165 }
166 }
167 return sExternalVibratorService;
168}
169
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000170class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
171 public:
172 void onNewDevicesAvailable() override {
173 // Start a detached thread to execute notification in parallel.
174 // This is done to prevent mutual blocking of audio_flinger and
175 // audio_policy services during system initialization.
176 std::thread notifier([]() {
177 AudioSystem::onNewAudioModulesAvailable();
178 });
179 notifier.detach();
180 }
181};
182
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183// ----------------------------------------------------------------------------
184
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700185std::string formatToString(audio_format_t format) {
186 std::string result;
187 FormatConverter::toString(format, result);
188 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800189}
190
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191// ----------------------------------------------------------------------------
192
193AudioFlinger::AudioFlinger()
194 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800195 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800196 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800197 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700198 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800199 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800200 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700201 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800202 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700203 mBtNrecIsOff(false),
204 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700205 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800206 mTotalMemory(0),
207 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700208 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700209 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800210 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700211 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700213 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
214 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
215 // zero ID has a special meaning, so unavailable
216 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
217 }
218
Eric Laurent94ca1142020-10-07 10:45:20 -0700219#if 1
220 // FIXME See bug 165702394 and bug 168511485
221 const bool doLog = false;
222#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800223 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700224#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800225 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800226 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
227 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700228 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800229 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700230
Wei Jia3f273d12015-11-24 09:06:49 -0800231 // reset battery stats.
232 // if the audio service has crashed, battery stats could be left
233 // in bad state, reset the state upon service start.
234 BatteryNotifier::getInstance().noteResetAudio();
235
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700236 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700237 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
238
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800239 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700240 std::vector<pid_t> halPids;
241 mDevicesFactoryHal->getHalPids(&halPids);
242 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800243
244 // Notify that we have started (also called when audioserver service restarts)
245 mediametrics::LogItem(mMetricsId)
246 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
247 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700248}
249
250void AudioFlinger::onFirstRef()
251{
Eric Laurent93575202011-01-18 18:39:02 -0800252 Mutex::Autolock _l(mLock);
253
Dima Zavin799a70e2011-04-18 16:57:27 -0700254 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800255 char val_str[PROPERTY_VALUE_MAX] = { 0 };
256 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
257 uint32_t int_val;
258 if (1 == sscanf(val_str, "%u", &int_val)) {
259 mStandbyTimeInNsecs = milliseconds(int_val);
260 ALOGI("Using %u mSec as standby time.", int_val);
261 } else {
262 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
263 ALOGI("Using default %u mSec as standby time.",
264 (uint32_t)(mStandbyTimeInNsecs / 1000000));
265 }
266 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267
Eric Laurenta4c5a552012-03-29 10:12:40 -0700268 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800269
270 gAudioFlinger = this;
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000271
272 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
273 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274}
275
Eric Laurent42896a02019-09-27 15:40:33 -0700276status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
277 TimeCheck::setAudioHalPids(pids);
278 return NO_ERROR;
279}
280
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281AudioFlinger::~AudioFlinger()
282{
283 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700284 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700285 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700286 }
287 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700288 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700289 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700290 }
Andy Hungb4946b62019-03-14 11:19:28 -0700291 while (!mMmapThreads.isEmpty()) {
292 const audio_io_handle_t io = mMmapThreads.keyAt(0);
293 if (mMmapThreads.valueAt(0)->isOutput()) {
294 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
295 } else {
296 closeInput_nonvirtual(io); // removes entry from mMmapThreads
297 }
298 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700299
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800300 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
301 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700304
305 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700306 if (sMediaLogService != 0) {
307 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
308 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
309 mUnregisteredWriters.pop();
310 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700311 }
312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313}
314
Eric Laurentfc235202016-12-20 18:48:17 -0800315//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800316__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800317status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
318 const audio_attributes_t *attr,
319 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700320 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800321 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800322 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800323 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700324 sp<MmapStreamInterface>& interface,
325 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800326{
327 sp<AudioFlinger> af;
328 {
329 Mutex::Autolock _l(gLock);
330 af = gAudioFlinger.promote();
331 }
332 status_t ret = NO_INIT;
333 if (af != 0) {
334 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800335 direction, attr, config, client, deviceId,
336 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800337 }
338 return ret;
339}
340
Eric Laurent6acd1d42017-01-04 14:23:29 -0800341status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
342 const audio_attributes_t *attr,
343 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700344 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800345 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800346 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800347 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700348 sp<MmapStreamInterface>& interface,
349 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800350{
351 status_t ret = initCheck();
352 if (ret != NO_ERROR) {
353 return ret;
354 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800355 audio_session_t actualSessionId = *sessionId;
356 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
357 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
358 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800359 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700360 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800361 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700362 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800363 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
364 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
365 fullConfig.sample_rate = config->sample_rate;
366 fullConfig.channel_mask = config->channel_mask;
367 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800368 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700369
370 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800371 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200372 &streamType, client.clientPid, client.clientUid,
Ricardo Correa57a37692020-03-23 17:27:25 -0700373 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800374 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
375 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800376 deviceId, &portId, &secondaryOutputs);
377 ALOGW_IF(!secondaryOutputs.empty(),
378 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800379 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700380 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700381 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800382 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800383 client.clientPid,
384 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800385 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800386 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700387 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800388 }
389 if (ret != NO_ERROR) {
390 return ret;
391 }
392
393 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
394 // audio policy manager and we can retrieve it
395 sp<MmapThread> thread = mMmapThreads.valueFor(io);
396 if (thread != 0) {
397 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700398 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700399 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800400 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800401 config->sample_rate = thread->sampleRate();
402 config->channel_mask = thread->channelMask();
403 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800404 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700405 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700406 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700407 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800408 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700409 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800410 ret = NO_INIT;
411 }
412
413 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
414
Eric Laurentfc235202016-12-20 18:48:17 -0800415 return ret;
416}
417
jiabin57303cc2018-12-18 15:45:57 -0800418/* static */
419int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
420 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
421 if (evs != 0) {
422 int32_t ret;
423 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
424 if (status.isOk()) {
425 return ret;
426 }
427 }
jiabine70bc7f2020-06-30 22:07:55 -0700428 return static_cast<int>(os::HapticScale::MUTE);
jiabin57303cc2018-12-18 15:45:57 -0800429}
430
431/* static */
432void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
433 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
434 if (evs != 0) {
435 evs->onExternalVibrationStop(*externalVibration);
436 }
437}
438
Eric Laurentb82e6b72019-11-22 17:25:04 -0800439status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
440 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700441 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800442 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
443 if (audioHwDevice == nullptr) {
444 return NO_INIT;
445 }
446 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
447}
448
449status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
450 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700451 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800452 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
453 if (audioHwDevice == nullptr) {
454 return NO_INIT;
455 }
456 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
457}
458
Eric Laurenta4c5a552012-03-29 10:12:40 -0700459static const char * const audio_interfaces[] = {
460 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
461 AUDIO_HARDWARE_MODULE_ID_A2DP,
462 AUDIO_HARDWARE_MODULE_ID_USB,
463};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700464
Phil Burk062e67a2015-02-11 13:40:50 -0800465AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700466 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700467 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700468{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700469 // if module is 0, the request comes from an old policy manager and we should load
470 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700471 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700472 if (module == 0) {
473 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700474 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700475 loadHwModule_l(audio_interfaces[i]);
476 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700477 // then try to find a module supporting the requested device.
478 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
479 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700480 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
481 uint32_t supportedDevices;
482 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700483 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700484 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700485 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700486 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700487 } else {
488 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700489 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
490 if (audioHwDevice != NULL) {
491 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700492 }
493 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700494
Dima Zavin799a70e2011-04-18 16:57:27 -0700495 return NULL;
496}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497
Glenn Kasten0f11b512014-01-31 16:18:54 -0800498void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 String8 result;
501
502 result.append("Clients:\n");
503 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800504 sp<Client> client = mClients.valueAt(i).promote();
505 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800506 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 }
508 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700509
Eric Laurentd1b28d42013-09-18 18:47:13 -0700510 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800511 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700512 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800513 const pid_t pid = mNotificationClients[i]->getPid();
514 const uid_t uid = mNotificationClients[i]->getUid();
515 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
516 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700517 }
518
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700519 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800520 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700521 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
522 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800523 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
524 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
525 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528}
529
530
Glenn Kasten0f11b512014-01-31 16:18:54 -0800531void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532{
533 const size_t SIZE = 256;
534 char buffer[SIZE];
535 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800536 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700537
John Grossman4ff14ba2012-02-08 16:37:41 -0800538 snprintf(buffer, SIZE, "Hardware status: %d\n"
539 "Standby Time mSec: %u\n",
540 hardwareStatus,
541 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 result.append(buffer);
543 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544}
545
Glenn Kasten0f11b512014-01-31 16:18:54 -0800546void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 const size_t SIZE = 256;
549 char buffer[SIZE];
550 String8 result;
551 snprintf(buffer, SIZE, "Permission Denial: "
552 "can't dump AudioFlinger from pid=%d, uid=%d\n",
553 IPCThreadState::self()->getCallingPid(),
554 IPCThreadState::self()->getCallingUid());
555 result.append(buffer);
556 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557}
558
Eric Laurent81784c32012-11-19 14:55:58 -0800559bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700561 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
562 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563}
564
565status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
566{
Glenn Kasten44deb052012-02-05 18:09:08 -0800567 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 dumpPermissionDenial(fd, args);
569 } else {
570 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800571 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572 if (!hardwareLocked) {
573 String8 result(kHardwareLockedString);
574 write(fd, result.string(), result.size());
575 } else {
576 mHardwareLock.unlock();
577 }
578
Eric Tan7b651152018-07-13 10:17:19 -0700579 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580
581 // failed to lock - AudioFlinger is probably deadlocked
582 if (!locked) {
583 String8 result(kDeadlockedString);
584 write(fd, result.string(), result.size());
585 }
586
Eric Laurent021cf962014-05-13 10:18:14 -0700587 bool clientLocked = dumpTryLock(mClientLock);
588 if (!clientLocked) {
589 String8 result(kClientLockedString);
590 write(fd, result.string(), result.size());
591 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700592
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700593 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700594 mEffectsFactoryHal->dumpEffects(fd);
595 } else {
596 String8 result(kNoEffectsFactory);
597 write(fd, result.string(), result.size());
598 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700601 if (clientLocked) {
602 mClientLock.unlock();
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 dumpInternals(fd, args);
606
607 // dump playback threads
608 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
609 mPlaybackThreads.valueAt(i)->dump(fd, args);
610 }
611
612 // dump record threads
613 for (size_t i = 0; i < mRecordThreads.size(); i++) {
614 mRecordThreads.valueAt(i)->dump(fd, args);
615 }
616
Eric Laurent6acd1d42017-01-04 14:23:29 -0800617 // dump mmap threads
618 for (size_t i = 0; i < mMmapThreads.size(); i++) {
619 mMmapThreads.valueAt(i)->dump(fd, args);
620 }
621
Eric Laurentaaa44472014-09-12 17:41:50 -0700622 // dump orphan effect chains
623 if (mOrphanEffectChains.size() != 0) {
624 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
625 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
626 mOrphanEffectChains.valueAt(i)->dump(fd, args);
627 }
628 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700629 // dump all hardware devs
630 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700631 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
632 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700634
Mikhail Naganov201369b2018-05-16 16:52:32 -0700635 mPatchPanel.dump(fd);
636
Eric Laurentb82e6b72019-11-22 17:25:04 -0800637 mDeviceEffectManager.dump(fd);
638
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700639 // dump external setParameters
640 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
641 dprintf(fd, "\n%s setParameters:\n", name);
642 logger.dump(fd, " " /* prefix */);
643 };
644 dumpLogger(mRejectedSetParameterLog, "Rejected");
645 dumpLogger(mAppSetParameterLog, "App");
646 dumpLogger(mSystemSetParameterLog, "System");
647
Andy Hunga8115dc2018-08-24 15:51:59 -0700648 // dump historical threads in the last 10 seconds
649 const std::string threadLog = mThreadLog.dumpToString(
650 "Historical Thread Log ", 0 /* lines */,
651 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
652 write(fd, threadLog.c_str(), threadLog.size());
653
rago3bd1c872016-09-26 12:58:14 -0700654 BUFLOG_RESET;
655
Glenn Kastend65d73c2012-06-22 17:21:07 -0700656 if (locked) {
657 mLock.unlock();
658 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800659
Andy Hung8946a282018-04-19 20:04:56 -0700660#ifdef TEE_SINK
661 // NBAIO_Tee dump is safe to call outside of AF lock.
662 NBAIO_Tee::dumpAll(fd, "_DUMP");
663#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800664 // append a copy of media.log here by forwarding fd to it, but don't attempt
665 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700666 if (sMediaLogServiceAsBinder != 0) {
667 dprintf(fd, "\nmedia.log:\n");
668 Vector<String16> args;
669 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800670 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700671
672 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700673 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700674 bool unreachableMemory = false;
675 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700676 if (arg == String16("-m")) {
677 dumpMem = true;
678 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700679 unreachableMemory = true;
680 }
681 }
682
Andy Hung07b745e2016-05-23 16:21:07 -0700683 if (dumpMem) {
684 dprintf(fd, "\nDumping memory:\n");
685 std::string s = dumpMemoryAddresses(100 /* limit */);
686 write(fd, s.c_str(), s.size());
687 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700688 if (unreachableMemory) {
689 dprintf(fd, "\nDumping unreachable memory:\n");
690 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700691 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700692 write(fd, s.c_str(), s.size());
693 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 }
695 return NO_ERROR;
696}
697
Eric Laurent021cf962014-05-13 10:18:14 -0700698sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800699{
Eric Laurent021cf962014-05-13 10:18:14 -0700700 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800701 // If pid is already in the mClients wp<> map, then use that entry
702 // (for which promote() is always != 0), otherwise create a new entry and Client.
703 sp<Client> client = mClients.valueFor(pid).promote();
704 if (client == 0) {
705 client = new Client(this, pid);
706 mClients.add(pid, client);
707 }
708
709 return client;
710}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711
Glenn Kasten9e58b552013-01-18 15:09:48 -0800712sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
713{
Jiabin Huang60766082020-07-28 22:03:56 +0000714 // If there is no memory allocated for logs, return a no-op writer that does nothing.
715 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700716 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800717 return new NBLog::Writer();
718 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700719 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
720 // If allocation fails, consult the vector of previously unregistered writers
721 // and garbage-collect one or more them until an allocation succeeds
722 if (shared == 0) {
723 Mutex::Autolock _l(mUnregisteredWritersLock);
724 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
725 {
726 // Pick the oldest stale writer to garbage-collect
727 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
728 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700729 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700730 // Now the media.log remote reference to IMemory is gone. When our last local
731 // reference to IMemory also drops to zero at end of this block,
732 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
733 }
734 // Re-attempt the allocation
735 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
736 if (shared != 0) {
737 goto success;
738 }
739 }
740 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000741 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700742 return new NBLog::Writer();
743 }
744success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700745 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800746 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
747 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700748 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800749 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800750}
751
752void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
753{
Glenn Kasten685ef092013-02-04 08:15:34 -0800754 if (writer == 0) {
755 return;
756 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800757 sp<IMemory> iMemory(writer->getIMemory());
758 if (iMemory == 0) {
759 return;
760 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700761 // Rather than removing the writer immediately, append it to a queue of old writers to
762 // be garbage-collected later. This allows us to continue to view old logs for a while.
763 Mutex::Autolock _l(mUnregisteredWritersLock);
764 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800765}
766
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767// IAudioFlinger interface
768
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -0800769status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
770 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800772 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800773 CreateTrackInput input = VALUE_OR_EXIT(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800774 CreateTrackOutput output;
775
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776 sp<PlaybackThread::Track> track;
777 sp<TrackHandle> trackHandle;
778 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800780 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800781 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800782 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783
Eric Laurent21da6472017-11-09 16:29:26 -0800784 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700785 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800786 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700787 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
788 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700789 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700790
Andy Hung4ef19fa2018-05-15 19:35:29 -0700791 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800792 ALOGW_IF(clientUid != callingUid,
793 "%s uid %d tried to pass itself off as %d",
794 __FUNCTION__, callingUid, clientUid);
795 clientUid = callingUid;
796 updatePid = true;
797 }
798 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700799 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800800 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800801 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700802 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800803 __func__, callingUid, callingPid, clientPid);
804 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700805 }
806
Eric Laurent21da6472017-11-09 16:29:26 -0800807 audio_session_t sessionId = input.sessionId;
808 if (sessionId == AUDIO_SESSION_ALLOCATE) {
809 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800810 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
811 lStatus = BAD_VALUE;
812 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800813 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800814
Eric Laurent21da6472017-11-09 16:29:26 -0800815 output.sessionId = sessionId;
816 output.outputId = AUDIO_IO_HANDLE_NONE;
817 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700818 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Ricardo Correa57a37692020-03-23 17:27:25 -0700819 clientPid, clientUid, &input.config, input.flags,
820 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800821
822 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
823 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
824 goto Exit;
825 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800826 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
827 // but if someone uses binder directly they could bypass that and cause us to crash
828 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000829 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 lStatus = BAD_VALUE;
831 goto Exit;
832 }
833
Glenn Kasten53b5d092014-02-05 10:00:23 -0800834 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800835 if (!audio_is_output_channel(input.config.channel_mask)) {
836 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800837 lStatus = BAD_VALUE;
838 goto Exit;
839 }
840
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700841 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800842 if (!audio_is_valid_format(input.config.format)) {
843 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700844 lStatus = BAD_VALUE;
845 goto Exit;
846 }
847
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 {
849 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800850 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800852 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853 lStatus = BAD_VALUE;
854 goto Exit;
855 }
856
Eric Laurent21da6472017-11-09 16:29:26 -0800857 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858
Glenn Kastene848bd92014-03-13 15:00:32 -0700859 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800860 // check if an effect chain with the same session ID is present on another
861 // output thread and move it here.
862 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
863 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
864 if (mPlaybackThreads.keyAt(i) != output.outputId) {
865 uint32_t sessions = t->hasAudioSession(sessionId);
866 if (sessions & ThreadBase::EFFECT_SESSION) {
867 effectThread = t.get();
868 break;
Eric Laurentde070132010-07-13 04:45:46 -0700869 }
870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 }
Eric Laurent21da6472017-11-09 16:29:26 -0800872 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873
Eric Laurent21da6472017-11-09 16:29:26 -0800874 output.sampleRate = input.config.sample_rate;
875 output.frameCount = input.frameCount;
876 output.notificationFrameCount = input.notificationFrameCount;
877 output.flags = input.flags;
878
Eric Laurent42984412019-05-09 17:57:03 -0700879 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700880 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800881 &output.frameCount, &output.notificationFrameCount,
882 input.notificationsPerBuffer, input.speed,
883 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700884 callingPid, input.clientInfo.clientTid, clientUid,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000885 &lStatus, portId, input.audioTrackCallback,
886 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800887 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700888 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700889
Eric Laurent21da6472017-11-09 16:29:26 -0800890 output.afFrameCount = thread->frameCount();
891 output.afSampleRate = thread->sampleRate();
892 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800893 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800894
Kevin Rocard153f92d2018-12-18 18:33:28 -0800895 if (lStatus == NO_ERROR) {
896 // Connect secondary outputs. Failure on a secondary output must not imped the primary
897 // Any secondary output setup failure will lead to a desync between the AP and AF until
898 // the track is destroyed.
899 TeePatches teePatches;
900 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
901 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
902 if (secondaryThread == NULL) {
903 ALOGE("no playback thread found for secondary output %d", output.outputId);
904 continue;
905 }
906
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100907 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
908 / thread->sampleRate();
909 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
910 / secondaryThread->sampleRate();
911 // If the secondary output has just been opened, the first secondaryThread write
912 // will not block as it will fill the empty startup buffer of the HAL,
913 // so a second sink buffer needs to be ready for the immediate next blocking write.
914 // Additionally, have a margin of one main thread buffer as the scheduling jitter
915 // can reorder the writes (eg if thread A&B have the same write intervale,
916 // the scheduler could schedule AB...BA)
917 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
918 // Total secondary output buffer must be at least as the read frames plus
919 // the margin of a few buffers on both sides in case the
920 // threads scheduling has some jitter.
921 // That value should not impact latency as the secondary track is started before
922 // its buffer is full, see frameCountToBeReady.
923 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
924 // The frameCount should also not be smaller than the secondary thread min frame
925 // count
926 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
927 [&] { Mutex::Autolock _l(secondaryThread->mLock);
928 return secondaryThread->latency_l(); }(),
929 secondaryThread->mNormalFrameCount,
930 secondaryThread->mSampleRate,
931 output.sampleRate,
932 input.speed);
933 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800934
935 using namespace std::chrono_literals;
936 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
937 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
938 output.sampleRate,
939 inChannelMask,
940 input.config.format,
941 frameCount,
942 NULL /* buffer */,
943 (size_t)0 /* bufferSize */,
944 AUDIO_INPUT_FLAG_DIRECT,
945 0ns /* timeout */);
946 status_t status = patchRecord->initCheck();
947 if (status != NO_ERROR) {
948 ALOGE("Secondary output patchRecord init failed: %d", status);
949 continue;
950 }
Andy Hungae22b482019-05-09 15:38:55 -0700951
952 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
953 // for fast usage: thread has fast mixer, sample rate matches, etc.;
954 // for now, we exclude fast tracks by removing the Fast flag.
955 const audio_output_flags_t outputFlags =
956 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800957 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
958 streamType,
959 output.sampleRate,
960 input.config.channel_mask,
961 input.config.format,
962 frameCount,
963 patchRecord->buffer(),
964 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700965 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100966 0ns /* timeout */,
967 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800968 status = patchTrack->initCheck();
969 if (status != NO_ERROR) {
970 ALOGE("Secondary output patchTrack init failed: %d", status);
971 continue;
972 }
973 teePatches.push_back({patchRecord, patchTrack});
974 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800975 // In case the downstream patchTrack on the secondaryThread temporarily outlives
976 // our created track, ensure the corresponding patchRecord is still alive.
977 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
978 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800979 }
980 track->setTeePatches(std::move(teePatches));
981 }
982
Eric Laurent39e94f82010-07-28 01:32:47 -0700983 // move effect chain to this output thread if an effect on same session was waiting
984 // for a track to be created
985 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700986 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700987 Mutex::Autolock _dl(thread->mLock);
988 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700989 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
990 effectThreadId = thread->id();
991 effectIds = thread->getEffectIds_l(sessionId);
992 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700993 }
Eric Laurenta011e352012-03-29 15:51:43 -0700994
995 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700996 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800997 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700998 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700999 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07001000 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -07001001 } else {
1002 mPendingSyncEvents[i]->cancel();
1003 }
Eric Laurenta011e352012-03-29 15:51:43 -07001004 mPendingSyncEvents.removeAt(i);
1005 i--;
1006 }
1007 }
1008 }
Glenn Kastene198c362013-08-13 09:13:36 -07001009
Eric Laurent21da6472017-11-09 16:29:26 -08001010 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 }
Glenn Kastene198c362013-08-13 09:13:36 -07001012
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001013 if (lStatus != NO_ERROR) {
1014 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001015 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001016 // Don't hold mClientLock when releasing the reference on the track as the
1017 // destructor will acquire it.
1018 {
1019 Mutex::Autolock _cl(mClientLock);
1020 client.clear();
1021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001023 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001024 }
1025
Eric Laurent6c796322019-04-09 14:13:17 -07001026 // effectThreadId is not NONE if an effect chain corresponding to the track session
1027 // was found on another thread and must be moved on this thread
1028 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1029 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1030 }
1031
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001032 output.audioTrack = new TrackHandle(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001033 _output = VALUE_OR_FATAL(output.toAidl());
1034
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001036 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001037 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001038 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001039 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040}
1041
Glenn Kasten2c073da2016-02-26 09:14:08 -08001042uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043{
1044 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001045 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001047 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 return 0;
1049 }
1050 return thread->sampleRate();
1051}
1052
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001053audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054{
1055 Mutex::Autolock _l(mLock);
1056 PlaybackThread *thread = checkPlaybackThread_l(output);
1057 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001058 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001059 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 }
1061 return thread->format();
1062}
1063
Glenn Kasten2c073da2016-02-26 09:14:08 -08001064size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065{
1066 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001067 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001069 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 return 0;
1071 }
Glenn Kasten58912562012-04-03 10:45:00 -07001072 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1073 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 return thread->frameCount();
1075}
1076
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001077size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1078{
1079 Mutex::Autolock _l(mLock);
1080 ThreadBase *thread = checkThread_l(ioHandle);
1081 if (thread == NULL) {
1082 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1083 return 0;
1084 }
1085 return thread->frameCountHAL();
1086}
1087
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001088uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089{
1090 Mutex::Autolock _l(mLock);
1091 PlaybackThread *thread = checkPlaybackThread_l(output);
1092 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001093 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 return 0;
1095 }
1096 return thread->latency();
1097}
1098
1099status_t AudioFlinger::setMasterVolume(float value)
1100{
Eric Laurenta1884f92011-08-23 08:25:03 -07001101 status_t ret = initCheck();
1102 if (ret != NO_ERROR) {
1103 return ret;
1104 }
1105
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 // check calling permissions
1107 if (!settingsAllowed()) {
1108 return PERMISSION_DENIED;
1109 }
1110
Eric Laurenta4c5a552012-03-29 10:12:40 -07001111 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001112 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001113
John Grossmanee578c02012-07-23 17:05:46 -07001114 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001115 {
John Grossmanee578c02012-07-23 17:05:46 -07001116 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001117 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1118 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001119
Eric Laurent00abf0d2020-04-22 19:28:22 -07001120 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1121 if (dev->canSetMasterVolume()) {
1122 dev->hwDevice()->setMasterVolume(value);
1123 }
1124 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001125 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 }
John Grossmanee578c02012-07-23 17:05:46 -07001127 // Now set the master volume in each playback thread. Playback threads
1128 // assigned to HALs which do not have master volume support will apply
1129 // master volume during the mix operation. Threads with HALs which do
1130 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001131 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1132 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1133 continue;
1134 }
John Grossmanee578c02012-07-23 17:05:46 -07001135 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137
1138 return NO_ERROR;
1139}
1140
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001141status_t AudioFlinger::setMasterBalance(float balance)
1142{
1143 status_t ret = initCheck();
1144 if (ret != NO_ERROR) {
1145 return ret;
1146 }
1147
1148 // check calling permissions
1149 if (!settingsAllowed()) {
1150 return PERMISSION_DENIED;
1151 }
1152
1153 // check range
1154 if (isnan(balance) || fabs(balance) > 1.f) {
1155 return BAD_VALUE;
1156 }
1157
1158 Mutex::Autolock _l(mLock);
1159
1160 // short cut.
1161 if (mMasterBalance == balance) return NO_ERROR;
1162
1163 mMasterBalance = balance;
1164
1165 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1166 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1167 continue;
1168 }
1169 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1170 }
1171
1172 return NO_ERROR;
1173}
1174
Glenn Kastenf78aee72012-01-04 11:00:47 -08001175status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176{
Eric Laurenta1884f92011-08-23 08:25:03 -07001177 status_t ret = initCheck();
1178 if (ret != NO_ERROR) {
1179 return ret;
1180 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181
1182 // check calling permissions
1183 if (!settingsAllowed()) {
1184 return PERMISSION_DENIED;
1185 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001186 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001187 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 return BAD_VALUE;
1189 }
1190
1191 { // scope for the lock
1192 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001193 if (mPrimaryHardwareDev == nullptr) {
1194 return INVALID_OPERATION;
1195 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001196 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001198 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 mHardwareStatus = AUDIO_HW_IDLE;
1200 }
1201
1202 if (NO_ERROR == ret) {
1203 Mutex::Autolock _l(mLock);
1204 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001205 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001206 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 }
1208
Joey Poomarin52989982020-03-05 17:40:49 +08001209 mediametrics::LogItem(mMetricsId)
1210 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1211 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1212 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 return ret;
1214}
1215
1216status_t AudioFlinger::setMicMute(bool state)
1217{
Eric Laurenta1884f92011-08-23 08:25:03 -07001218 status_t ret = initCheck();
1219 if (ret != NO_ERROR) {
1220 return ret;
1221 }
1222
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 // check calling permissions
1224 if (!settingsAllowed()) {
1225 return PERMISSION_DENIED;
1226 }
1227
1228 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001229 if (mPrimaryHardwareDev == nullptr) {
1230 return INVALID_OPERATION;
1231 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001232 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1233 if (primaryDev == nullptr) {
1234 ALOGW("%s: no primary HAL device", __func__);
1235 return INVALID_OPERATION;
1236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001238 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001240 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001241 if (dev != primaryDev) {
1242 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001243 }
1244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001246 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 return ret;
1248}
1249
1250bool AudioFlinger::getMicMute() const
1251{
Eric Laurenta1884f92011-08-23 08:25:03 -07001252 status_t ret = initCheck();
1253 if (ret != NO_ERROR) {
1254 return false;
1255 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001256 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001257 if (mPrimaryHardwareDev == nullptr) {
1258 return false;
1259 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001260 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1261 if (primaryDev == nullptr) {
1262 ALOGW("%s: no primary HAL device", __func__);
1263 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001264 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001265 bool state;
1266 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1267 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001269 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1270 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271}
1272
Eric Laurent5ada82e2019-08-29 17:53:54 -07001273void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001274{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001275 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001276
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001277 AutoMutex lock(mLock);
1278 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001279 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001280 }
1281 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001282 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001283 }
1284}
1285
Mathias Agopian65ab4712010-07-14 17:59:35 -07001286status_t AudioFlinger::setMasterMute(bool muted)
1287{
John Grossmand8f178d2012-07-20 14:51:35 -07001288 status_t ret = initCheck();
1289 if (ret != NO_ERROR) {
1290 return ret;
1291 }
1292
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293 // check calling permissions
1294 if (!settingsAllowed()) {
1295 return PERMISSION_DENIED;
1296 }
1297
John Grossmanee578c02012-07-23 17:05:46 -07001298 Mutex::Autolock _l(mLock);
1299 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001300
John Grossmanee578c02012-07-23 17:05:46 -07001301 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001302 {
John Grossmanee578c02012-07-23 17:05:46 -07001303 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001304 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1305 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001306
Eric Laurent00abf0d2020-04-22 19:28:22 -07001307 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1308 if (dev->canSetMasterMute()) {
1309 dev->hwDevice()->setMasterMute(muted);
1310 }
1311 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001312 }
John Grossmand8f178d2012-07-20 14:51:35 -07001313 }
1314
John Grossmanee578c02012-07-23 17:05:46 -07001315 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001316 // assigned to HALs which do not have master mute support will apply master mute
1317 // during the mix operation. Threads with HALs which do support master mute
1318 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001319 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1320 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1321 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001323
1324 return NO_ERROR;
1325}
1326
1327float AudioFlinger::masterVolume() const
1328{
Glenn Kasten98067102011-12-13 11:47:54 -08001329 Mutex::Autolock _l(mLock);
1330 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331}
1332
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001333status_t AudioFlinger::getMasterBalance(float *balance) const
1334{
1335 Mutex::Autolock _l(mLock);
1336 *balance = getMasterBalance_l();
1337 return NO_ERROR; // if called through binder, may return a transactional error
1338}
1339
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340bool AudioFlinger::masterMute() const
1341{
Glenn Kasten98067102011-12-13 11:47:54 -08001342 Mutex::Autolock _l(mLock);
1343 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001344}
1345
John Grossman4ff14ba2012-02-08 16:37:41 -08001346float AudioFlinger::masterVolume_l() const
1347{
John Grossman4ff14ba2012-02-08 16:37:41 -08001348 return mMasterVolume;
1349}
1350
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001351float AudioFlinger::getMasterBalance_l() const
1352{
1353 return mMasterBalance;
1354}
1355
John Grossmand8f178d2012-07-20 14:51:35 -07001356bool AudioFlinger::masterMute_l() const
1357{
John Grossmanee578c02012-07-23 17:05:46 -07001358 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001359}
1360
Eric Laurent223fd5c2014-11-11 13:43:36 -08001361status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1362{
1363 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001364 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001365 return BAD_VALUE;
1366 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001367 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1368 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1369 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001370 return PERMISSION_DENIED;
1371 }
1372
1373 return NO_ERROR;
1374}
1375
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001376status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1377 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378{
1379 // check calling permissions
1380 if (!settingsAllowed()) {
1381 return PERMISSION_DENIED;
1382 }
1383
Eric Laurent223fd5c2014-11-11 13:43:36 -08001384 status_t status = checkStreamType(stream);
1385 if (status != NO_ERROR) {
1386 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 }
Eric Laurent98e38192018-02-15 18:31:53 -08001388 if (output == AUDIO_IO_HANDLE_NONE) {
1389 return BAD_VALUE;
1390 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001391 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1392 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393
1394 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001395 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1396 if (volumeInterface == NULL) {
1397 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398 }
Eric Laurent98e38192018-02-15 18:31:53 -08001399 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400
1401 return NO_ERROR;
1402}
1403
Glenn Kastenfff6d712012-01-12 16:38:12 -08001404status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405{
1406 // check calling permissions
1407 if (!settingsAllowed()) {
1408 return PERMISSION_DENIED;
1409 }
1410
Eric Laurent223fd5c2014-11-11 13:43:36 -08001411 status_t status = checkStreamType(stream);
1412 if (status != NO_ERROR) {
1413 return status;
1414 }
1415 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1416
1417 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001418 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001419 return BAD_VALUE;
1420 }
1421
Eric Laurent93575202011-01-18 18:39:02 -08001422 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001424 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1425 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1426 volumeInterfaces[i]->setStreamMute(stream, muted);
1427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428
1429 return NO_ERROR;
1430}
1431
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001432float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001434 status_t status = checkStreamType(stream);
1435 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 return 0.0f;
1437 }
Eric Laurent98e38192018-02-15 18:31:53 -08001438 if (output == AUDIO_IO_HANDLE_NONE) {
1439 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 }
1441
Eric Laurent98e38192018-02-15 18:31:53 -08001442 AutoMutex lock(mLock);
1443 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1444 if (volumeInterface == NULL) {
1445 return 0.0f;
1446 }
1447
1448 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449}
1450
Glenn Kastenfff6d712012-01-12 16:38:12 -08001451bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001453 status_t status = checkStreamType(stream);
1454 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455 return true;
1456 }
1457
Glenn Kasten6637baa2012-01-09 09:40:36 -08001458 AutoMutex lock(mLock);
1459 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460}
1461
Eric Laurent054d9d32015-04-24 08:48:48 -07001462
Andy Hungd9ef4b12020-11-11 15:13:18 -08001463void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001464{
1465 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1466 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1467 }
1468}
1469
jiabinc52b1ff2019-10-31 17:20:42 -07001470void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1471{
1472 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1473 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1474 }
1475}
1476
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001477// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1478void AudioFlinger::forwardParametersToDownstreamPatches_l(
1479 audio_io_handle_t upStream, const String8& keyValuePairs,
1480 std::function<bool(const sp<PlaybackThread>&)> useThread)
1481{
1482 std::vector<PatchPanel::SoftwarePatch> swPatches;
1483 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1484 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1485 __func__, swPatches.size(), upStream);
1486 for (const auto& swPatch : swPatches) {
1487 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1488 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1489 downStream->setParameters(keyValuePairs);
1490 }
1491 }
1492}
1493
Eric Laurentf1047e82018-04-16 19:18:20 -07001494// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1495// Some keys are used for audio routing and audio path configuration and should be reserved for use
1496// by audio policy and audio flinger for functional, privacy and security reasons.
1497void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1498{
1499 static const String8 kReservedParameters[] = {
1500 String8(AudioParameter::keyRouting),
1501 String8(AudioParameter::keySamplingRate),
1502 String8(AudioParameter::keyFormat),
1503 String8(AudioParameter::keyChannels),
1504 String8(AudioParameter::keyFrameCount),
1505 String8(AudioParameter::keyInputSource),
1506 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001507 String8(AudioParameter::keyDeviceConnect),
1508 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001509 String8(AudioParameter::keyStreamSupportedFormats),
1510 String8(AudioParameter::keyStreamSupportedChannels),
1511 String8(AudioParameter::keyStreamSupportedSamplingRates),
1512 };
1513
Andy Hung4ef19fa2018-05-15 19:35:29 -07001514 if (isAudioServerUid(callingUid)) {
1515 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001516 }
1517
1518 AudioParameter param = AudioParameter(keyValuePairs);
1519 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001520 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001521 for (auto& key : kReservedParameters) {
1522 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001523 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001524 param.remove(key);
1525 }
1526 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001527 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1528 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001529 keyValuePairs = param.toString();
1530}
1531
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001532void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1533 size_t rejectedKVPSize, const String8& rejectedKVPs,
1534 uid_t callingUid) {
1535 auto prefix = String8::format("UID %5d", callingUid);
1536 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1537 if (rejectedKVPSize != 0) {
1538 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1539 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1540 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1541 } else {
1542 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1543 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1544 }
1545}
1546
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001547status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548{
Eric Laurentf1047e82018-04-16 19:18:20 -07001549 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1550 ioHandle, keyValuePairs.string(),
1551 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001552
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 // check calling permissions
1554 if (!settingsAllowed()) {
1555 return PERMISSION_DENIED;
1556 }
1557
Eric Laurentf1047e82018-04-16 19:18:20 -07001558 String8 filteredKeyValuePairs = keyValuePairs;
1559 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1560
1561 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1562
Glenn Kasten142f5192014-03-25 17:44:59 -07001563 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1564 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001565 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001566 // result will remain NO_INIT if no audio device is present
1567 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001568 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001569 AutoMutex lock(mHardwareLock);
1570 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1571 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001572 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001573 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001574 // return success if at least one audio device accepts the parameters as not all
1575 // HALs are requested to support all parameters. If no audio device supports the
1576 // requested parameters, the last error is reported.
1577 if (final_result != NO_ERROR) {
1578 final_result = result;
1579 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001580 }
1581 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001582 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001583 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001584 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001585 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001586 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1587 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001588 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001589 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001590 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001591 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001592 }
1593 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001594 String8 screenState;
1595 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001596 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001597 if (isOff != (AudioFlinger::mScreenState & 1)) {
1598 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001599 }
1600 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001601 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 }
1603
1604 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1605 // and the thread is exited once the lock is released
1606 sp<ThreadBase> thread;
1607 {
1608 Mutex::Autolock _l(mLock);
1609 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001610 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001612 if (thread == 0) {
1613 thread = checkMmapThread_l(ioHandle);
1614 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001615 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001616 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001617 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001618 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001619 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1620 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001621 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001622 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 }
1624 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001625 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001626 status_t result = thread->setParameters(filteredKeyValuePairs);
1627 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1628 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 }
1630 return BAD_VALUE;
1631}
1632
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001633String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001634{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001635 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1636 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637
Eric Laurenta4c5a552012-03-29 10:12:40 -07001638 Mutex::Autolock _l(mLock);
1639
Glenn Kasten142f5192014-03-25 17:44:59 -07001640 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001641 String8 out_s8;
1642
Eric Laurent00abf0d2020-04-22 19:28:22 -07001643 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001644 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001645 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001646 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001647 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001648 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001649 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001650 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001651 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001652 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 }
1654
Eric Laurent6acd1d42017-01-04 14:23:29 -08001655 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1656 if (thread == NULL) {
1657 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1658 if (thread == NULL) {
1659 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1660 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001661 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001662 }
1663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001665 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666}
1667
Glenn Kastendd8104c2012-07-02 12:42:44 -07001668size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1669 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001670{
Eric Laurenta1884f92011-08-23 08:25:03 -07001671 status_t ret = initCheck();
1672 if (ret != NO_ERROR) {
1673 return 0;
1674 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001675 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001676 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001677 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001678 return 0;
1679 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001680
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001681 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001682 if (mPrimaryHardwareDev == nullptr) {
1683 return 0;
1684 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001685 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001686
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001687 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001688 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1689 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1690 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1691 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1692 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1693
1694 std::vector<audio_format_t> formats = {format};
1695 if (format != AUDIO_FORMAT_PCM_16_BIT)
1696 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1697
1698 std::vector<uint32_t> sampleRates = {sampleRate};
1699 static const uint32_t SR_44100 = 44100;
1700 static const uint32_t SR_48000 = 48000;
1701
1702 if (sampleRate != SR_48000)
1703 sampleRates.push_back(SR_48000);
1704 if (sampleRate != SR_44100)
1705 sampleRates.push_back(SR_44100);
1706
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001707 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001708
Robin Lee9899ff72019-12-24 22:02:08 +01001709 // Change parameters of the configuration each iteration until we find a
1710 // configuration that the device will support.
1711 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001712 for (auto testChannelMask : channelMasks) {
1713 config.channel_mask = testChannelMask;
1714 for (auto testFormat : formats) {
1715 config.format = testFormat;
1716 for (auto testSampleRate : sampleRates) {
1717 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001718
Judy Hsiaoabab5222019-11-09 18:14:58 +08001719 size_t bytes = 0;
1720 status_t result = dev->getInputBufferSize(&config, &bytes);
1721 if (result != OK || bytes == 0) {
1722 continue;
1723 }
1724
1725 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1726 config.format != format) {
1727 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1728 uint32_t srcChannelCount =
1729 audio_channel_count_from_in_mask(config.channel_mask);
1730 size_t srcFrames =
1731 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1732 size_t dstFrames = destinationFramesPossible(
1733 srcFrames, config.sample_rate, sampleRate);
1734 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1735 }
1736 return bytes;
1737 }
1738 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001739 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001740
1741 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1742 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1743 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
Glenn Kasten5f972c02014-01-13 09:59:31 -08001746uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 Mutex::Autolock _l(mLock);
1749
1750 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1751 if (recordThread != NULL) {
1752 return recordThread->getInputFramesLost();
1753 }
1754 return 0;
1755}
1756
1757status_t AudioFlinger::setVoiceVolume(float value)
1758{
Eric Laurenta1884f92011-08-23 08:25:03 -07001759 status_t ret = initCheck();
1760 if (ret != NO_ERROR) {
1761 return ret;
1762 }
1763
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 // check calling permissions
1765 if (!settingsAllowed()) {
1766 return PERMISSION_DENIED;
1767 }
1768
1769 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001770 if (mPrimaryHardwareDev == nullptr) {
1771 return INVALID_OPERATION;
1772 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001773 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001774 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001775 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 mHardwareStatus = AUDIO_HW_IDLE;
1777
Joey Poomarin52989982020-03-05 17:40:49 +08001778 mediametrics::LogItem(mMetricsId)
1779 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1780 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1781 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 return ret;
1783}
1784
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001785status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001786 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 Mutex::Autolock _l(mLock);
1789
1790 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1791 if (playbackThread != NULL) {
1792 return playbackThread->getRenderPosition(halFrames, dspFrames);
1793 }
1794
1795 return BAD_VALUE;
1796}
1797
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001798void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001801 if (client == 0) {
1802 return;
1803 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001804 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001805 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001806 {
1807 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001808 if (mNotificationClients.indexOfKey(pid) < 0) {
1809 sp<NotificationClient> notificationClient = new NotificationClient(this,
1810 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001811 pid,
1812 uid);
1813 ALOGV("registerClient() client %p, pid %d, uid %u",
1814 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815
Eric Laurent021cf962014-05-13 10:18:14 -07001816 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
Marco Nelissen06b46062014-11-14 07:58:25 -08001818 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001819 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001820 }
1821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822
Eric Laurent021cf962014-05-13 10:18:14 -07001823 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001824 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001825 // the config change is always sent from playback or record threads to avoid deadlock
1826 // with AudioSystem::gLock
1827 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001828 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001829 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001831 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001832 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 }
1834}
1835
1836void AudioFlinger::removeNotificationClient(pid_t pid)
1837{
Eric Laurent6c796322019-04-09 14:13:17 -07001838 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001839 {
Eric Laurent6c796322019-04-09 14:13:17 -07001840 Mutex::Autolock _l(mLock);
1841 {
1842 Mutex::Autolock _cl(mClientLock);
1843 mNotificationClients.removeItem(pid);
1844 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001845
Eric Laurent6c796322019-04-09 14:13:17 -07001846 ALOGV("%d died, releasing its sessions", pid);
1847 size_t num = mAudioSessionRefs.size();
1848 bool removed = false;
1849 for (size_t i = 0; i < num; ) {
1850 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1851 ALOGV(" pid %d @ %zu", ref->mPid, i);
1852 if (ref->mPid == pid) {
1853 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1854 mAudioSessionRefs.removeAt(i);
1855 delete ref;
1856 removed = true;
1857 num--;
1858 } else {
1859 i++;
1860 }
1861 }
1862 if (removed) {
1863 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001864 }
1865 }
Eric Laurent6c796322019-04-09 14:13:17 -07001866 for (auto& effect : removedEffects) {
1867 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869}
1870
Eric Laurent73e26b62015-04-27 16:55:58 -07001871void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001872 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001873 pid_t pid) {
1874 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
1875 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
1876 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
1877 legacy2aidl_audio_io_config_event_AudioIoConfigEvent(event));
1878
Eric Laurent021cf962014-05-13 10:18:14 -07001879 Mutex::Autolock _l(mClientLock);
1880 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001882 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001883 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
1884 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001885 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 }
1887}
1888
Eric Laurent021cf962014-05-13 10:18:14 -07001889// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890void AudioFlinger::removeClient_l(pid_t pid)
1891{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001892 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001893 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 mClients.removeItem(pid);
1895}
1896
Eric Laurent717e1282012-06-29 16:36:52 -07001897// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001898sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1899 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001900{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001901 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001902
1903 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001904 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001905 ALOG_ASSERT(thread == 0);
1906 thread = mPlaybackThreads.valueAt(i);
1907 }
1908 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001909 if (thread != nullptr) {
1910 return thread;
1911 }
1912 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1913 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1914 ALOG_ASSERT(thread == 0);
1915 thread = mRecordThreads.valueAt(i);
1916 }
1917 }
1918 if (thread != nullptr) {
1919 return thread;
1920 }
1921 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1922 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1923 ALOG_ASSERT(thread == 0);
1924 thread = mMmapThreads.valueAt(i);
1925 }
1926 }
Eric Laurent717e1282012-06-29 16:36:52 -07001927 return thread;
1928}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931
1932// ----------------------------------------------------------------------------
1933
1934AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1935 : RefBase(),
1936 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001937 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938{
Andy Hung6f248bb2018-01-23 14:04:37 -08001939 mMemoryDealer = new MemoryDealer(
1940 audioFlinger->getClientSharedHeapSize(),
1941 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942}
1943
Eric Laurent021cf962014-05-13 10:18:14 -07001944// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945AudioFlinger::Client::~Client()
1946{
1947 mAudioFlinger->removeClient_l(mPid);
1948}
1949
Glenn Kasten435dbe62012-01-30 10:15:48 -08001950sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951{
1952 return mMemoryDealer;
1953}
1954
1955// ----------------------------------------------------------------------------
1956
1957AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001958 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001959 pid_t pid,
1960 uid_t uid)
1961 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962{
1963}
1964
1965AudioFlinger::NotificationClient::~NotificationClient()
1966{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967}
1968
Glenn Kasten0f11b512014-01-31 16:18:54 -08001969void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970{
1971 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001972 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973}
1974
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001975// ----------------------------------------------------------------------------
1976AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1977 : mPendingRequests(false) {}
1978
1979
1980void AudioFlinger::MediaLogNotifier::requestMerge() {
1981 AutoMutex _l(mMutex);
1982 mPendingRequests = true;
1983 mCond.signal();
1984}
1985
1986bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001987 // Should already have been checked, but just in case
1988 if (sMediaLogService == 0) {
1989 return false;
1990 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001991 // Wait until there are pending requests
1992 {
1993 AutoMutex _l(mMutex);
1994 mPendingRequests = false; // to ignore past requests
1995 while (!mPendingRequests) {
1996 mCond.wait(mMutex);
1997 // TODO may also need an exitPending check
1998 }
1999 mPendingRequests = false;
2000 }
2001 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002002 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002003 usleep(kPostTriggerSleepPeriod);
2004 return true;
2005}
2006
2007void AudioFlinger::requestLogMerge() {
2008 mMediaLogNotifier->requestMerge();
2009}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
2011// ----------------------------------------------------------------------------
2012
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002013status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2014 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002016 CreateRecordInput input = VALUE_OR_EXIT(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002017 CreateRecordOutput output;
2018
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 sp<RecordThread::RecordTrack> recordTrack;
2020 sp<RecordHandle> recordHandle;
2021 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002023 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002024 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025
Eric Laurentf14db3c2017-12-08 14:20:36 -08002026 output.cblk.clear();
2027 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002028 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002029
Eric Laurentf14db3c2017-12-08 14:20:36 -08002030 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002031 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08002032 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07002033 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002034 ALOGW_IF(clientUid != callingUid,
2035 "%s uid %d tried to pass itself off as %d",
2036 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002037 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002038 updatePid = true;
2039 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002040 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002041 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002042 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002043 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002044 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08002045 __func__, callingUid, callingPid, clientPid);
2046 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07002047 }
2048
Andy Hung6770c6f2015-04-07 13:43:36 -07002049 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002050 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2051 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002052 lStatus = BAD_VALUE;
2053 goto Exit;
2054 }
2055
Glenn Kasten53b5d092014-02-05 10:00:23 -08002056 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002057 if (!audio_is_input_channel(input.config.channel_mask)) {
2058 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002059 lStatus = BAD_VALUE;
2060 goto Exit;
2061 }
2062
Eric Laurentf14db3c2017-12-08 14:20:36 -08002063 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2064 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2065 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2066 lStatus = BAD_VALUE;
2067 goto Exit;
2068 }
2069
2070 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002071 output.selectedDeviceId = input.selectedDeviceId;
2072 output.flags = input.flags;
2073
2074 client = registerPid(clientPid);
2075
2076 // Not a conventional loop, but a retry loop for at most two iterations total.
2077 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2078 // Exits loop via break on no error of got exit on error
2079 // The sp<> references will be dropped when re-entering scope.
2080 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2081 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002082 // release previously opened input if retrying.
2083 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2084 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002085 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002086 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002087 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002088 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002089 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002090 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002091 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002092 sessionId,
2093 // FIXME compare to AudioTrack
2094 clientPid,
2095 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002096 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002097 &input.config,
2098 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002099 if (lStatus != NO_ERROR) {
2100 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2101 goto Exit;
2102 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002103
Glenn Kasten05997e22014-03-13 15:08:33 -07002104 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002106 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002108 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2109 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 goto Exit;
2111 }
2112
Eric Laurentf14db3c2017-12-08 14:20:36 -08002113 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114
Eric Laurentf14db3c2017-12-08 14:20:36 -08002115 output.sampleRate = input.config.sample_rate;
2116 output.frameCount = input.frameCount;
2117 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002118
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002119 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002120 input.config.format, input.config.channel_mask,
2121 &output.frameCount, sessionId,
2122 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002123 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002124 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002125 &lStatus, portId,
2126 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002127 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002128
Eric Laurentf14db3c2017-12-08 14:20:36 -08002129 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2130 // audio policy manager without FAST constraint
2131 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002132 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002133 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002134
2135 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002136 goto Exit;
2137 }
2138
2139 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2140 // session and move it to this thread.
2141 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2142 if (chain != 0) {
2143 Mutex::Autolock _l(thread->mLock);
2144 thread->addEffectChain_l(chain);
2145 }
2146 break;
2147 }
2148 // End of retry loop.
2149 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 }
Glenn Kastene198c362013-08-13 09:13:36 -07002151
Eric Laurentf14db3c2017-12-08 14:20:36 -08002152 output.cblk = recordTrack->getCblk();
2153 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002154 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002155
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002156 output.audioRecord = new RecordHandle(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002157 _output = VALUE_OR_FATAL(output.toAidl());
2158
Eric Laurentf14db3c2017-12-08 14:20:36 -08002159Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002160 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002161 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002162 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002163 // Don't hold mClientLock when releasing the reference on the track as the
2164 // destructor will acquire it.
2165 {
2166 Mutex::Autolock _cl(mClientLock);
2167 client.clear();
2168 }
Eric Laurent896c9672017-12-08 14:08:45 -08002169 recordTrack.clear();
2170 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002171 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 }
2174
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002175 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176}
2177
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002178
2179
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180// ----------------------------------------------------------------------------
2181
Eric Laurenta4c5a552012-03-29 10:12:40 -07002182audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2183{
Eric Laurent44622db2014-08-01 19:00:33 -07002184 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002185 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002186 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002187 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002188 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002189 }
2190 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002191 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002192 return loadHwModule_l(name);
2193}
2194
Eric Laurent00abf0d2020-04-22 19:28:22 -07002195// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002196audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2197{
2198 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2199 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2200 ALOGW("loadHwModule() module %s already loaded", name);
2201 return mAudioHwDevs.keyAt(i);
2202 }
2203 }
2204
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002205 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002206
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002207 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002208 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002209 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002210 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002211 }
2212
2213 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002214 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002215 mHardwareStatus = AUDIO_HW_IDLE;
2216 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002217 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002218 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002219 }
2220
John Grossmanee578c02012-07-23 17:05:46 -07002221 // Check and cache this HAL's level of support for master mute and master
2222 // volume. If this is the first HAL opened, and it supports the get
2223 // methods, use the initial values provided by the HAL as the current
2224 // master mute and volume settings.
2225
2226 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002227 if (0 == mAudioHwDevs.size()) {
2228 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2229 float mv;
2230 if (OK == dev->getMasterVolume(&mv)) {
2231 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002232 }
2233
Eric Laurent00abf0d2020-04-22 19:28:22 -07002234 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2235 bool mm;
2236 if (OK == dev->getMasterMute(&mm)) {
2237 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002238 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002239 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002240
2241 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2242 if (OK == dev->setMasterVolume(mMasterVolume)) {
2243 flags = static_cast<AudioHwDevice::Flags>(flags |
2244 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2245 }
2246
2247 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2248 if (OK == dev->setMasterMute(mMasterMute)) {
2249 flags = static_cast<AudioHwDevice::Flags>(flags |
2250 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2251 }
2252
2253 mHardwareStatus = AUDIO_HW_IDLE;
2254
Mikhail Naganov97373b02018-07-23 13:27:24 -07002255 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002256 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2257 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2258 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002259
Glenn Kastena13cde92016-03-28 15:26:02 -07002260 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002261 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2262 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2263 mPrimaryHardwareDev = audioDevice;
2264 mHardwareStatus = AUDIO_HW_SET_MODE;
2265 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2266 mHardwareStatus = AUDIO_HW_IDLE;
2267 }
2268
2269 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002270
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002271 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002272
2273 return handle;
2274
2275}
2276
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002277// ----------------------------------------------------------------------------
2278
Glenn Kasten3b16c762012-11-14 08:44:39 -08002279uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002280{
2281 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002282 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002283 return thread != NULL ? thread->sampleRate() : 0;
2284}
2285
Glenn Kastene33054e2012-11-14 12:54:39 -08002286size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002287{
2288 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002289 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002290 return thread != NULL ? thread->frameCountHAL() : 0;
2291}
2292
2293// ----------------------------------------------------------------------------
2294
Andy Hung6f248bb2018-01-23 14:04:37 -08002295status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002296{
2297 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002298 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002299 return PERMISSION_DENIED;
2300 }
2301 Mutex::Autolock _l(mLock);
2302 if (mIsDeviceTypeKnown) {
2303 return INVALID_OPERATION;
2304 }
2305 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002306 mTotalMemory = totalMemory;
2307 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2308 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2309 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2310 // though actual setting is determined through device configuration.
2311 constexpr int64_t GB = 1024 * 1024 * 1024;
2312 mClientSharedHeapSize =
2313 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2314 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2315 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2316 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2317 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002318 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002319
2320 // TODO: Cache the client shared heap size in a persistent property.
2321 // It's possible that a native process or Java service or app accesses audioserver
2322 // after it is registered by system server, but before AudioService updates
2323 // the memory info. This would occur immediately after boot or an audioserver
2324 // crash and restore. Before update from AudioService, the client would get the
2325 // minimum heap size.
2326
2327 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2328 (isLowRamDevice ? "true" : "false"),
2329 (long long)mTotalMemory,
2330 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002331 return NO_ERROR;
2332}
2333
Andy Hung6f248bb2018-01-23 14:04:37 -08002334size_t AudioFlinger::getClientSharedHeapSize() const
2335{
2336 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2337 if (heapSizeInBytes != 0) { // read-only property overrides all.
2338 return heapSizeInBytes;
2339 }
2340 return mClientSharedHeapSize;
2341}
2342
Mikhail Naganovdea53042018-04-26 13:10:21 -07002343status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2344{
2345 ALOGV(__func__);
2346
2347 audio_module_handle_t module;
2348 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2349 module = config->ext.device.hw_module;
2350 } else {
2351 module = config->ext.mix.hw_module;
2352 }
2353
2354 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002355 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002356 ssize_t index = mAudioHwDevs.indexOfKey(module);
2357 if (index < 0) {
2358 ALOGW("%s() bad hw module %d", __func__, module);
2359 return BAD_VALUE;
2360 }
2361
2362 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2363 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2364}
2365
Eric Laurent93c3d412014-08-01 14:48:35 -07002366audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2367{
2368 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002369
2370 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2371 if (index >= 0) {
2372 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2373 mHwAvSyncIds.valueAt(index), sessionId);
2374 return mHwAvSyncIds.valueAt(index);
2375 }
2376
Eric Laurent00abf0d2020-04-22 19:28:22 -07002377 sp<DeviceHalInterface> dev;
2378 {
2379 AutoMutex lock(mHardwareLock);
2380 if (mPrimaryHardwareDev == nullptr) {
2381 return AUDIO_HW_SYNC_INVALID;
2382 }
2383 dev = mPrimaryHardwareDev->hwDevice();
2384 }
2385 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002386 return AUDIO_HW_SYNC_INVALID;
2387 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002388 String8 reply;
2389 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002390 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002391 param = AudioParameter(reply);
2392 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002393
2394 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002395 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002396 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2397 return AUDIO_HW_SYNC_INVALID;
2398 }
2399
2400 // allow only one session for a given HW A/V sync ID.
2401 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2402 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2403 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2404 value, mHwAvSyncIds.keyAt(i));
2405 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002406 break;
2407 }
2408 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002409
2410 mHwAvSyncIds.add(sessionId, value);
2411
2412 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2413 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2414 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002415 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002416 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002417 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002418 String8 keyValuePairs = param.toString();
2419 thread->setParameters(keyValuePairs);
2420 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2421 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002422 break;
2423 }
2424 }
2425
2426 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2427 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002428}
2429
Eric Laurent72e3f392015-05-20 14:43:50 -07002430status_t AudioFlinger::systemReady()
2431{
2432 Mutex::Autolock _l(mLock);
2433 ALOGI("%s", __FUNCTION__);
2434 if (mSystemReady) {
2435 ALOGW("%s called twice", __FUNCTION__);
2436 return NO_ERROR;
2437 }
2438 mSystemReady = true;
2439 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2440 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2441 thread->systemReady();
2442 }
2443 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2444 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2445 thread->systemReady();
2446 }
2447 return NO_ERROR;
2448}
2449
jiabin46a76fa2018-01-05 10:18:21 -08002450status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2451{
jiabin9ff780e2018-03-19 18:19:52 -07002452 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002453 status_t status = INVALID_OPERATION;
2454
2455 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2456 std::vector<media::MicrophoneInfo> mics;
2457 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2458 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2459 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2460 mHardwareStatus = AUDIO_HW_IDLE;
2461 if (devStatus == NO_ERROR) {
2462 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2463 // report success if at least one HW module supports the function.
2464 status = NO_ERROR;
2465 }
2466 }
2467
jiabin9ff780e2018-03-19 18:19:52 -07002468 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002469}
2470
Eric Laurentfa90e842014-10-17 18:12:31 -07002471// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2472void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2473{
2474 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2475 if (index >= 0) {
2476 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2477 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2478 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002479 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002480 String8 keyValuePairs = param.toString();
2481 thread->setParameters(keyValuePairs);
2482 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2483 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002484 }
2485}
2486
2487
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002488// ----------------------------------------------------------------------------
2489
Eric Laurent83b88082014-06-20 18:31:16 -07002490
Eric Laurent6acd1d42017-01-04 14:23:29 -08002491sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002492 audio_io_handle_t *output,
2493 audio_config_t *config,
2494 audio_devices_t deviceType,
2495 const String8& address,
2496 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002497{
jiabin43810402019-10-24 14:58:31 -07002498 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002499 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002500 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002501 }
2502
Eric Laurentcf2c0212014-07-25 16:20:43 -07002503 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002504 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2505 } else {
2506 // Audio Policy does not currently request a specific output handle.
2507 // If this is ever needed, see openInput_l() for example code.
2508 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2509 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002510 }
Eric Laurent83b88082014-06-20 18:31:16 -07002511
2512 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2513
Eric Laurent83b88082014-06-20 18:31:16 -07002514 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002515 // This if statement allows overriding the audio policy settings
2516 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2517 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2518 // Check only for Normal Mixing mode
2519 if (kEnableExtendedPrecision) {
2520 // Specify format (uncomment one below to choose)
2521 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2522 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2523 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2524 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002525 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002526 }
2527 if (kEnableExtendedChannels) {
2528 // Specify channel mask (uncomment one below to choose)
2529 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2530 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2531 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2532 }
Eric Laurent83b88082014-06-20 18:31:16 -07002533 }
2534
Phil Burk062e67a2015-02-11 13:40:50 -08002535 AudioStreamOut *outputStream = NULL;
2536 status_t status = outHwDev->openOutputStream(
2537 &outputStream,
2538 *output,
jiabin43810402019-10-24 14:58:31 -07002539 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002540 flags,
2541 config,
2542 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002543
2544 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002545
Phil Burk062e67a2015-02-11 13:40:50 -08002546 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002547 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2548 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002549 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002550 mMmapThreads.add(*output, thread);
2551 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2552 *output, thread.get());
2553 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002554 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002555 sp<PlaybackThread> thread;
2556 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002557 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002558 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2559 *output, thread.get());
2560 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2561 || !isValidPcmSinkFormat(config->format)
2562 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002563 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002564 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2565 *output, thread.get());
2566 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002567 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002568 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2569 *output, thread.get());
2570 }
2571 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002572 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002573 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002574 }
Eric Laurent83b88082014-06-20 18:31:16 -07002575 }
2576
2577 return 0;
2578}
2579
Eric Laurentcf2c0212014-07-25 16:20:43 -07002580status_t AudioFlinger::openOutput(audio_module_handle_t module,
2581 audio_io_handle_t *output,
2582 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002583 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002584 uint32_t *latencyMs,
2585 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586{
jiabin43810402019-10-24 14:58:31 -07002587 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002588 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002589 this, module,
jiabin43810402019-10-24 14:58:31 -07002590 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002591 config->sample_rate,
2592 config->format,
2593 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002594 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595
jiabin43810402019-10-24 14:58:31 -07002596 audio_devices_t deviceType = device->type();
2597 const String8 address = String8(device->address().c_str());
2598
2599 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002600 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002602
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603 Mutex::Autolock _l(mLock);
2604
jiabin43810402019-10-24 14:58:31 -07002605 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002606 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002607 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2608 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2609 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610
Eric Laurent6acd1d42017-01-04 14:23:29 -08002611 // notify client processes of the new output creation
2612 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002613
Eric Laurent00abf0d2020-04-22 19:28:22 -07002614 // the first primary output opened designates the primary hw device if no HW module
2615 // named "primary" was already loaded.
2616 AutoMutex lock(mHardwareLock);
2617 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002618 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002619 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002620
Eric Laurent6acd1d42017-01-04 14:23:29 -08002621 mHardwareStatus = AUDIO_HW_SET_MODE;
2622 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2623 mHardwareStatus = AUDIO_HW_IDLE;
2624 }
2625 } else {
2626 MmapThread *mmapThread = (MmapThread *)thread.get();
2627 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002628 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002629 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 }
2631
Eric Laurentcf2c0212014-07-25 16:20:43 -07002632 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633}
2634
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002635audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2636 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637{
2638 Mutex::Autolock _l(mLock);
2639 MixerThread *thread1 = checkMixerThread_l(output1);
2640 MixerThread *thread2 = checkMixerThread_l(output2);
2641
2642 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002643 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2644 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002645 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 }
2647
Glenn Kasteneeecb982016-02-26 10:44:04 -08002648 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002649 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 thread->addOutputTrack(thread2);
2651 mPlaybackThreads.add(id, thread);
2652 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002653 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 return id;
2655}
2656
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002657status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658{
Glenn Kastend96c5722012-04-25 13:44:49 -07002659 return closeOutput_nonvirtual(output);
2660}
2661
2662status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2663{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 // keep strong reference on the playback thread so that
2665 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002666 sp<PlaybackThread> playbackThread;
2667 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 {
2669 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002670 playbackThread = checkPlaybackThread_l(output);
2671 if (playbackThread != NULL) {
2672 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673
Andy Hungdc099c22018-09-18 13:46:39 -07002674 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002675
Eric Laurent6acd1d42017-01-04 14:23:29 -08002676 if (playbackThread->type() == ThreadBase::MIXER) {
2677 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2678 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2679 DuplicatingThread *dupThread =
2680 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2681 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2682 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 }
2684 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002685
2686
Eric Laurent6acd1d42017-01-04 14:23:29 -08002687 mPlaybackThreads.removeItem(output);
2688 // save all effects to the default thread
2689 if (mPlaybackThreads.size()) {
2690 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2691 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002692 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002693 Mutex::Autolock _dl(dstThread->mLock);
2694 Mutex::Autolock _sl(playbackThread->mLock);
2695 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2696 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002697 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002698 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 }
2701 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002702 } else {
2703 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2704 if (mmapThread == 0) {
2705 return BAD_VALUE;
2706 }
Andy Hungdc099c22018-09-18 13:46:39 -07002707 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002708 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002709 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002711 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2712 ioDesc->mIoHandle = output;
2713 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002714 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002716 // The thread entity (active unit of execution) is no longer running here,
2717 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718
Eric Laurent6acd1d42017-01-04 14:23:29 -08002719 if (playbackThread != 0) {
2720 playbackThread->exit();
2721 if (!playbackThread->isDuplicating()) {
2722 closeOutputFinish(playbackThread);
2723 }
2724 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002725 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002726 mmapThread->exit();
2727 AudioStreamOut *out = mmapThread->clearOutput();
2728 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2729 // from now on thread->mOutput is NULL
2730 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 }
2732 return NO_ERROR;
2733}
2734
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002735void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002736{
2737 AudioStreamOut *out = thread->clearOutput();
2738 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2739 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002740 delete out;
2741}
2742
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002743void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002744{
2745 mPlaybackThreads.removeItem(thread->mId);
2746 thread->exit();
2747 closeOutputFinish(thread);
2748}
2749
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002750status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751{
2752 Mutex::Autolock _l(mLock);
2753 PlaybackThread *thread = checkPlaybackThread_l(output);
2754
2755 if (thread == NULL) {
2756 return BAD_VALUE;
2757 }
2758
Steve Block3856b092011-10-20 11:56:00 +01002759 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 thread->suspend();
2761
2762 return NO_ERROR;
2763}
2764
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002765status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766{
2767 Mutex::Autolock _l(mLock);
2768 PlaybackThread *thread = checkPlaybackThread_l(output);
2769
2770 if (thread == NULL) {
2771 return BAD_VALUE;
2772 }
2773
Steve Block3856b092011-10-20 11:56:00 +01002774 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775
2776 thread->restore();
2777
2778 return NO_ERROR;
2779}
2780
Eric Laurentcf2c0212014-07-25 16:20:43 -07002781status_t AudioFlinger::openInput(audio_module_handle_t module,
2782 audio_io_handle_t *input,
2783 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002784 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002785 const String8& address,
2786 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002787 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788{
Eric Laurent83b88082014-06-20 18:31:16 -07002789 Mutex::Autolock _l(mLock);
2790
Glenn Kastene7d66712015-03-05 13:46:52 -08002791 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002792 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002793 }
2794
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002795 sp<ThreadBase> thread = openInput_l(
2796 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002797
2798 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002799 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002800 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002801 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002803 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002804}
Dima Zavin799a70e2011-04-18 16:57:27 -07002805
Eric Laurent6acd1d42017-01-04 14:23:29 -08002806sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002807 audio_io_handle_t *input,
2808 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002809 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002810 const String8& address,
2811 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002812 audio_input_flags_t flags,
2813 audio_devices_t outputDevice,
2814 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002815{
Glenn Kastene7d66712015-03-05 13:46:52 -08002816 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002817 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002818 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002819 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002820 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002821
Glenn Kasteneeecb982016-02-26 10:44:04 -08002822 // Audio Policy can request a specific handle for hardware hotword.
2823 // The goal here is not to re-open an already opened input.
2824 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002825 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002826 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2827 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2828 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2829 return 0;
2830 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2831 // This should not happen in a transient state with current design.
2832 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2833 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002834 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002835
Eric Laurentcf2c0212014-07-25 16:20:43 -07002836 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002837 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002838 sp<StreamInHalInterface> inStream;
2839 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002840 *input, devices, &halconfig, flags, address.string(), source,
2841 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002842 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2843 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002844 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002845 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002846 halconfig.sample_rate,
2847 halconfig.format,
2848 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002849 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002850 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002852 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002853 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002854 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002855 audio_is_linear_pcm(config->format) &&
2856 audio_is_linear_pcm(halconfig.format) &&
2857 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002858 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2859 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002860 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002861 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002862 inStream.clear();
2863 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002864 *input, devices, &halconfig, flags, address.string(), source,
2865 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002866 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 }
2868
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002869 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002870 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002871 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2872 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002873 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002874 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002875 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2876 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002877 return thread;
2878 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002879 // Start record thread
2880 // RecordThread requires both input and output device indication to forward to audio
2881 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002882 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002883 mRecordThreads.add(*input, thread);
2884 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2885 return thread;
2886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887 }
2888
Eric Laurentcf2c0212014-07-25 16:20:43 -07002889 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 return 0;
2891}
2892
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002893status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894{
Glenn Kastend96c5722012-04-25 13:44:49 -07002895 return closeInput_nonvirtual(input);
2896}
2897
2898status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2899{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 // keep strong reference on the record thread so that
2901 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002902 sp<RecordThread> recordThread;
2903 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904 {
2905 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002906 recordThread = checkRecordThread_l(input);
2907 if (recordThread != 0) {
2908 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909
Andy Hungdc099c22018-09-18 13:46:39 -07002910 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002911
Eric Laurent6acd1d42017-01-04 14:23:29 -08002912 // If we still have effect chains, it means that a client still holds a handle
2913 // on at least one effect. We must either move the chain to an existing thread with the
2914 // same session ID or put it aside in case a new record thread is opened for a
2915 // new capture on the same session
2916 sp<EffectChain> chain;
2917 {
2918 Mutex::Autolock _sl(recordThread->mLock);
2919 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2920 // Note: maximum one chain per record thread
2921 if (effectChains.size() != 0) {
2922 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002923 }
2924 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002925 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002926 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002927 // This should only happen in case of overlap between one thread tear down and the
2928 // creation of its replacement
2929 size_t i;
2930 for (i = 0; i < mRecordThreads.size(); i++) {
2931 sp<RecordThread> t = mRecordThreads.valueAt(i);
2932 if (t == recordThread) {
2933 continue;
2934 }
2935 if (t->hasAudioSession(chain->sessionId()) != 0) {
2936 Mutex::Autolock _l(t->mLock);
2937 ALOGV("closeInput() found thread %d for effect session %d",
2938 t->id(), chain->sessionId());
2939 t->addEffectChain_l(chain);
2940 break;
2941 }
2942 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002943 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002944 if (i == mRecordThreads.size()) {
2945 putOrphanEffectChain_l(chain);
2946 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002947 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002948 mRecordThreads.removeItem(input);
2949 } else {
2950 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2951 if (mmapThread == 0) {
2952 return BAD_VALUE;
2953 }
Andy Hungdc099c22018-09-18 13:46:39 -07002954 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002955 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002956 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002957 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2958 ioDesc->mIoHandle = input;
2959 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960 }
Eric Laurent83b88082014-06-20 18:31:16 -07002961 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2962 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002963 if (recordThread != 0) {
2964 closeInputFinish(recordThread);
2965 } else if (mmapThread != 0) {
2966 mmapThread->exit();
2967 AudioStreamIn *in = mmapThread->clearInput();
2968 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2969 // from now on thread->mInput is NULL
2970 delete in;
2971 }
Eric Laurent83b88082014-06-20 18:31:16 -07002972 return NO_ERROR;
2973}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002975void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002976{
2977 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002978 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002979 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002980 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002981 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002982}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002984void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002985{
2986 mRecordThreads.removeItem(thread->mId);
2987 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988}
2989
Glenn Kastend2304db2014-02-03 07:40:31 -08002990status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991{
2992 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002993 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994
2995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2996 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002997 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002998 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002999 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3000 mMmapThreads[i]->invalidateTracks(stream);
3001 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002 return NO_ERROR;
3003}
3004
3005
Glenn Kasteneeecb982016-02-26 10:44:04 -08003006audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007{
Glenn Kasten9d003132016-04-06 14:38:09 -07003008 // This is a binder API, so a malicious client could pass in a bad parameter.
3009 // Check for that before calling the internal API nextUniqueId().
3010 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3011 ALOGE("newAudioUniqueId invalid use %d", use);
3012 return AUDIO_UNIQUE_ID_ALLOCATE;
3013 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003014 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015}
3016
Andy Hung8b0bfd92019-12-23 13:11:11 -08003017void AudioFlinger::acquireAudioSessionId(
3018 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003019{
3020 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003021 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003022 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003023 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003024 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3025 caller = pid; // check must match releaseAudioSessionId()
3026 }
3027 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3028 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003029 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003030
Eric Laurent021cf962014-05-13 10:18:14 -07003031 {
3032 Mutex::Autolock _cl(mClientLock);
3033 // Ignore requests received from processes not known as notification client. The request
3034 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3035 // called from a different pid leaving a stale session reference. Also we don't know how
3036 // to clear this reference if the client process dies.
3037 if (mNotificationClients.indexOfKey(caller) < 0) {
3038 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3039 return;
3040 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003041 }
3042
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003043 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003044 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003045 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003046 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3047 ref->mCnt++;
3048 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003049 return;
3050 }
3051 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003052 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003053 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003054}
3055
Glenn Kastend848eb42016-03-08 13:42:11 -08003056void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003057{
Eric Laurent6c796322019-04-09 14:13:17 -07003058 std::vector< sp<EffectModule> > removedEffects;
3059 {
3060 Mutex::Autolock _l(mLock);
3061 pid_t caller = IPCThreadState::self()->getCallingPid();
3062 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3063 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003064 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3065 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003066 }
Eric Laurent6c796322019-04-09 14:13:17 -07003067 size_t num = mAudioSessionRefs.size();
3068 for (size_t i = 0; i < num; i++) {
3069 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3070 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3071 ref->mCnt--;
3072 ALOGV(" decremented refcount to %d", ref->mCnt);
3073 if (ref->mCnt == 0) {
3074 mAudioSessionRefs.removeAt(i);
3075 delete ref;
3076 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3077 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3078 }
3079 goto Exit;
3080 }
3081 }
3082 // If the caller is audioserver it is likely that the session being released was acquired
3083 // on behalf of a process not in notification clients and we ignore the warning.
3084 ALOGW_IF(!isAudioServerUid(callerUid),
3085 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003086 }
Eric Laurent6c796322019-04-09 14:13:17 -07003087
3088Exit:
3089 for (auto& effect : removedEffects) {
3090 effect->updatePolicyState();
3091 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003092}
3093
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003094bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3095{
3096 size_t num = mAudioSessionRefs.size();
3097 for (size_t i = 0; i < num; i++) {
3098 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3099 if (ref->mSessionid == audioSession) {
3100 return true;
3101 }
3102 }
3103 return false;
3104}
3105
Eric Laurent6c796322019-04-09 14:13:17 -07003106std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003107
Steve Block3856b092011-10-20 11:56:00 +01003108 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003109
3110 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003111 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003112
3113 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3114 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003115 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003116 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3117 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003118 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003119 chains.push(ec);
3120 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003121 }
3122 }
Eric Laurent6c796322019-04-09 14:13:17 -07003123
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003124 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3125 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003126 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003127 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3128 sp<EffectChain> ec = t->mEffectChains[j];
3129 chains.push(ec);
3130 }
3131 }
3132
Eric Laurent6c796322019-04-09 14:13:17 -07003133 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3134 sp<MmapThread> t = mMmapThreads.valueAt(i);
3135 Mutex::Autolock _l(t->mLock);
3136 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3137 sp<EffectChain> ec = t->mEffectChains[j];
3138 chains.push(ec);
3139 }
3140 }
3141
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003142 for (size_t i = 0; i < chains.size(); i++) {
3143 sp<EffectChain> ec = chains[i];
3144 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003145 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003146 if (t == 0) {
3147 continue;
3148 }
3149 size_t numsessionrefs = mAudioSessionRefs.size();
3150 bool found = false;
3151 for (size_t k = 0; k < numsessionrefs; k++) {
3152 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003153 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003154 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003155 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003156 found = true;
3157 break;
3158 }
3159 }
3160 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003161 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003162 // remove all effects from the chain
3163 while (ec->mEffects.size()) {
3164 sp<EffectModule> effect = ec->mEffects[0];
3165 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003166 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003167 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003168 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003169 }
Eric Laurent6c796322019-04-09 14:13:17 -07003170 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003171 }
3172 }
3173 }
Eric Laurent6c796322019-04-09 14:13:17 -07003174 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003175}
3176
Andy Hungdc099c22018-09-18 13:46:39 -07003177// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3178void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3179{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303180 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3181 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003182 const int fd = fdToString.fd();
3183 if (fd >= 0) {
3184 thread->dump(fd, {} /* args */);
3185 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3186 }
3187}
3188
Glenn Kasteneeecb982016-02-26 10:44:04 -08003189// checkThread_l() must be called with AudioFlinger::mLock held
3190AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3191{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003192 ThreadBase *thread = checkMmapThread_l(ioHandle);
3193 if (thread == 0) {
3194 switch (audio_unique_id_get_use(ioHandle)) {
3195 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3196 thread = checkPlaybackThread_l(ioHandle);
3197 break;
3198 case AUDIO_UNIQUE_ID_USE_INPUT:
3199 thread = checkRecordThread_l(ioHandle);
3200 break;
3201 default:
3202 break;
3203 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003204 }
3205 return thread;
3206}
3207
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003209AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210{
Glenn Kastena1117922012-01-26 10:53:32 -08003211 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212}
3213
3214// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003215AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216{
3217 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003218 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219}
3220
3221// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003222AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223{
Glenn Kastena1117922012-01-26 10:53:32 -08003224 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225}
3226
Eric Laurent6acd1d42017-01-04 14:23:29 -08003227// checkMmapThread_l() must be called with AudioFlinger::mLock held
3228AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3229{
3230 return mMmapThreads.valueFor(io).get();
3231}
3232
3233
3234// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3235AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3236{
Eric Laurent7459b902017-04-19 18:10:41 -07003237 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003238 if (volumeInterface == nullptr) {
3239 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3240 if (mmapThread != nullptr) {
3241 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003242 MmapPlaybackThread *mmapPlaybackThread =
3243 static_cast<MmapPlaybackThread *>(mmapThread);
3244 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003245 }
3246 }
3247 }
3248 return volumeInterface;
3249}
3250
3251Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3252{
3253 Vector <VolumeInterface *> volumeInterfaces;
3254 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003255 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003256 }
3257 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3258 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003259 MmapPlaybackThread *mmapPlaybackThread =
3260 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3261 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003262 }
3263 }
3264 return volumeInterfaces;
3265}
3266
Glenn Kasteneeecb982016-02-26 10:44:04 -08003267audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268{
Glenn Kasten9d003132016-04-06 14:38:09 -07003269 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003270 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003271 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3272 for (int retry = 0; retry < maxRetries; retry++) {
3273 // The cast allows wraparound from max positive to min negative instead of abort
3274 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3275 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3276 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3277 // allow wrap by skipping 0 and -1 for session ids
3278 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3279 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3280 return (audio_unique_id_t) (base | use);
3281 }
3282 }
3283 // We have no way of recovering from wraparound
3284 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3285 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286}
3287
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003288AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003289{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003290 AutoMutex lock(mHardwareLock);
3291 if (mPrimaryHardwareDev == nullptr) {
3292 return nullptr;
3293 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003294 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3295 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003296 if(thread->isDuplicating()) {
3297 continue;
3298 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003299 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003300 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003301 return thread;
3302 }
3303 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003304 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003305}
3306
jiabinc52b1ff2019-10-31 17:20:42 -07003307DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003308{
3309 PlaybackThread *thread = primaryPlaybackThread_l();
3310
3311 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003312 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003313 }
3314
jiabinc52b1ff2019-10-31 17:20:42 -07003315 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003316}
3317
Glenn Kastena7335632016-06-09 17:09:53 -07003318AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3319{
3320 size_t minFrameCount = 0;
3321 PlaybackThread *minThread = NULL;
3322 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3323 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3324 if (!thread->isDuplicating()) {
3325 size_t frameCount = thread->frameCountHAL();
3326 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3327 (frameCount == minFrameCount && thread->hasFastMixer() &&
3328 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3329 minFrameCount = frameCount;
3330 minThread = thread;
3331 }
3332 }
3333 }
3334 return minThread;
3335}
3336
jiabineb3bda02020-06-30 14:07:03 -07003337AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3338 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3339 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3340 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3341 return thread;
3342 }
3343 }
3344 return nullptr;
3345}
3346
Eric Laurenta011e352012-03-29 15:51:43 -07003347sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003348 audio_session_t triggerSession,
3349 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003350 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003351 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003352{
3353 Mutex::Autolock _l(mLock);
3354
3355 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3356 status_t playStatus = NAME_NOT_FOUND;
3357 status_t recStatus = NAME_NOT_FOUND;
3358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3359 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3360 if (playStatus == NO_ERROR) {
3361 return event;
3362 }
3363 }
3364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3365 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3366 if (recStatus == NO_ERROR) {
3367 return event;
3368 }
3369 }
3370 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3371 mPendingSyncEvents.add(event);
3372 } else {
3373 ALOGV("createSyncEvent() invalid event %d", event->type());
3374 event.clear();
3375 }
3376 return event;
3377}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003378
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379// ----------------------------------------------------------------------------
3380// Effect management
3381// ----------------------------------------------------------------------------
3382
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003383sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3384 return mEffectsFactoryHal;
3385}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386
Glenn Kastenf587ba52012-01-26 16:25:10 -08003387status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388{
3389 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003390 if (mEffectsFactoryHal.get()) {
3391 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3392 } else {
3393 return -ENODEV;
3394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395}
3396
Glenn Kastenf587ba52012-01-26 16:25:10 -08003397status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398{
3399 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003400 if (mEffectsFactoryHal.get()) {
3401 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3402 } else {
3403 return -ENODEV;
3404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405}
3406
Glenn Kasten5e92a782012-01-30 07:40:52 -08003407status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003408 const effect_uuid_t *pTypeUuid,
3409 uint32_t preferredTypeFlag,
3410 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003412 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3413 return BAD_VALUE;
3414 }
3415
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003417
3418 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003419 return -ENODEV;
3420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003422 status_t status = NO_ERROR;
3423 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3424 // If uuid is specified, request effect descriptor from that.
3425 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3426 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3427 // If uuid is not specified, look for an available implementation
3428 // of the required type instead.
3429
3430 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3431 effect_descriptor_t desc;
3432 desc.flags = 0; // prevent compiler warning
3433
3434 uint32_t numEffects = 0;
3435 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3436 if (status < 0) {
3437 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3438 return status;
3439 }
3440
3441 bool found = false;
3442 for (uint32_t i = 0; i < numEffects; i++) {
3443 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3444 if (status < 0) {
3445 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3446 continue;
3447 }
3448 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3449 // If matching type found save effect descriptor.
3450 found = true;
3451 *descriptor = desc;
3452
3453 // If there's no preferred flag or this descriptor matches the preferred
3454 // flag, success! If this descriptor doesn't match the preferred
3455 // flag, continue enumeration in case a better matching version of this
3456 // effect type is available. Note that this means if no effect with a
3457 // correct flag is found, the descriptor returned will correspond to the
3458 // last effect that at least had a matching type uuid (if any).
3459 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3460 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3461 break;
3462 }
3463 }
3464 }
3465
3466 if (!found) {
3467 status = NAME_NOT_FOUND;
3468 ALOGW("getEffectDescriptor(): Effect not found by type.");
3469 }
3470 } else {
3471 status = BAD_VALUE;
3472 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3473 }
3474 return status;
3475}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003477sp<media::IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 effect_descriptor_t *pDesc,
3479 const sp<IEffectClient>& effectClient,
3480 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003481 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003482 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003483 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003484 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003485 pid_t pid,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003486 bool probe,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 status_t *status,
3488 int *id,
3489 int *enabled)
3490{
3491 status_t lStatus = NO_ERROR;
3492 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494
Eric Laurentb6436272016-12-07 19:24:50 -08003495 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003496 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003497 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3498 ALOGW_IF(pid != -1 && pid != callingPid,
3499 "%s uid %d pid %d tried to pass itself off as pid %d",
3500 __func__, callingUid, callingPid, pid);
3501 pid = callingPid;
3502 }
3503
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003504 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3505 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506
3507 if (pDesc == NULL) {
3508 lStatus = BAD_VALUE;
3509 goto Exit;
3510 }
3511
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003512 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003513 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003514 lStatus = NO_INIT;
3515 goto Exit;
3516 }
3517
Andy Hung6096dcd2019-03-13 13:20:30 -07003518 // check audio settings permission for global effects
3519 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3520 if (!settingsAllowed()) {
3521 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3522 lStatus = PERMISSION_DENIED;
3523 goto Exit;
3524 }
3525 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3526 if (!isAudioServerUid(callingUid)) {
3527 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3528 lStatus = PERMISSION_DENIED;
3529 goto Exit;
3530 }
3531
3532 if (io == AUDIO_IO_HANDLE_NONE) {
3533 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3534 lStatus = BAD_VALUE;
3535 goto Exit;
3536 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003537 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3538 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3539 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3540 lStatus = PERMISSION_DENIED;
3541 goto Exit;
3542 }
Eric Laurent94876032019-11-13 12:45:28 -08003543 if (io != AUDIO_IO_HANDLE_NONE) {
3544 ALOGE("%s: io handle should not be specified for device effect", __func__);
3545 lStatus = BAD_VALUE;
3546 goto Exit;
3547 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003548 } else {
3549 // general sessionId.
3550
3551 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3552 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3553 lStatus = BAD_VALUE;
3554 goto Exit;
3555 }
3556
3557 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3558 // to prevent creating an effect when one doesn't actually have track with that session?
3559 }
3560
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003562 // Get the full effect descriptor from the uuid/type.
3563 // If the session is the output mix, prefer an auxiliary effect,
3564 // otherwise no preference.
3565 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3566 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3567 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3568 if (lStatus < 0) {
3569 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3570 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 }
3572
3573 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003574 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3576 lStatus = INVALID_OPERATION;
3577 goto Exit;
3578 }
3579
Eric Laurent59255e42011-07-27 19:49:51 -07003580 // check recording permission for visualizer
3581 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003582 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003583 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003584 lStatus = PERMISSION_DENIED;
3585 goto Exit;
3586 }
3587
jiabineb3bda02020-06-30 14:07:03 -07003588 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&desc.type);
3589 if (hapticPlaybackRequired
3590 && (sessionId == AUDIO_SESSION_DEVICE
3591 || sessionId == AUDIO_SESSION_OUTPUT_MIX
3592 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
3593 // haptic-generating effect is only valid when the session id is a general session id
3594 lStatus = INVALID_OPERATION;
3595 goto Exit;
3596 }
3597
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003599 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003600 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003601 // if the output returned by getOutputForEffect() is removed before we lock the
3602 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3603 // and we will exit safely
3604 io = AudioSystem::getOutputForEffect(&desc);
3605 ALOGV("createEffect got output %d", io);
3606 }
3607
3608 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609
Eric Laurentb82e6b72019-11-22 17:25:04 -08003610 if (sessionId == AUDIO_SESSION_DEVICE) {
3611 sp<Client> client = registerPid(pid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003612 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003613 handle = mDeviceEffectManager.createEffect_l(
3614 &desc, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003615 enabled, &lStatus, probe);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003616 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3617 // remove local strong reference to Client with mClientLock held
3618 Mutex::Autolock _cl(mClientLock);
3619 client.clear();
3620 } else {
3621 // handle must be valid here, but check again to be safe.
3622 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3623 }
3624 goto Register;
3625 }
3626
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627 // If output is not specified try to find a matching audio session ID in one of the
3628 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003629 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3630 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003631 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3632 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003633 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003634 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003635 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3636 if (io == AUDIO_IO_HANDLE_NONE) {
3637 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003639 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003640 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003641 }
Andy Hung444bb552019-03-14 17:06:39 -07003642
3643 // If you wish to create a Record preprocessing AudioEffect in Java,
3644 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3645 // Otherwise it will fail when created on a Playback thread by legacy
3646 // handling below. Ditto with Mmap, the associated Mmap track must be created
3647 // before creating the AudioEffect or the io handle must be specified.
3648 //
3649 // Detect if the effect is created after an AudioRecord is destroyed.
3650 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3651 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3652 " for session %d no longer exists",
3653 __func__, desc.name, sessionId);
3654 lStatus = PERMISSION_DENIED;
3655 goto Exit;
3656 }
3657
3658 // Legacy handling of creating an effect on an expired or made-up
3659 // session id. We think that it is a Playback effect.
3660 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003661 // If no output thread contains the requested session ID, default to
3662 // first output. The effect chain will be moved to the correct output
3663 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003664 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003665 io = mPlaybackThreads.keyAt(0);
3666 }
Steve Block3856b092011-10-20 11:56:00 +01003667 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003668 } else if (checkPlaybackThread_l(io) != nullptr) {
3669 // allow only one effect chain per sessionId on mPlaybackThreads.
3670 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3671 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07003672 if (io == checkIo) {
3673 if (hapticPlaybackRequired
3674 && mPlaybackThreads.valueAt(i)
3675 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3676 ALOGE("%s: haptic playback thread is required while the required playback "
3677 "thread(io=%d) doesn't support", __func__, (int)io);
3678 lStatus = BAD_VALUE;
3679 goto Exit;
3680 }
3681 continue;
3682 }
Andy Hung1631f062019-03-12 19:39:03 -07003683 const uint32_t sessionType =
3684 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3685 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3686 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3687 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3688 android_errorWriteLog(0x534e4554, "123237974");
3689 lStatus = BAD_VALUE;
3690 goto Exit;
3691 }
3692 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003693 }
3694 ThreadBase *thread = checkRecordThread_l(io);
3695 if (thread == NULL) {
3696 thread = checkPlaybackThread_l(io);
3697 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003698 thread = checkMmapThread_l(io);
3699 if (thread == NULL) {
3700 ALOGE("createEffect() unknown output thread");
3701 lStatus = BAD_VALUE;
3702 goto Exit;
3703 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003704 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003705 } else {
3706 // Check if one effect chain was awaiting for an effect to be created on this
3707 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003708 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003709 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003710 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003711 thread->addEffectChain_l(chain);
3712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003714
Eric Laurent021cf962014-05-13 10:18:14 -07003715 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003717 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003718 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07003719 ThreadBase *oriThread = nullptr;
3720 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3721 ThreadBase *hapticThread = hapticPlaybackThread_l();
3722 if (hapticThread == nullptr) {
3723 ALOGE("%s haptic thread not found while it is required", __func__);
3724 lStatus = INVALID_OPERATION;
3725 goto Exit;
3726 }
3727 if (hapticThread != thread) {
3728 // Force to use haptic thread for haptic-generating effect.
3729 oriThread = thread;
3730 thread = hapticThread;
3731 }
3732 }
Eric Laurentde070132010-07-13 04:45:46 -07003733 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003734 &desc, enabled, &lStatus, pinned, probe);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003735 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003736 // remove local strong reference to Client with mClientLock held
3737 Mutex::Autolock _cl(mClientLock);
3738 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003739 } else {
3740 // handle must be valid here, but check again to be safe.
3741 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07003742 // Invalidate audio session when haptic playback is created.
3743 if (hapticPlaybackRequired && oriThread != nullptr) {
3744 // invalidateTracksForAudioSession will trigger locking the thread.
3745 oriThread->invalidateTracksForAudioSession(sessionId);
3746 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748 }
3749
Eric Laurentb82e6b72019-11-22 17:25:04 -08003750Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003751 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003752 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003753 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003754 if (effect != nullptr) {
3755 status_t rStatus = effect->updatePolicyState();
3756 if (rStatus != NO_ERROR) {
3757 lStatus = rStatus;
3758 }
3759 }
3760 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003761 handle.clear();
3762 }
3763
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003765 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 return handle;
3767}
3768
Glenn Kastend848eb42016-03-08 13:42:11 -08003769status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003770 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003771{
Steve Block3856b092011-10-20 11:56:00 +01003772 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003773 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003774 Mutex::Autolock _l(mLock);
3775 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003776 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003777 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003778 }
Eric Laurentde070132010-07-13 04:45:46 -07003779 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3780 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003781 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003782 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783 }
Eric Laurentde070132010-07-13 04:45:46 -07003784 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3785 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003786 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003787 return BAD_VALUE;
3788 }
3789
3790 Mutex::Autolock _dl(dstThread->mLock);
3791 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003792 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793}
3794
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003795
3796void AudioFlinger::setEffectSuspended(int effectId,
3797 audio_session_t sessionId,
3798 bool suspended)
3799{
3800 Mutex::Autolock _l(mLock);
3801
3802 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3803 if (thread == nullptr) {
3804 return;
3805 }
3806 Mutex::Autolock _sl(thread->mLock);
3807 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3808 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3809}
3810
3811
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003812// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003813status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003814 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003815 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003816{
Steve Block3856b092011-10-20 11:56:00 +01003817 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003818 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003819
Eric Laurent59255e42011-07-27 19:49:51 -07003820 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003821 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003822 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003823 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003824 return INVALID_OPERATION;
3825 }
3826
Eric Laurent4c415062016-06-17 16:14:16 -07003827 // Check whether the destination thread and all effects in the chain are compatible
3828 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003829 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003830 " destination thread %p is not compatible with effects in the chain",
3831 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003832 return INVALID_OPERATION;
3833 }
3834
Eric Laurent39e94f82010-07-28 01:32:47 -07003835 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003836 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003837 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003838 // removed.
3839 srcThread->removeEffectChain_l(chain);
3840
3841 // transfer all effects one by one so that new effect chain is created on new thread with
3842 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003843 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003844 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003845 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003846 Vector< sp<EffectModule> > removed;
3847 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003848 while (effect != 0) {
3849 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003850 removed.add(effect);
3851 status = dstThread->addEffect_l(effect);
3852 if (status != NO_ERROR) {
3853 break;
3854 }
Eric Laurentec35a142011-10-05 17:42:25 -07003855 // 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 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003860 // if the move request is not received from audio policy manager, the effect must be
3861 // re-registered with the new strategy and output
3862 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003863 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003864 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003865 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003866 status = NO_INIT;
3867 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003868 }
3869 strategy = dstChain->strategy();
3870 }
Eric Laurentde070132010-07-13 04:45:46 -07003871 effect = chain->getEffectFromId_l(0);
3872 }
3873
Eric Laurent5baf2af2013-09-12 17:37:00 -07003874 if (status != NO_ERROR) {
3875 for (size_t i = 0; i < removed.size(); i++) {
3876 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003877 }
3878 }
3879
3880 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881}
3882
Eric Laurent6c796322019-04-09 14:13:17 -07003883status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3884 const sp<PlaybackThread>& dstThread,
3885 sp<PlaybackThread> *srcThread)
3886{
3887 status_t status = NO_ERROR;
3888 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003889 sp<PlaybackThread> thread =
3890 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003891
3892 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3893 Mutex::Autolock _dl(dstThread->mLock);
3894 Mutex::Autolock _sl(thread->mLock);
3895 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3896 sp<EffectChain> dstChain;
3897 if (srcChain == 0) {
3898 return INVALID_OPERATION;
3899 }
3900
3901 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3902 if (effect == 0) {
3903 return INVALID_OPERATION;
3904 }
3905 thread->removeEffect_l(effect);
3906 status = dstThread->addEffect_l(effect);
3907 if (status != NO_ERROR) {
3908 thread->addEffect_l(effect);
3909 status = INVALID_OPERATION;
3910 goto Exit;
3911 }
3912
Eric Laurent6b446ce2019-12-13 10:56:31 -08003913 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003914 if (dstChain == 0) {
3915 thread->addEffect_l(effect);
3916 status = INVALID_OPERATION;
3917 }
3918
3919Exit:
3920 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3921 if (effect->state() == EffectModule::ACTIVE ||
3922 effect->state() == EffectModule::STOPPING) {
3923 effect->start();
3924 }
3925 }
3926
3927 if (status == NO_ERROR && srcThread != nullptr) {
3928 *srcThread = thread;
3929 }
3930 return status;
3931}
3932
Eric Laurent5baf2af2013-09-12 17:37:00 -07003933bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003934{
3935 if (mGlobalEffectEnableTime != 0 &&
3936 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3937 return true;
3938 }
3939
3940 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3941 sp<EffectChain> ec =
3942 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003943 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003944 return true;
3945 }
3946 }
3947 return false;
3948}
3949
Eric Laurent5baf2af2013-09-12 17:37:00 -07003950void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003951{
3952 Mutex::Autolock _l(mLock);
3953
3954 mGlobalEffectEnableTime = systemTime();
3955
3956 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3957 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3958 if (t->mType == ThreadBase::OFFLOAD) {
3959 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3960 }
3961 }
3962
3963}
3964
Eric Laurentaaa44472014-09-12 17:41:50 -07003965status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3966{
Eric Laurentd8365c52017-07-16 15:27:05 -07003967 // clear possible suspended state before parking the chain so that it starts in default state
3968 // when attached to a new record thread
3969 chain->setEffectSuspended_l(FX_IID_AEC, false);
3970 chain->setEffectSuspended_l(FX_IID_NS, false);
3971
Glenn Kastend848eb42016-03-08 13:42:11 -08003972 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003973 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003974 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003975 if (index >= 0) {
3976 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3977 return ALREADY_EXISTS;
3978 }
3979 mOrphanEffectChains.add(session, chain);
3980 return NO_ERROR;
3981}
3982
3983sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3984{
3985 sp<EffectChain> chain;
3986 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003987 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003988 if (index >= 0) {
3989 chain = mOrphanEffectChains.valueAt(index);
3990 mOrphanEffectChains.removeItemsAt(index);
3991 }
3992 return chain;
3993}
3994
3995bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3996{
3997 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003998 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003999 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004000 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004001 if (index >= 0) {
4002 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08004003 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004004 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004005 mOrphanEffectChains.removeItemsAt(index);
4006 }
4007 return true;
4008 }
4009 return false;
4010}
4011
4012
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013// ----------------------------------------------------------------------------
4014
4015status_t AudioFlinger::onTransact(
4016 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4017{
4018 return BnAudioFlinger::onTransact(code, data, reply, flags);
4019}
4020
Glenn Kasten63238ef2015-03-02 15:50:29 -08004021} // namespace android