blob: e589eb974477adb4f9f8fc4b486d3db5572efa46 [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-Tsvi10dc0a62020-09-18 11:31:55 -070025#define VALUE_OR_FATAL(result) \
26 ({ auto _tmp = (result); \
27 LOG_ALWAYS_FATAL_IF(!_tmp.ok(), \
28 "Failed result (%d)", \
29 _tmp.error()); \
30 _tmp.value(); })
31
Glenn Kasten153b9fe2013-07-15 11:23:36 -070032#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080033#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <math.h>
35#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070036#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <sys/time.h>
38#include <sys/resource.h>
Mikhail Naganov88b30d22020-03-09 19:43:13 +000039#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
jiabin57303cc2018-12-18 15:45:57 -080041#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080042#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/IServiceManager.h>
44#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070045#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070047#include <media/audiohal/DeviceHalInterface.h>
48#include <media/audiohal/DevicesFactoryHalInterface.h>
49#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070050#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080051#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070052#include <media/TypeConverter.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070053#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <utils/String16.h>
55#include <utils/threads.h>
56
Steven Morelandf0c02ce2018-02-23 14:53:55 -080057#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <cutils/properties.h>
59
Dima Zavin64760242011-05-11 14:15:23 -070060#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070061#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070064#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Andy Hung6770c6f2015-04-07 13:43:36 -070066#include <media/AudioResamplerPublic.h>
67
Mikhail Naganov9fe94012016-10-14 14:57:40 -070068#include <system/audio_effects/effect_visualizer.h>
69#include <system/audio_effects/effect_ns.h>
70#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070071#include <system/audio_effects/effect_hapticgenerator.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
Glenn Kasten3b21c502011-12-15 09:52:39 -080073#include <audio_utils/primitives.h>
74
Eric Laurentfeb0db62011-07-22 09:04:31 -070075#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080076
Glenn Kasten9e58b552013-01-18 15:09:48 -080077#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070078#include <media/AidlConversion.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080079#include <media/nbaio/Pipe.h>
80#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080081#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070082#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070083#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070084#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070085#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080086
rago3bd1c872016-09-26 12:58:14 -070087//#define BUFLOG_NDEBUG 0
88#include <BufLog.h>
89
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080090#include "TypedLogger.h"
91
Mathias Agopian65ab4712010-07-14 17:59:35 -070092// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
John Grossman1c345192012-03-27 14:00:17 -070094// Note: the following macro is used for extremely verbose logging message. In
95// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
96// 0; but one side effect of this is to turn all LOGV's as well. Some messages
97// are so verbose that we want to suppress them even when we have ALOG_ASSERT
98// turned on. Do not uncomment the #def below unless you really know what you
99// are doing and want to see all of the extremely verbose messages.
100//#define VERY_VERY_VERBOSE_LOGGING
101#ifdef VERY_VERY_VERBOSE_LOGGING
102#define ALOGVV ALOGV
103#else
104#define ALOGVV(a...) do { } while(0)
105#endif
Eric Laurentde070132010-07-13 04:45:46 -0700106
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107namespace android {
108
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700109using media::IEffectClient;
110
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700113static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700114static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115
Glenn Kasten58912562012-04-03 10:45:00 -0700116
John Grossman4ff14ba2012-02-08 16:37:41 -0800117nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800118
Eric Laurent81784c32012-11-19 14:55:58 -0800119uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700120
Eric Laurent813e2a72013-08-31 12:59:48 -0700121// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
122// we define a minimum time during which a global effect is considered enabled.
123static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
124
Eric Laurentfc235202016-12-20 18:48:17 -0800125Mutex gLock;
126wp<AudioFlinger> gAudioFlinger;
127
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700128// Keep a strong reference to media.log service around forever.
129// The service is within our parent process so it can never die in a way that we could observe.
130// These two variables are const after initialization.
131static sp<IBinder> sMediaLogServiceAsBinder;
132static sp<IMediaLogService> sMediaLogService;
133
134static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
135
136static void sMediaLogInit()
137{
138 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
139 if (sMediaLogServiceAsBinder != 0) {
140 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
141 }
142}
143
jiabin57303cc2018-12-18 15:45:57 -0800144// Keep a strong reference to external vibrator service
145static sp<os::IExternalVibratorService> sExternalVibratorService;
146
147static sp<os::IExternalVibratorService> getExternalVibratorService() {
148 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700149 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800150 String16("external_vibrator_service"));
151 if (binder != 0) {
152 sExternalVibratorService =
153 interface_cast<os::IExternalVibratorService>(binder);
154 }
155 }
156 return sExternalVibratorService;
157}
158
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000159class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
160 public:
161 void onNewDevicesAvailable() override {
162 // Start a detached thread to execute notification in parallel.
163 // This is done to prevent mutual blocking of audio_flinger and
164 // audio_policy services during system initialization.
165 std::thread notifier([]() {
166 AudioSystem::onNewAudioModulesAvailable();
167 });
168 notifier.detach();
169 }
170};
171
Mathias Agopian65ab4712010-07-14 17:59:35 -0700172// ----------------------------------------------------------------------------
173
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700174std::string formatToString(audio_format_t format) {
175 std::string result;
176 FormatConverter::toString(format, result);
177 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800178}
179
Mathias Agopian65ab4712010-07-14 17:59:35 -0700180// ----------------------------------------------------------------------------
181
182AudioFlinger::AudioFlinger()
183 : BnAudioFlinger(),
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800184 mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800185 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800186 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700187 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800188 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800189 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700190 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800191 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700192 mBtNrecIsOff(false),
193 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700194 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800195 mTotalMemory(0),
196 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700197 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700198 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800199 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700200 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201{
Glenn Kastend2e67e12016-04-11 08:26:37 -0700202 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
203 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
204 // zero ID has a special meaning, so unavailable
205 mNextUniqueIds[use] = AUDIO_UNIQUE_ID_USE_MAX;
206 }
207
Eric Laurent94ca1142020-10-07 10:45:20 -0700208#if 1
209 // FIXME See bug 165702394 and bug 168511485
210 const bool doLog = false;
211#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800212 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700213#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800214 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800215 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
216 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700217 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800218 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700219
Wei Jia3f273d12015-11-24 09:06:49 -0800220 // reset battery stats.
221 // if the audio service has crashed, battery stats could be left
222 // in bad state, reset the state upon service start.
223 BatteryNotifier::getInstance().noteResetAudio();
224
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700225 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700226 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
227
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800228 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700229 std::vector<pid_t> halPids;
230 mDevicesFactoryHal->getHalPids(&halPids);
231 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800232
233 // Notify that we have started (also called when audioserver service restarts)
234 mediametrics::LogItem(mMetricsId)
235 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
236 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700237}
238
239void AudioFlinger::onFirstRef()
240{
Eric Laurent93575202011-01-18 18:39:02 -0800241 Mutex::Autolock _l(mLock);
242
Dima Zavin799a70e2011-04-18 16:57:27 -0700243 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800244 char val_str[PROPERTY_VALUE_MAX] = { 0 };
245 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
246 uint32_t int_val;
247 if (1 == sscanf(val_str, "%u", &int_val)) {
248 mStandbyTimeInNsecs = milliseconds(int_val);
249 ALOGI("Using %u mSec as standby time.", int_val);
250 } else {
251 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
252 ALOGI("Using default %u mSec as standby time.",
253 (uint32_t)(mStandbyTimeInNsecs / 1000000));
254 }
255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256
Eric Laurenta4c5a552012-03-29 10:12:40 -0700257 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800258
259 gAudioFlinger = this;
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000260
261 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
262 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263}
264
Eric Laurent42896a02019-09-27 15:40:33 -0700265status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
266 TimeCheck::setAudioHalPids(pids);
267 return NO_ERROR;
268}
269
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270AudioFlinger::~AudioFlinger()
271{
272 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700273 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700274 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275 }
276 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700277 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700278 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279 }
Andy Hungb4946b62019-03-14 11:19:28 -0700280 while (!mMmapThreads.isEmpty()) {
281 const audio_io_handle_t io = mMmapThreads.keyAt(0);
282 if (mMmapThreads.valueAt(0)->isOutput()) {
283 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
284 } else {
285 closeInput_nonvirtual(io); // removes entry from mMmapThreads
286 }
287 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700288
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800289 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
290 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700291 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700292 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700293
294 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700295 if (sMediaLogService != 0) {
296 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
297 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
298 mUnregisteredWriters.pop();
299 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700300 }
301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302}
303
Eric Laurentfc235202016-12-20 18:48:17 -0800304//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800305__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800306status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
307 const audio_attributes_t *attr,
308 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700309 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800310 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800311 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800312 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700313 sp<MmapStreamInterface>& interface,
314 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800315{
316 sp<AudioFlinger> af;
317 {
318 Mutex::Autolock _l(gLock);
319 af = gAudioFlinger.promote();
320 }
321 status_t ret = NO_INIT;
322 if (af != 0) {
323 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800324 direction, attr, config, client, deviceId,
325 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800326 }
327 return ret;
328}
329
Eric Laurent6acd1d42017-01-04 14:23:29 -0800330status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
331 const audio_attributes_t *attr,
332 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700333 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800334 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800335 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800336 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700337 sp<MmapStreamInterface>& interface,
338 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800339{
340 status_t ret = initCheck();
341 if (ret != NO_ERROR) {
342 return ret;
343 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800344 audio_session_t actualSessionId = *sessionId;
345 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
346 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
347 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800348 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700349 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800350 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700351 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800352 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
353 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
354 fullConfig.sample_rate = config->sample_rate;
355 fullConfig.channel_mask = config->channel_mask;
356 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800357 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700358
359 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800360 actualSessionId,
Nadav Bar766fb022018-01-07 12:18:03 +0200361 &streamType, client.clientPid, client.clientUid,
Ricardo Correa57a37692020-03-23 17:27:25 -0700362 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800363 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
364 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800365 deviceId, &portId, &secondaryOutputs);
366 ALOGW_IF(!secondaryOutputs.empty(),
367 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800368 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700369 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700370 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800371 actualSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800372 client.clientPid,
373 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -0800374 client.packageName,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800375 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700376 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800377 }
378 if (ret != NO_ERROR) {
379 return ret;
380 }
381
382 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
383 // audio policy manager and we can retrieve it
384 sp<MmapThread> thread = mMmapThreads.valueFor(io);
385 if (thread != 0) {
386 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700387 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700388 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800389 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800390 config->sample_rate = thread->sampleRate();
391 config->channel_mask = thread->channelMask();
392 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800393 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700394 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700395 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700396 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800397 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700398 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800399 ret = NO_INIT;
400 }
401
402 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
403
Eric Laurentfc235202016-12-20 18:48:17 -0800404 return ret;
405}
406
jiabin57303cc2018-12-18 15:45:57 -0800407/* static */
408int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
409 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
410 if (evs != 0) {
411 int32_t ret;
412 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
413 if (status.isOk()) {
414 return ret;
415 }
416 }
jiabine70bc7f2020-06-30 22:07:55 -0700417 return static_cast<int>(os::HapticScale::MUTE);
jiabin57303cc2018-12-18 15:45:57 -0800418}
419
420/* static */
421void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
422 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
423 if (evs != 0) {
424 evs->onExternalVibrationStop(*externalVibration);
425 }
426}
427
Eric Laurentb82e6b72019-11-22 17:25:04 -0800428status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
429 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700430 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800431 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
432 if (audioHwDevice == nullptr) {
433 return NO_INIT;
434 }
435 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
436}
437
438status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
439 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700440 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800441 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
442 if (audioHwDevice == nullptr) {
443 return NO_INIT;
444 }
445 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
446}
447
Eric Laurenta4c5a552012-03-29 10:12:40 -0700448static const char * const audio_interfaces[] = {
449 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
450 AUDIO_HARDWARE_MODULE_ID_A2DP,
451 AUDIO_HARDWARE_MODULE_ID_USB,
452};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700453
Phil Burk062e67a2015-02-11 13:40:50 -0800454AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700455 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700456 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700457{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700458 // if module is 0, the request comes from an old policy manager and we should load
459 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700460 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700461 if (module == 0) {
462 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700463 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700464 loadHwModule_l(audio_interfaces[i]);
465 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700466 // then try to find a module supporting the requested device.
467 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
468 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700469 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
470 uint32_t supportedDevices;
471 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700472 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700473 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700474 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700475 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700476 } else {
477 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700478 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
479 if (audioHwDevice != NULL) {
480 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700481 }
482 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700483
Dima Zavin799a70e2011-04-18 16:57:27 -0700484 return NULL;
485}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486
Glenn Kasten0f11b512014-01-31 16:18:54 -0800487void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700488{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 String8 result;
490
491 result.append("Clients:\n");
492 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800493 sp<Client> client = mClients.valueAt(i).promote();
494 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800495 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 }
497 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700498
Eric Laurentd1b28d42013-09-18 18:47:13 -0700499 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800500 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700501 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800502 const pid_t pid = mNotificationClients[i]->getPid();
503 const uid_t uid = mNotificationClients[i]->getUid();
504 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
505 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700506 }
507
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700508 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800509 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700510 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
511 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800512 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
513 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
514 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517}
518
519
Glenn Kasten0f11b512014-01-31 16:18:54 -0800520void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521{
522 const size_t SIZE = 256;
523 char buffer[SIZE];
524 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800525 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526
John Grossman4ff14ba2012-02-08 16:37:41 -0800527 snprintf(buffer, SIZE, "Hardware status: %d\n"
528 "Standby Time mSec: %u\n",
529 hardwareStatus,
530 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 result.append(buffer);
532 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533}
534
Glenn Kasten0f11b512014-01-31 16:18:54 -0800535void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536{
537 const size_t SIZE = 256;
538 char buffer[SIZE];
539 String8 result;
540 snprintf(buffer, SIZE, "Permission Denial: "
541 "can't dump AudioFlinger from pid=%d, uid=%d\n",
542 IPCThreadState::self()->getCallingPid(),
543 IPCThreadState::self()->getCallingUid());
544 result.append(buffer);
545 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546}
547
Eric Laurent81784c32012-11-19 14:55:58 -0800548bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700550 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
551 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552}
553
554status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
555{
Glenn Kasten44deb052012-02-05 18:09:08 -0800556 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 dumpPermissionDenial(fd, args);
558 } else {
559 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800560 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 if (!hardwareLocked) {
562 String8 result(kHardwareLockedString);
563 write(fd, result.string(), result.size());
564 } else {
565 mHardwareLock.unlock();
566 }
567
Eric Tan7b651152018-07-13 10:17:19 -0700568 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569
570 // failed to lock - AudioFlinger is probably deadlocked
571 if (!locked) {
572 String8 result(kDeadlockedString);
573 write(fd, result.string(), result.size());
574 }
575
Eric Laurent021cf962014-05-13 10:18:14 -0700576 bool clientLocked = dumpTryLock(mClientLock);
577 if (!clientLocked) {
578 String8 result(kClientLockedString);
579 write(fd, result.string(), result.size());
580 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700581
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700582 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700583 mEffectsFactoryHal->dumpEffects(fd);
584 } else {
585 String8 result(kNoEffectsFactory);
586 write(fd, result.string(), result.size());
587 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700588
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700590 if (clientLocked) {
591 mClientLock.unlock();
592 }
593
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 dumpInternals(fd, args);
595
596 // dump playback threads
597 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
598 mPlaybackThreads.valueAt(i)->dump(fd, args);
599 }
600
601 // dump record threads
602 for (size_t i = 0; i < mRecordThreads.size(); i++) {
603 mRecordThreads.valueAt(i)->dump(fd, args);
604 }
605
Eric Laurent6acd1d42017-01-04 14:23:29 -0800606 // dump mmap threads
607 for (size_t i = 0; i < mMmapThreads.size(); i++) {
608 mMmapThreads.valueAt(i)->dump(fd, args);
609 }
610
Eric Laurentaaa44472014-09-12 17:41:50 -0700611 // dump orphan effect chains
612 if (mOrphanEffectChains.size() != 0) {
613 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
614 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
615 mOrphanEffectChains.valueAt(i)->dump(fd, args);
616 }
617 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700618 // dump all hardware devs
619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700620 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
621 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700623
Mikhail Naganov201369b2018-05-16 16:52:32 -0700624 mPatchPanel.dump(fd);
625
Eric Laurentb82e6b72019-11-22 17:25:04 -0800626 mDeviceEffectManager.dump(fd);
627
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700628 // dump external setParameters
629 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
630 dprintf(fd, "\n%s setParameters:\n", name);
631 logger.dump(fd, " " /* prefix */);
632 };
633 dumpLogger(mRejectedSetParameterLog, "Rejected");
634 dumpLogger(mAppSetParameterLog, "App");
635 dumpLogger(mSystemSetParameterLog, "System");
636
Andy Hunga8115dc2018-08-24 15:51:59 -0700637 // dump historical threads in the last 10 seconds
638 const std::string threadLog = mThreadLog.dumpToString(
639 "Historical Thread Log ", 0 /* lines */,
640 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
641 write(fd, threadLog.c_str(), threadLog.size());
642
rago3bd1c872016-09-26 12:58:14 -0700643 BUFLOG_RESET;
644
Glenn Kastend65d73c2012-06-22 17:21:07 -0700645 if (locked) {
646 mLock.unlock();
647 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800648
Andy Hung8946a282018-04-19 20:04:56 -0700649#ifdef TEE_SINK
650 // NBAIO_Tee dump is safe to call outside of AF lock.
651 NBAIO_Tee::dumpAll(fd, "_DUMP");
652#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800653 // append a copy of media.log here by forwarding fd to it, but don't attempt
654 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700655 if (sMediaLogServiceAsBinder != 0) {
656 dprintf(fd, "\nmedia.log:\n");
657 Vector<String16> args;
658 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800659 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700660
661 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700662 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700663 bool unreachableMemory = false;
664 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700665 if (arg == String16("-m")) {
666 dumpMem = true;
667 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700668 unreachableMemory = true;
669 }
670 }
671
Andy Hung07b745e2016-05-23 16:21:07 -0700672 if (dumpMem) {
673 dprintf(fd, "\nDumping memory:\n");
674 std::string s = dumpMemoryAddresses(100 /* limit */);
675 write(fd, s.c_str(), s.size());
676 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700677 if (unreachableMemory) {
678 dprintf(fd, "\nDumping unreachable memory:\n");
679 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700680 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700681 write(fd, s.c_str(), s.size());
682 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683 }
684 return NO_ERROR;
685}
686
Eric Laurent021cf962014-05-13 10:18:14 -0700687sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800688{
Eric Laurent021cf962014-05-13 10:18:14 -0700689 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800690 // If pid is already in the mClients wp<> map, then use that entry
691 // (for which promote() is always != 0), otherwise create a new entry and Client.
692 sp<Client> client = mClients.valueFor(pid).promote();
693 if (client == 0) {
694 client = new Client(this, pid);
695 mClients.add(pid, client);
696 }
697
698 return client;
699}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700
Glenn Kasten9e58b552013-01-18 15:09:48 -0800701sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
702{
Jiabin Huang60766082020-07-28 22:03:56 +0000703 // If there is no memory allocated for logs, return a no-op writer that does nothing.
704 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700705 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800706 return new NBLog::Writer();
707 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700708 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
709 // If allocation fails, consult the vector of previously unregistered writers
710 // and garbage-collect one or more them until an allocation succeeds
711 if (shared == 0) {
712 Mutex::Autolock _l(mUnregisteredWritersLock);
713 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
714 {
715 // Pick the oldest stale writer to garbage-collect
716 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
717 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700718 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700719 // Now the media.log remote reference to IMemory is gone. When our last local
720 // reference to IMemory also drops to zero at end of this block,
721 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
722 }
723 // Re-attempt the allocation
724 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
725 if (shared != 0) {
726 goto success;
727 }
728 }
729 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000730 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700731 return new NBLog::Writer();
732 }
733success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700734 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800735 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
736 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700737 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800738 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800739}
740
741void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
742{
Glenn Kasten685ef092013-02-04 08:15:34 -0800743 if (writer == 0) {
744 return;
745 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800746 sp<IMemory> iMemory(writer->getIMemory());
747 if (iMemory == 0) {
748 return;
749 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700750 // Rather than removing the writer immediately, append it to a queue of old writers to
751 // be garbage-collected later. This allows us to continue to view old logs for a while.
752 Mutex::Autolock _l(mUnregisteredWritersLock);
753 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800754}
755
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756// IAudioFlinger interface
757
Eric Laurent21da6472017-11-09 16:29:26 -0800758sp<IAudioTrack> AudioFlinger::createTrack(const CreateTrackInput& input,
759 CreateTrackOutput& output,
760 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761{
762 sp<PlaybackThread::Track> track;
763 sp<TrackHandle> trackHandle;
764 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800766 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800767 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800768 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769
Eric Laurent21da6472017-11-09 16:29:26 -0800770 bool updatePid = (input.clientInfo.clientPid == -1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700771 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent21da6472017-11-09 16:29:26 -0800772 uid_t clientUid = input.clientInfo.clientUid;
Eric Laurent6c796322019-04-09 14:13:17 -0700773 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
774 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700775 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700776
Andy Hung4ef19fa2018-05-15 19:35:29 -0700777 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800778 ALOGW_IF(clientUid != callingUid,
779 "%s uid %d tried to pass itself off as %d",
780 __FUNCTION__, callingUid, clientUid);
781 clientUid = callingUid;
782 updatePid = true;
783 }
784 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -0700785 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800786 if (updatePid) {
Eric Laurent21da6472017-11-09 16:29:26 -0800787 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700788 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800789 __func__, callingUid, callingPid, clientPid);
790 clientPid = callingPid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700791 }
792
Eric Laurent21da6472017-11-09 16:29:26 -0800793 audio_session_t sessionId = input.sessionId;
794 if (sessionId == AUDIO_SESSION_ALLOCATE) {
795 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800796 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
797 lStatus = BAD_VALUE;
798 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800799 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800800
Eric Laurent21da6472017-11-09 16:29:26 -0800801 output.sessionId = sessionId;
802 output.outputId = AUDIO_IO_HANDLE_NONE;
803 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700804 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Ricardo Correa57a37692020-03-23 17:27:25 -0700805 clientPid, clientUid, &input.config, input.flags,
806 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800807
808 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
809 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
810 goto Exit;
811 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800812 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
813 // but if someone uses binder directly they could bypass that and cause us to crash
814 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000815 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 lStatus = BAD_VALUE;
817 goto Exit;
818 }
819
Glenn Kasten53b5d092014-02-05 10:00:23 -0800820 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800821 if (!audio_is_output_channel(input.config.channel_mask)) {
822 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800823 lStatus = BAD_VALUE;
824 goto Exit;
825 }
826
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700827 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800828 if (!audio_is_valid_format(input.config.format)) {
829 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700830 lStatus = BAD_VALUE;
831 goto Exit;
832 }
833
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 {
835 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800836 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800838 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839 lStatus = BAD_VALUE;
840 goto Exit;
841 }
842
Eric Laurent21da6472017-11-09 16:29:26 -0800843 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844
Glenn Kastene848bd92014-03-13 15:00:32 -0700845 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800846 // check if an effect chain with the same session ID is present on another
847 // output thread and move it here.
848 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
849 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
850 if (mPlaybackThreads.keyAt(i) != output.outputId) {
851 uint32_t sessions = t->hasAudioSession(sessionId);
852 if (sessions & ThreadBase::EFFECT_SESSION) {
853 effectThread = t.get();
854 break;
Eric Laurentde070132010-07-13 04:45:46 -0700855 }
856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 }
Eric Laurent21da6472017-11-09 16:29:26 -0800858 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859
Eric Laurent21da6472017-11-09 16:29:26 -0800860 output.sampleRate = input.config.sample_rate;
861 output.frameCount = input.frameCount;
862 output.notificationFrameCount = input.notificationFrameCount;
863 output.flags = input.flags;
864
Eric Laurent42984412019-05-09 17:57:03 -0700865 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700866 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800867 &output.frameCount, &output.notificationFrameCount,
868 input.notificationsPerBuffer, input.speed,
869 input.sharedBuffer, sessionId, &output.flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700870 callingPid, input.clientInfo.clientTid, clientUid,
Colin Crossb8a9dbb2020-08-27 04:12:26 +0000871 &lStatus, portId, input.audioTrackCallback,
872 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800873 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700874 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700875
Eric Laurent21da6472017-11-09 16:29:26 -0800876 output.afFrameCount = thread->frameCount();
877 output.afSampleRate = thread->sampleRate();
878 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800879 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800880
Kevin Rocard153f92d2018-12-18 18:33:28 -0800881 if (lStatus == NO_ERROR) {
882 // Connect secondary outputs. Failure on a secondary output must not imped the primary
883 // Any secondary output setup failure will lead to a desync between the AP and AF until
884 // the track is destroyed.
885 TeePatches teePatches;
886 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
887 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
888 if (secondaryThread == NULL) {
889 ALOGE("no playback thread found for secondary output %d", output.outputId);
890 continue;
891 }
892
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100893 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
894 / thread->sampleRate();
895 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
896 / secondaryThread->sampleRate();
897 // If the secondary output has just been opened, the first secondaryThread write
898 // will not block as it will fill the empty startup buffer of the HAL,
899 // so a second sink buffer needs to be ready for the immediate next blocking write.
900 // Additionally, have a margin of one main thread buffer as the scheduling jitter
901 // can reorder the writes (eg if thread A&B have the same write intervale,
902 // the scheduler could schedule AB...BA)
903 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
904 // Total secondary output buffer must be at least as the read frames plus
905 // the margin of a few buffers on both sides in case the
906 // threads scheduling has some jitter.
907 // That value should not impact latency as the secondary track is started before
908 // its buffer is full, see frameCountToBeReady.
909 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
910 // The frameCount should also not be smaller than the secondary thread min frame
911 // count
912 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
913 [&] { Mutex::Autolock _l(secondaryThread->mLock);
914 return secondaryThread->latency_l(); }(),
915 secondaryThread->mNormalFrameCount,
916 secondaryThread->mSampleRate,
917 output.sampleRate,
918 input.speed);
919 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800920
921 using namespace std::chrono_literals;
922 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
923 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
924 output.sampleRate,
925 inChannelMask,
926 input.config.format,
927 frameCount,
928 NULL /* buffer */,
929 (size_t)0 /* bufferSize */,
930 AUDIO_INPUT_FLAG_DIRECT,
931 0ns /* timeout */);
932 status_t status = patchRecord->initCheck();
933 if (status != NO_ERROR) {
934 ALOGE("Secondary output patchRecord init failed: %d", status);
935 continue;
936 }
Andy Hungae22b482019-05-09 15:38:55 -0700937
938 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
939 // for fast usage: thread has fast mixer, sample rate matches, etc.;
940 // for now, we exclude fast tracks by removing the Fast flag.
941 const audio_output_flags_t outputFlags =
942 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800943 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
944 streamType,
945 output.sampleRate,
946 input.config.channel_mask,
947 input.config.format,
948 frameCount,
949 patchRecord->buffer(),
950 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -0700951 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100952 0ns /* timeout */,
953 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800954 status = patchTrack->initCheck();
955 if (status != NO_ERROR) {
956 ALOGE("Secondary output patchTrack init failed: %d", status);
957 continue;
958 }
959 teePatches.push_back({patchRecord, patchTrack});
960 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -0800961 // In case the downstream patchTrack on the secondaryThread temporarily outlives
962 // our created track, ensure the corresponding patchRecord is still alive.
963 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
964 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800965 }
966 track->setTeePatches(std::move(teePatches));
967 }
968
Eric Laurent39e94f82010-07-28 01:32:47 -0700969 // move effect chain to this output thread if an effect on same session was waiting
970 // for a track to be created
971 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -0700972 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -0700973 Mutex::Autolock _dl(thread->mLock);
974 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -0700975 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
976 effectThreadId = thread->id();
977 effectIds = thread->getEffectIds_l(sessionId);
978 }
Eric Laurent39e94f82010-07-28 01:32:47 -0700979 }
Eric Laurenta011e352012-03-29 15:51:43 -0700980
981 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -0700982 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -0800983 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -0700984 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700985 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700986 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700987 } else {
988 mPendingSyncEvents[i]->cancel();
989 }
Eric Laurenta011e352012-03-29 15:51:43 -0700990 mPendingSyncEvents.removeAt(i);
991 i--;
992 }
993 }
994 }
Glenn Kastene198c362013-08-13 09:13:36 -0700995
Eric Laurent21da6472017-11-09 16:29:26 -0800996 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997 }
Glenn Kastene198c362013-08-13 09:13:36 -0700998
Glenn Kasten3ef14ef2014-03-13 15:08:51 -0700999 if (lStatus != NO_ERROR) {
1000 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001001 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001002 // Don't hold mClientLock when releasing the reference on the track as the
1003 // destructor will acquire it.
1004 {
1005 Mutex::Autolock _cl(mClientLock);
1006 client.clear();
1007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001009 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 }
1011
Eric Laurent6c796322019-04-09 14:13:17 -07001012 // effectThreadId is not NONE if an effect chain corresponding to the track session
1013 // was found on another thread and must be moved on this thread
1014 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1015 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1016 }
1017
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001018 // return handle to client
1019 trackHandle = new TrackHandle(track);
1020
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001022 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001023 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001024 }
Glenn Kasten9156ef32013-08-06 15:39:08 -07001025 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 return trackHandle;
1027}
1028
Glenn Kasten2c073da2016-02-26 09:14:08 -08001029uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030{
1031 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001032 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001034 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 return 0;
1036 }
1037 return thread->sampleRate();
1038}
1039
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001040audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041{
1042 Mutex::Autolock _l(mLock);
1043 PlaybackThread *thread = checkPlaybackThread_l(output);
1044 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001045 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001046 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 }
1048 return thread->format();
1049}
1050
Glenn Kasten2c073da2016-02-26 09:14:08 -08001051size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052{
1053 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001054 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001056 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 return 0;
1058 }
Glenn Kasten58912562012-04-03 10:45:00 -07001059 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1060 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 return thread->frameCount();
1062}
1063
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001064size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1065{
1066 Mutex::Autolock _l(mLock);
1067 ThreadBase *thread = checkThread_l(ioHandle);
1068 if (thread == NULL) {
1069 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1070 return 0;
1071 }
1072 return thread->frameCountHAL();
1073}
1074
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001075uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076{
1077 Mutex::Autolock _l(mLock);
1078 PlaybackThread *thread = checkPlaybackThread_l(output);
1079 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001080 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 return 0;
1082 }
1083 return thread->latency();
1084}
1085
1086status_t AudioFlinger::setMasterVolume(float value)
1087{
Eric Laurenta1884f92011-08-23 08:25:03 -07001088 status_t ret = initCheck();
1089 if (ret != NO_ERROR) {
1090 return ret;
1091 }
1092
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 // check calling permissions
1094 if (!settingsAllowed()) {
1095 return PERMISSION_DENIED;
1096 }
1097
Eric Laurenta4c5a552012-03-29 10:12:40 -07001098 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001099 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001100
John Grossmanee578c02012-07-23 17:05:46 -07001101 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001102 {
John Grossmanee578c02012-07-23 17:05:46 -07001103 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001104 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1105 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001106
Eric Laurent00abf0d2020-04-22 19:28:22 -07001107 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1108 if (dev->canSetMasterVolume()) {
1109 dev->hwDevice()->setMasterVolume(value);
1110 }
1111 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113 }
John Grossmanee578c02012-07-23 17:05:46 -07001114 // Now set the master volume in each playback thread. Playback threads
1115 // assigned to HALs which do not have master volume support will apply
1116 // master volume during the mix operation. Threads with HALs which do
1117 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001118 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1119 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1120 continue;
1121 }
John Grossmanee578c02012-07-23 17:05:46 -07001122 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124
1125 return NO_ERROR;
1126}
1127
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001128status_t AudioFlinger::setMasterBalance(float balance)
1129{
1130 status_t ret = initCheck();
1131 if (ret != NO_ERROR) {
1132 return ret;
1133 }
1134
1135 // check calling permissions
1136 if (!settingsAllowed()) {
1137 return PERMISSION_DENIED;
1138 }
1139
1140 // check range
1141 if (isnan(balance) || fabs(balance) > 1.f) {
1142 return BAD_VALUE;
1143 }
1144
1145 Mutex::Autolock _l(mLock);
1146
1147 // short cut.
1148 if (mMasterBalance == balance) return NO_ERROR;
1149
1150 mMasterBalance = balance;
1151
1152 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1153 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1154 continue;
1155 }
1156 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1157 }
1158
1159 return NO_ERROR;
1160}
1161
Glenn Kastenf78aee72012-01-04 11:00:47 -08001162status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163{
Eric Laurenta1884f92011-08-23 08:25:03 -07001164 status_t ret = initCheck();
1165 if (ret != NO_ERROR) {
1166 return ret;
1167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168
1169 // check calling permissions
1170 if (!settingsAllowed()) {
1171 return PERMISSION_DENIED;
1172 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001173 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001174 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 return BAD_VALUE;
1176 }
1177
1178 { // scope for the lock
1179 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001180 if (mPrimaryHardwareDev == nullptr) {
1181 return INVALID_OPERATION;
1182 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001183 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001185 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 mHardwareStatus = AUDIO_HW_IDLE;
1187 }
1188
1189 if (NO_ERROR == ret) {
1190 Mutex::Autolock _l(mLock);
1191 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001192 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001193 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 }
1195
Joey Poomarin52989982020-03-05 17:40:49 +08001196 mediametrics::LogItem(mMetricsId)
1197 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1198 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1199 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 return ret;
1201}
1202
1203status_t AudioFlinger::setMicMute(bool state)
1204{
Eric Laurenta1884f92011-08-23 08:25:03 -07001205 status_t ret = initCheck();
1206 if (ret != NO_ERROR) {
1207 return ret;
1208 }
1209
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 // check calling permissions
1211 if (!settingsAllowed()) {
1212 return PERMISSION_DENIED;
1213 }
1214
1215 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001216 if (mPrimaryHardwareDev == nullptr) {
1217 return INVALID_OPERATION;
1218 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001219 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1220 if (primaryDev == nullptr) {
1221 ALOGW("%s: no primary HAL device", __func__);
1222 return INVALID_OPERATION;
1223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001225 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001226 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001227 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001228 if (dev != primaryDev) {
1229 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001230 }
1231 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001233 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 return ret;
1235}
1236
1237bool AudioFlinger::getMicMute() const
1238{
Eric Laurenta1884f92011-08-23 08:25:03 -07001239 status_t ret = initCheck();
1240 if (ret != NO_ERROR) {
1241 return false;
1242 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001243 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001244 if (mPrimaryHardwareDev == nullptr) {
1245 return false;
1246 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001247 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1248 if (primaryDev == nullptr) {
1249 ALOGW("%s: no primary HAL device", __func__);
1250 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001251 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001252 bool state;
1253 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1254 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001256 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1257 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001258}
1259
Eric Laurent5ada82e2019-08-29 17:53:54 -07001260void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001261{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001262 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001263
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001264 AutoMutex lock(mLock);
1265 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001266 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001267 }
1268 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001269 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001270 }
1271}
1272
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273status_t AudioFlinger::setMasterMute(bool muted)
1274{
John Grossmand8f178d2012-07-20 14:51:35 -07001275 status_t ret = initCheck();
1276 if (ret != NO_ERROR) {
1277 return ret;
1278 }
1279
Mathias Agopian65ab4712010-07-14 17:59:35 -07001280 // check calling permissions
1281 if (!settingsAllowed()) {
1282 return PERMISSION_DENIED;
1283 }
1284
John Grossmanee578c02012-07-23 17:05:46 -07001285 Mutex::Autolock _l(mLock);
1286 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001287
John Grossmanee578c02012-07-23 17:05:46 -07001288 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001289 {
John Grossmanee578c02012-07-23 17:05:46 -07001290 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001291 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1292 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001293
Eric Laurent00abf0d2020-04-22 19:28:22 -07001294 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1295 if (dev->canSetMasterMute()) {
1296 dev->hwDevice()->setMasterMute(muted);
1297 }
1298 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001299 }
John Grossmand8f178d2012-07-20 14:51:35 -07001300 }
1301
John Grossmanee578c02012-07-23 17:05:46 -07001302 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001303 // assigned to HALs which do not have master mute support will apply master mute
1304 // during the mix operation. Threads with HALs which do support master mute
1305 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001306 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1307 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1308 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310
1311 return NO_ERROR;
1312}
1313
1314float AudioFlinger::masterVolume() const
1315{
Glenn Kasten98067102011-12-13 11:47:54 -08001316 Mutex::Autolock _l(mLock);
1317 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318}
1319
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001320status_t AudioFlinger::getMasterBalance(float *balance) const
1321{
1322 Mutex::Autolock _l(mLock);
1323 *balance = getMasterBalance_l();
1324 return NO_ERROR; // if called through binder, may return a transactional error
1325}
1326
Mathias Agopian65ab4712010-07-14 17:59:35 -07001327bool AudioFlinger::masterMute() const
1328{
Glenn Kasten98067102011-12-13 11:47:54 -08001329 Mutex::Autolock _l(mLock);
1330 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331}
1332
John Grossman4ff14ba2012-02-08 16:37:41 -08001333float AudioFlinger::masterVolume_l() const
1334{
John Grossman4ff14ba2012-02-08 16:37:41 -08001335 return mMasterVolume;
1336}
1337
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001338float AudioFlinger::getMasterBalance_l() const
1339{
1340 return mMasterBalance;
1341}
1342
John Grossmand8f178d2012-07-20 14:51:35 -07001343bool AudioFlinger::masterMute_l() const
1344{
John Grossmanee578c02012-07-23 17:05:46 -07001345 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001346}
1347
Eric Laurent223fd5c2014-11-11 13:43:36 -08001348status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1349{
1350 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001351 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001352 return BAD_VALUE;
1353 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001354 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1355 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1356 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001357 return PERMISSION_DENIED;
1358 }
1359
1360 return NO_ERROR;
1361}
1362
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001363status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1364 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365{
1366 // check calling permissions
1367 if (!settingsAllowed()) {
1368 return PERMISSION_DENIED;
1369 }
1370
Eric Laurent223fd5c2014-11-11 13:43:36 -08001371 status_t status = checkStreamType(stream);
1372 if (status != NO_ERROR) {
1373 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 }
Eric Laurent98e38192018-02-15 18:31:53 -08001375 if (output == AUDIO_IO_HANDLE_NONE) {
1376 return BAD_VALUE;
1377 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001378 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1379 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380
1381 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001382 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1383 if (volumeInterface == NULL) {
1384 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 }
Eric Laurent98e38192018-02-15 18:31:53 -08001386 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387
1388 return NO_ERROR;
1389}
1390
Glenn Kastenfff6d712012-01-12 16:38:12 -08001391status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392{
1393 // check calling permissions
1394 if (!settingsAllowed()) {
1395 return PERMISSION_DENIED;
1396 }
1397
Eric Laurent223fd5c2014-11-11 13:43:36 -08001398 status_t status = checkStreamType(stream);
1399 if (status != NO_ERROR) {
1400 return status;
1401 }
1402 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1403
1404 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001405 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 return BAD_VALUE;
1407 }
1408
Eric Laurent93575202011-01-18 18:39:02 -08001409 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001410 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001411 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1412 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1413 volumeInterfaces[i]->setStreamMute(stream, muted);
1414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415
1416 return NO_ERROR;
1417}
1418
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001419float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001421 status_t status = checkStreamType(stream);
1422 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 return 0.0f;
1424 }
Eric Laurent98e38192018-02-15 18:31:53 -08001425 if (output == AUDIO_IO_HANDLE_NONE) {
1426 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 }
1428
Eric Laurent98e38192018-02-15 18:31:53 -08001429 AutoMutex lock(mLock);
1430 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1431 if (volumeInterface == NULL) {
1432 return 0.0f;
1433 }
1434
1435 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
Glenn Kastenfff6d712012-01-12 16:38:12 -08001438bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001440 status_t status = checkStreamType(stream);
1441 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442 return true;
1443 }
1444
Glenn Kasten6637baa2012-01-09 09:40:36 -08001445 AutoMutex lock(mLock);
1446 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447}
1448
Eric Laurent054d9d32015-04-24 08:48:48 -07001449
1450void AudioFlinger::broacastParametersToRecordThreads_l(const String8& keyValuePairs)
1451{
1452 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1453 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1454 }
1455}
1456
jiabinc52b1ff2019-10-31 17:20:42 -07001457void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1458{
1459 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1460 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1461 }
1462}
1463
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001464// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1465void AudioFlinger::forwardParametersToDownstreamPatches_l(
1466 audio_io_handle_t upStream, const String8& keyValuePairs,
1467 std::function<bool(const sp<PlaybackThread>&)> useThread)
1468{
1469 std::vector<PatchPanel::SoftwarePatch> swPatches;
1470 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1471 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1472 __func__, swPatches.size(), upStream);
1473 for (const auto& swPatch : swPatches) {
1474 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1475 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1476 downStream->setParameters(keyValuePairs);
1477 }
1478 }
1479}
1480
Eric Laurentf1047e82018-04-16 19:18:20 -07001481// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1482// Some keys are used for audio routing and audio path configuration and should be reserved for use
1483// by audio policy and audio flinger for functional, privacy and security reasons.
1484void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1485{
1486 static const String8 kReservedParameters[] = {
1487 String8(AudioParameter::keyRouting),
1488 String8(AudioParameter::keySamplingRate),
1489 String8(AudioParameter::keyFormat),
1490 String8(AudioParameter::keyChannels),
1491 String8(AudioParameter::keyFrameCount),
1492 String8(AudioParameter::keyInputSource),
1493 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001494 String8(AudioParameter::keyDeviceConnect),
1495 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001496 String8(AudioParameter::keyStreamSupportedFormats),
1497 String8(AudioParameter::keyStreamSupportedChannels),
1498 String8(AudioParameter::keyStreamSupportedSamplingRates),
1499 };
1500
Andy Hung4ef19fa2018-05-15 19:35:29 -07001501 if (isAudioServerUid(callingUid)) {
1502 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001503 }
1504
1505 AudioParameter param = AudioParameter(keyValuePairs);
1506 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001507 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001508 for (auto& key : kReservedParameters) {
1509 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001510 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001511 param.remove(key);
1512 }
1513 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001514 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1515 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001516 keyValuePairs = param.toString();
1517}
1518
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001519void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1520 size_t rejectedKVPSize, const String8& rejectedKVPs,
1521 uid_t callingUid) {
1522 auto prefix = String8::format("UID %5d", callingUid);
1523 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1524 if (rejectedKVPSize != 0) {
1525 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1526 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1527 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1528 } else {
1529 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1530 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1531 }
1532}
1533
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001534status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535{
Eric Laurentf1047e82018-04-16 19:18:20 -07001536 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1537 ioHandle, keyValuePairs.string(),
1538 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001539
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 // check calling permissions
1541 if (!settingsAllowed()) {
1542 return PERMISSION_DENIED;
1543 }
1544
Eric Laurentf1047e82018-04-16 19:18:20 -07001545 String8 filteredKeyValuePairs = keyValuePairs;
1546 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1547
1548 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1549
Glenn Kasten142f5192014-03-25 17:44:59 -07001550 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1551 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001552 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001553 // result will remain NO_INIT if no audio device is present
1554 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001555 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001556 AutoMutex lock(mHardwareLock);
1557 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1558 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001559 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001560 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001561 // return success if at least one audio device accepts the parameters as not all
1562 // HALs are requested to support all parameters. If no audio device supports the
1563 // requested parameters, the last error is reported.
1564 if (final_result != NO_ERROR) {
1565 final_result = result;
1566 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001567 }
1568 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001569 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001570 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001571 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001572 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001573 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1574 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001575 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001576 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001577 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001578 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001579 }
1580 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001581 String8 screenState;
1582 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001583 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001584 if (isOff != (AudioFlinger::mScreenState & 1)) {
1585 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001586 }
1587 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001588 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 }
1590
1591 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1592 // and the thread is exited once the lock is released
1593 sp<ThreadBase> thread;
1594 {
1595 Mutex::Autolock _l(mLock);
1596 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001597 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001599 if (thread == 0) {
1600 thread = checkMmapThread_l(ioHandle);
1601 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001602 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001603 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001604 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001605 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001606 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1607 (value != 0)) {
Eric Laurentf1047e82018-04-16 19:18:20 -07001608 broacastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 }
1611 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001612 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001613 status_t result = thread->setParameters(filteredKeyValuePairs);
1614 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1615 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 }
1617 return BAD_VALUE;
1618}
1619
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001620String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001622 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1623 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624
Eric Laurenta4c5a552012-03-29 10:12:40 -07001625 Mutex::Autolock _l(mLock);
1626
Glenn Kasten142f5192014-03-25 17:44:59 -07001627 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001628 String8 out_s8;
1629
Eric Laurent00abf0d2020-04-22 19:28:22 -07001630 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001631 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001632 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001633 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001634 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001635 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001636 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001637 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001638 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001639 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001640 }
1641
Eric Laurent6acd1d42017-01-04 14:23:29 -08001642 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1643 if (thread == NULL) {
1644 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1645 if (thread == NULL) {
1646 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1647 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001648 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001649 }
1650 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001652 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653}
1654
Glenn Kastendd8104c2012-07-02 12:42:44 -07001655size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1656 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657{
Eric Laurenta1884f92011-08-23 08:25:03 -07001658 status_t ret = initCheck();
1659 if (ret != NO_ERROR) {
1660 return 0;
1661 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001662 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001663 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001664 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001665 return 0;
1666 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001667
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001668 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001669 if (mPrimaryHardwareDev == nullptr) {
1670 return 0;
1671 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001672 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001673
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001674 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001675 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1676 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1677 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1678 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1679 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1680
1681 std::vector<audio_format_t> formats = {format};
1682 if (format != AUDIO_FORMAT_PCM_16_BIT)
1683 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1684
1685 std::vector<uint32_t> sampleRates = {sampleRate};
1686 static const uint32_t SR_44100 = 44100;
1687 static const uint32_t SR_48000 = 48000;
1688
1689 if (sampleRate != SR_48000)
1690 sampleRates.push_back(SR_48000);
1691 if (sampleRate != SR_44100)
1692 sampleRates.push_back(SR_44100);
1693
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001694 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001695
Robin Lee9899ff72019-12-24 22:02:08 +01001696 // Change parameters of the configuration each iteration until we find a
1697 // configuration that the device will support.
1698 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001699 for (auto testChannelMask : channelMasks) {
1700 config.channel_mask = testChannelMask;
1701 for (auto testFormat : formats) {
1702 config.format = testFormat;
1703 for (auto testSampleRate : sampleRates) {
1704 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001705
Judy Hsiaoabab5222019-11-09 18:14:58 +08001706 size_t bytes = 0;
1707 status_t result = dev->getInputBufferSize(&config, &bytes);
1708 if (result != OK || bytes == 0) {
1709 continue;
1710 }
1711
1712 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1713 config.format != format) {
1714 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1715 uint32_t srcChannelCount =
1716 audio_channel_count_from_in_mask(config.channel_mask);
1717 size_t srcFrames =
1718 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1719 size_t dstFrames = destinationFramesPossible(
1720 srcFrames, config.sample_rate, sampleRate);
1721 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1722 }
1723 return bytes;
1724 }
1725 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001726 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001727
1728 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1729 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1730 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731}
1732
Glenn Kasten5f972c02014-01-13 09:59:31 -08001733uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 Mutex::Autolock _l(mLock);
1736
1737 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1738 if (recordThread != NULL) {
1739 return recordThread->getInputFramesLost();
1740 }
1741 return 0;
1742}
1743
1744status_t AudioFlinger::setVoiceVolume(float value)
1745{
Eric Laurenta1884f92011-08-23 08:25:03 -07001746 status_t ret = initCheck();
1747 if (ret != NO_ERROR) {
1748 return ret;
1749 }
1750
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 // check calling permissions
1752 if (!settingsAllowed()) {
1753 return PERMISSION_DENIED;
1754 }
1755
1756 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001757 if (mPrimaryHardwareDev == nullptr) {
1758 return INVALID_OPERATION;
1759 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001760 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001761 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001762 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 mHardwareStatus = AUDIO_HW_IDLE;
1764
Joey Poomarin52989982020-03-05 17:40:49 +08001765 mediametrics::LogItem(mMetricsId)
1766 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1767 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1768 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 return ret;
1770}
1771
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001772status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001773 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 Mutex::Autolock _l(mLock);
1776
1777 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1778 if (playbackThread != NULL) {
1779 return playbackThread->getRenderPosition(halFrames, dspFrames);
1780 }
1781
1782 return BAD_VALUE;
1783}
1784
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001785void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001788 if (client == 0) {
1789 return;
1790 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001791 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001792 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001793 {
1794 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001795 if (mNotificationClients.indexOfKey(pid) < 0) {
1796 sp<NotificationClient> notificationClient = new NotificationClient(this,
1797 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001798 pid,
1799 uid);
1800 ALOGV("registerClient() client %p, pid %d, uid %u",
1801 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802
Eric Laurent021cf962014-05-13 10:18:14 -07001803 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804
Marco Nelissen06b46062014-11-14 07:58:25 -08001805 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001806 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001807 }
1808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809
Eric Laurent021cf962014-05-13 10:18:14 -07001810 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001811 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001812 // the config change is always sent from playback or record threads to avoid deadlock
1813 // with AudioSystem::gLock
1814 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001815 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001818 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001819 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 }
1821}
1822
1823void AudioFlinger::removeNotificationClient(pid_t pid)
1824{
Eric Laurent6c796322019-04-09 14:13:17 -07001825 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001826 {
Eric Laurent6c796322019-04-09 14:13:17 -07001827 Mutex::Autolock _l(mLock);
1828 {
1829 Mutex::Autolock _cl(mClientLock);
1830 mNotificationClients.removeItem(pid);
1831 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001832
Eric Laurent6c796322019-04-09 14:13:17 -07001833 ALOGV("%d died, releasing its sessions", pid);
1834 size_t num = mAudioSessionRefs.size();
1835 bool removed = false;
1836 for (size_t i = 0; i < num; ) {
1837 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1838 ALOGV(" pid %d @ %zu", ref->mPid, i);
1839 if (ref->mPid == pid) {
1840 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1841 mAudioSessionRefs.removeAt(i);
1842 delete ref;
1843 removed = true;
1844 num--;
1845 } else {
1846 i++;
1847 }
1848 }
1849 if (removed) {
1850 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001851 }
1852 }
Eric Laurent6c796322019-04-09 14:13:17 -07001853 for (auto& effect : removedEffects) {
1854 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001855 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856}
1857
Eric Laurent73e26b62015-04-27 16:55:58 -07001858void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001859 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001860 pid_t pid) {
1861 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
1862 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
1863 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
1864 legacy2aidl_audio_io_config_event_AudioIoConfigEvent(event));
1865
Eric Laurent021cf962014-05-13 10:18:14 -07001866 Mutex::Autolock _l(mClientLock);
1867 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001869 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001870 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
1871 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 }
1874}
1875
Eric Laurent021cf962014-05-13 10:18:14 -07001876// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877void AudioFlinger::removeClient_l(pid_t pid)
1878{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001879 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001880 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 mClients.removeItem(pid);
1882}
1883
Eric Laurent717e1282012-06-29 16:36:52 -07001884// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001885sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1886 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001887{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001888 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001889
1890 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001891 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001892 ALOG_ASSERT(thread == 0);
1893 thread = mPlaybackThreads.valueAt(i);
1894 }
1895 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001896 if (thread != nullptr) {
1897 return thread;
1898 }
1899 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1900 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1901 ALOG_ASSERT(thread == 0);
1902 thread = mRecordThreads.valueAt(i);
1903 }
1904 }
1905 if (thread != nullptr) {
1906 return thread;
1907 }
1908 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1909 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1910 ALOG_ASSERT(thread == 0);
1911 thread = mMmapThreads.valueAt(i);
1912 }
1913 }
Eric Laurent717e1282012-06-29 16:36:52 -07001914 return thread;
1915}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
1919// ----------------------------------------------------------------------------
1920
1921AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1922 : RefBase(),
1923 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001924 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925{
Andy Hung6f248bb2018-01-23 14:04:37 -08001926 mMemoryDealer = new MemoryDealer(
1927 audioFlinger->getClientSharedHeapSize(),
1928 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929}
1930
Eric Laurent021cf962014-05-13 10:18:14 -07001931// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932AudioFlinger::Client::~Client()
1933{
1934 mAudioFlinger->removeClient_l(mPid);
1935}
1936
Glenn Kasten435dbe62012-01-30 10:15:48 -08001937sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938{
1939 return mMemoryDealer;
1940}
1941
1942// ----------------------------------------------------------------------------
1943
1944AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001945 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001946 pid_t pid,
1947 uid_t uid)
1948 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949{
1950}
1951
1952AudioFlinger::NotificationClient::~NotificationClient()
1953{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954}
1955
Glenn Kasten0f11b512014-01-31 16:18:54 -08001956void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957{
1958 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08001959 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960}
1961
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001962// ----------------------------------------------------------------------------
1963AudioFlinger::MediaLogNotifier::MediaLogNotifier()
1964 : mPendingRequests(false) {}
1965
1966
1967void AudioFlinger::MediaLogNotifier::requestMerge() {
1968 AutoMutex _l(mMutex);
1969 mPendingRequests = true;
1970 mCond.signal();
1971}
1972
1973bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001974 // Should already have been checked, but just in case
1975 if (sMediaLogService == 0) {
1976 return false;
1977 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001978 // Wait until there are pending requests
1979 {
1980 AutoMutex _l(mMutex);
1981 mPendingRequests = false; // to ignore past requests
1982 while (!mPendingRequests) {
1983 mCond.wait(mMutex);
1984 // TODO may also need an exitPending check
1985 }
1986 mPendingRequests = false;
1987 }
1988 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001989 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001990 usleep(kPostTriggerSleepPeriod);
1991 return true;
1992}
1993
1994void AudioFlinger::requestLogMerge() {
1995 mMediaLogNotifier->requestMerge();
1996}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
1998// ----------------------------------------------------------------------------
1999
Eric Laurentf14db3c2017-12-08 14:20:36 -08002000sp<media::IAudioRecord> AudioFlinger::createRecord(const CreateRecordInput& input,
2001 CreateRecordOutput& output,
2002 status_t *status)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003{
2004 sp<RecordThread::RecordTrack> recordTrack;
2005 sp<RecordHandle> recordHandle;
2006 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002008 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002009 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
Eric Laurentf14db3c2017-12-08 14:20:36 -08002011 output.cblk.clear();
2012 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002013 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002014
Eric Laurentf14db3c2017-12-08 14:20:36 -08002015 bool updatePid = (input.clientInfo.clientPid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002016 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurentf14db3c2017-12-08 14:20:36 -08002017 uid_t clientUid = input.clientInfo.clientUid;
Andy Hung4ef19fa2018-05-15 19:35:29 -07002018 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002019 ALOGW_IF(clientUid != callingUid,
2020 "%s uid %d tried to pass itself off as %d",
2021 __FUNCTION__, callingUid, clientUid);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002022 clientUid = callingUid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002023 updatePid = true;
2024 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002025 pid_t clientPid = input.clientInfo.clientPid;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002026 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002027 if (updatePid) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002028 ALOGW_IF(clientPid != -1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002029 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurentf14db3c2017-12-08 14:20:36 -08002030 __func__, callingUid, callingPid, clientPid);
2031 clientPid = callingPid;
Marco Nelissendcb346b2015-09-09 10:47:29 -07002032 }
2033
Andy Hung6770c6f2015-04-07 13:43:36 -07002034 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002035 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2036 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002037 lStatus = BAD_VALUE;
2038 goto Exit;
2039 }
2040
Glenn Kasten53b5d092014-02-05 10:00:23 -08002041 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002042 if (!audio_is_input_channel(input.config.channel_mask)) {
2043 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002044 lStatus = BAD_VALUE;
2045 goto Exit;
2046 }
2047
Eric Laurentf14db3c2017-12-08 14:20:36 -08002048 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2049 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2050 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2051 lStatus = BAD_VALUE;
2052 goto Exit;
2053 }
2054
2055 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002056 output.selectedDeviceId = input.selectedDeviceId;
2057 output.flags = input.flags;
2058
2059 client = registerPid(clientPid);
2060
2061 // Not a conventional loop, but a retry loop for at most two iterations total.
2062 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2063 // Exits loop via break on no error of got exit on error
2064 // The sp<> references will be dropped when re-entering scope.
2065 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2066 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002067 // release previously opened input if retrying.
2068 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2069 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002070 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002071 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002072 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002073 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002074 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002075 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002076 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002077 sessionId,
2078 // FIXME compare to AudioTrack
2079 clientPid,
2080 clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08002081 input.opPackageName,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002082 &input.config,
2083 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002084 if (lStatus != NO_ERROR) {
2085 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2086 goto Exit;
2087 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002088
Glenn Kasten05997e22014-03-13 15:08:33 -07002089 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002091 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002093 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2094 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 goto Exit;
2096 }
2097
Eric Laurentf14db3c2017-12-08 14:20:36 -08002098 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099
Eric Laurentf14db3c2017-12-08 14:20:36 -08002100 output.sampleRate = input.config.sample_rate;
2101 output.frameCount = input.frameCount;
2102 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002103
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002104 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002105 input.config.format, input.config.channel_mask,
2106 &output.frameCount, sessionId,
2107 &output.notificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002108 callingPid, clientUid, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002109 input.clientInfo.clientTid,
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07002110 &lStatus, portId,
2111 input.opPackageName);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002112 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002113
Eric Laurentf14db3c2017-12-08 14:20:36 -08002114 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2115 // audio policy manager without FAST constraint
2116 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002117 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002118 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002119
2120 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002121 goto Exit;
2122 }
2123
2124 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2125 // session and move it to this thread.
2126 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2127 if (chain != 0) {
2128 Mutex::Autolock _l(thread->mLock);
2129 thread->addEffectChain_l(chain);
2130 }
2131 break;
2132 }
2133 // End of retry loop.
2134 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 }
Glenn Kastene198c362013-08-13 09:13:36 -07002136
Eric Laurentf14db3c2017-12-08 14:20:36 -08002137 output.cblk = recordTrack->getCblk();
2138 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002139 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002140
2141 // return handle to client
2142 recordHandle = new RecordHandle(recordTrack);
2143
2144Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002145 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002146 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002147 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002148 // Don't hold mClientLock when releasing the reference on the track as the
2149 // destructor will acquire it.
2150 {
2151 Mutex::Autolock _cl(mClientLock);
2152 client.clear();
2153 }
Eric Laurent896c9672017-12-08 14:08:45 -08002154 recordTrack.clear();
2155 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002156 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 }
2159
Glenn Kasten9156ef32013-08-06 15:39:08 -07002160 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 return recordHandle;
2162}
2163
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002164
2165
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166// ----------------------------------------------------------------------------
2167
Eric Laurenta4c5a552012-03-29 10:12:40 -07002168audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2169{
Eric Laurent44622db2014-08-01 19:00:33 -07002170 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002171 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002172 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002173 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002174 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002175 }
2176 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002177 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002178 return loadHwModule_l(name);
2179}
2180
Eric Laurent00abf0d2020-04-22 19:28:22 -07002181// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002182audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2183{
2184 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2185 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2186 ALOGW("loadHwModule() module %s already loaded", name);
2187 return mAudioHwDevs.keyAt(i);
2188 }
2189 }
2190
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002191 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002192
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002193 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002194 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002195 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002196 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002197 }
2198
2199 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002200 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002201 mHardwareStatus = AUDIO_HW_IDLE;
2202 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002203 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002204 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002205 }
2206
John Grossmanee578c02012-07-23 17:05:46 -07002207 // Check and cache this HAL's level of support for master mute and master
2208 // volume. If this is the first HAL opened, and it supports the get
2209 // methods, use the initial values provided by the HAL as the current
2210 // master mute and volume settings.
2211
2212 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002213 if (0 == mAudioHwDevs.size()) {
2214 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2215 float mv;
2216 if (OK == dev->getMasterVolume(&mv)) {
2217 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002218 }
2219
Eric Laurent00abf0d2020-04-22 19:28:22 -07002220 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2221 bool mm;
2222 if (OK == dev->getMasterMute(&mm)) {
2223 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002224 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002225 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002226
2227 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2228 if (OK == dev->setMasterVolume(mMasterVolume)) {
2229 flags = static_cast<AudioHwDevice::Flags>(flags |
2230 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2231 }
2232
2233 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2234 if (OK == dev->setMasterMute(mMasterMute)) {
2235 flags = static_cast<AudioHwDevice::Flags>(flags |
2236 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2237 }
2238
2239 mHardwareStatus = AUDIO_HW_IDLE;
2240
Mikhail Naganov97373b02018-07-23 13:27:24 -07002241 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002242 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2243 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2244 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002245
Glenn Kastena13cde92016-03-28 15:26:02 -07002246 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002247 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2248 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2249 mPrimaryHardwareDev = audioDevice;
2250 mHardwareStatus = AUDIO_HW_SET_MODE;
2251 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2252 mHardwareStatus = AUDIO_HW_IDLE;
2253 }
2254
2255 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002256
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002257 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002258
2259 return handle;
2260
2261}
2262
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002263// ----------------------------------------------------------------------------
2264
Glenn Kasten3b16c762012-11-14 08:44:39 -08002265uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002266{
2267 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002268 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002269 return thread != NULL ? thread->sampleRate() : 0;
2270}
2271
Glenn Kastene33054e2012-11-14 12:54:39 -08002272size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002273{
2274 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002275 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002276 return thread != NULL ? thread->frameCountHAL() : 0;
2277}
2278
2279// ----------------------------------------------------------------------------
2280
Andy Hung6f248bb2018-01-23 14:04:37 -08002281status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002282{
2283 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002284 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002285 return PERMISSION_DENIED;
2286 }
2287 Mutex::Autolock _l(mLock);
2288 if (mIsDeviceTypeKnown) {
2289 return INVALID_OPERATION;
2290 }
2291 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002292 mTotalMemory = totalMemory;
2293 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2294 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2295 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2296 // though actual setting is determined through device configuration.
2297 constexpr int64_t GB = 1024 * 1024 * 1024;
2298 mClientSharedHeapSize =
2299 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2300 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2301 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2302 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2303 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002304 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002305
2306 // TODO: Cache the client shared heap size in a persistent property.
2307 // It's possible that a native process or Java service or app accesses audioserver
2308 // after it is registered by system server, but before AudioService updates
2309 // the memory info. This would occur immediately after boot or an audioserver
2310 // crash and restore. Before update from AudioService, the client would get the
2311 // minimum heap size.
2312
2313 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2314 (isLowRamDevice ? "true" : "false"),
2315 (long long)mTotalMemory,
2316 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002317 return NO_ERROR;
2318}
2319
Andy Hung6f248bb2018-01-23 14:04:37 -08002320size_t AudioFlinger::getClientSharedHeapSize() const
2321{
2322 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2323 if (heapSizeInBytes != 0) { // read-only property overrides all.
2324 return heapSizeInBytes;
2325 }
2326 return mClientSharedHeapSize;
2327}
2328
Mikhail Naganovdea53042018-04-26 13:10:21 -07002329status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2330{
2331 ALOGV(__func__);
2332
2333 audio_module_handle_t module;
2334 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2335 module = config->ext.device.hw_module;
2336 } else {
2337 module = config->ext.mix.hw_module;
2338 }
2339
2340 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002341 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002342 ssize_t index = mAudioHwDevs.indexOfKey(module);
2343 if (index < 0) {
2344 ALOGW("%s() bad hw module %d", __func__, module);
2345 return BAD_VALUE;
2346 }
2347
2348 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2349 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2350}
2351
Eric Laurent93c3d412014-08-01 14:48:35 -07002352audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2353{
2354 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002355
2356 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2357 if (index >= 0) {
2358 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2359 mHwAvSyncIds.valueAt(index), sessionId);
2360 return mHwAvSyncIds.valueAt(index);
2361 }
2362
Eric Laurent00abf0d2020-04-22 19:28:22 -07002363 sp<DeviceHalInterface> dev;
2364 {
2365 AutoMutex lock(mHardwareLock);
2366 if (mPrimaryHardwareDev == nullptr) {
2367 return AUDIO_HW_SYNC_INVALID;
2368 }
2369 dev = mPrimaryHardwareDev->hwDevice();
2370 }
2371 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002372 return AUDIO_HW_SYNC_INVALID;
2373 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002374 String8 reply;
2375 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002376 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002377 param = AudioParameter(reply);
2378 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002379
2380 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002381 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002382 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2383 return AUDIO_HW_SYNC_INVALID;
2384 }
2385
2386 // allow only one session for a given HW A/V sync ID.
2387 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2388 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2389 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2390 value, mHwAvSyncIds.keyAt(i));
2391 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002392 break;
2393 }
2394 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002395
2396 mHwAvSyncIds.add(sessionId, value);
2397
2398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2399 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2400 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002401 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002402 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002403 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002404 String8 keyValuePairs = param.toString();
2405 thread->setParameters(keyValuePairs);
2406 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2407 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002408 break;
2409 }
2410 }
2411
2412 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2413 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002414}
2415
Eric Laurent72e3f392015-05-20 14:43:50 -07002416status_t AudioFlinger::systemReady()
2417{
2418 Mutex::Autolock _l(mLock);
2419 ALOGI("%s", __FUNCTION__);
2420 if (mSystemReady) {
2421 ALOGW("%s called twice", __FUNCTION__);
2422 return NO_ERROR;
2423 }
2424 mSystemReady = true;
2425 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2426 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2427 thread->systemReady();
2428 }
2429 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2430 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2431 thread->systemReady();
2432 }
2433 return NO_ERROR;
2434}
2435
jiabin46a76fa2018-01-05 10:18:21 -08002436status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2437{
jiabin9ff780e2018-03-19 18:19:52 -07002438 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002439 status_t status = INVALID_OPERATION;
2440
2441 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2442 std::vector<media::MicrophoneInfo> mics;
2443 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2444 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2445 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2446 mHardwareStatus = AUDIO_HW_IDLE;
2447 if (devStatus == NO_ERROR) {
2448 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2449 // report success if at least one HW module supports the function.
2450 status = NO_ERROR;
2451 }
2452 }
2453
jiabin9ff780e2018-03-19 18:19:52 -07002454 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002455}
2456
Eric Laurentfa90e842014-10-17 18:12:31 -07002457// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2458void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2459{
2460 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2461 if (index >= 0) {
2462 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2463 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2464 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002465 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002466 String8 keyValuePairs = param.toString();
2467 thread->setParameters(keyValuePairs);
2468 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2469 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002470 }
2471}
2472
2473
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002474// ----------------------------------------------------------------------------
2475
Eric Laurent83b88082014-06-20 18:31:16 -07002476
Eric Laurent6acd1d42017-01-04 14:23:29 -08002477sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002478 audio_io_handle_t *output,
2479 audio_config_t *config,
2480 audio_devices_t deviceType,
2481 const String8& address,
2482 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002483{
jiabin43810402019-10-24 14:58:31 -07002484 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002485 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002486 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002487 }
2488
Eric Laurentcf2c0212014-07-25 16:20:43 -07002489 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002490 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2491 } else {
2492 // Audio Policy does not currently request a specific output handle.
2493 // If this is ever needed, see openInput_l() for example code.
2494 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2495 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002496 }
Eric Laurent83b88082014-06-20 18:31:16 -07002497
2498 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2499
Eric Laurent83b88082014-06-20 18:31:16 -07002500 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002501 // This if statement allows overriding the audio policy settings
2502 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2503 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2504 // Check only for Normal Mixing mode
2505 if (kEnableExtendedPrecision) {
2506 // Specify format (uncomment one below to choose)
2507 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2508 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2509 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2510 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002511 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002512 }
2513 if (kEnableExtendedChannels) {
2514 // Specify channel mask (uncomment one below to choose)
2515 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2516 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2517 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2518 }
Eric Laurent83b88082014-06-20 18:31:16 -07002519 }
2520
Phil Burk062e67a2015-02-11 13:40:50 -08002521 AudioStreamOut *outputStream = NULL;
2522 status_t status = outHwDev->openOutputStream(
2523 &outputStream,
2524 *output,
jiabin43810402019-10-24 14:58:31 -07002525 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002526 flags,
2527 config,
2528 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002529
2530 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002531
Phil Burk062e67a2015-02-11 13:40:50 -08002532 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002533 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2534 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002535 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002536 mMmapThreads.add(*output, thread);
2537 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2538 *output, thread.get());
2539 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002540 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002541 sp<PlaybackThread> thread;
2542 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002543 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002544 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2545 *output, thread.get());
2546 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2547 || !isValidPcmSinkFormat(config->format)
2548 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002549 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002550 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2551 *output, thread.get());
2552 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002553 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002554 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2555 *output, thread.get());
2556 }
2557 mPlaybackThreads.add(*output, thread);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002558 mPatchPanel.notifyStreamOpened(outHwDev, *output);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002559 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002560 }
Eric Laurent83b88082014-06-20 18:31:16 -07002561 }
2562
2563 return 0;
2564}
2565
Eric Laurentcf2c0212014-07-25 16:20:43 -07002566status_t AudioFlinger::openOutput(audio_module_handle_t module,
2567 audio_io_handle_t *output,
2568 audio_config_t *config,
jiabin43810402019-10-24 14:58:31 -07002569 const sp<DeviceDescriptorBase>& device,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002570 uint32_t *latencyMs,
2571 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572{
jiabin43810402019-10-24 14:58:31 -07002573 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002574 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002575 this, module,
jiabin43810402019-10-24 14:58:31 -07002576 device->toString().c_str(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07002577 config->sample_rate,
2578 config->format,
2579 config->channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002580 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581
jiabin43810402019-10-24 14:58:31 -07002582 audio_devices_t deviceType = device->type();
2583 const String8 address = String8(device->address().c_str());
2584
2585 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002586 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002588
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 Mutex::Autolock _l(mLock);
2590
jiabin43810402019-10-24 14:58:31 -07002591 sp<ThreadBase> thread = openOutput_l(module, output, config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002592 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002593 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2594 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2595 *latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596
Eric Laurent6acd1d42017-01-04 14:23:29 -08002597 // notify client processes of the new output creation
2598 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002599
Eric Laurent00abf0d2020-04-22 19:28:22 -07002600 // the first primary output opened designates the primary hw device if no HW module
2601 // named "primary" was already loaded.
2602 AutoMutex lock(mHardwareLock);
2603 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002604 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002605 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002606
Eric Laurent6acd1d42017-01-04 14:23:29 -08002607 mHardwareStatus = AUDIO_HW_SET_MODE;
2608 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2609 mHardwareStatus = AUDIO_HW_IDLE;
2610 }
2611 } else {
2612 MmapThread *mmapThread = (MmapThread *)thread.get();
2613 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002614 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002615 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 }
2617
Eric Laurentcf2c0212014-07-25 16:20:43 -07002618 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619}
2620
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002621audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2622 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623{
2624 Mutex::Autolock _l(mLock);
2625 MixerThread *thread1 = checkMixerThread_l(output1);
2626 MixerThread *thread2 = checkMixerThread_l(output2);
2627
2628 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002629 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2630 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002631 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 }
2633
Glenn Kasteneeecb982016-02-26 10:44:04 -08002634 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002635 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 thread->addOutputTrack(thread2);
2637 mPlaybackThreads.add(id, thread);
2638 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002639 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 return id;
2641}
2642
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002643status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644{
Glenn Kastend96c5722012-04-25 13:44:49 -07002645 return closeOutput_nonvirtual(output);
2646}
2647
2648status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2649{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 // keep strong reference on the playback thread so that
2651 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002652 sp<PlaybackThread> playbackThread;
2653 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 {
2655 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002656 playbackThread = checkPlaybackThread_l(output);
2657 if (playbackThread != NULL) {
2658 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659
Andy Hungdc099c22018-09-18 13:46:39 -07002660 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002661
Eric Laurent6acd1d42017-01-04 14:23:29 -08002662 if (playbackThread->type() == ThreadBase::MIXER) {
2663 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2664 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2665 DuplicatingThread *dupThread =
2666 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2667 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 }
2670 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671
2672
Eric Laurent6acd1d42017-01-04 14:23:29 -08002673 mPlaybackThreads.removeItem(output);
2674 // save all effects to the default thread
2675 if (mPlaybackThreads.size()) {
2676 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2677 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002678 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002679 Mutex::Autolock _dl(dstThread->mLock);
2680 Mutex::Autolock _sl(playbackThread->mLock);
2681 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2682 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002683 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002684 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 }
2687 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002688 } else {
2689 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2690 if (mmapThread == 0) {
2691 return BAD_VALUE;
2692 }
Andy Hungdc099c22018-09-18 13:46:39 -07002693 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002694 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002695 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002697 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2698 ioDesc->mIoHandle = output;
2699 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002700 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002702 // The thread entity (active unit of execution) is no longer running here,
2703 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704
Eric Laurent6acd1d42017-01-04 14:23:29 -08002705 if (playbackThread != 0) {
2706 playbackThread->exit();
2707 if (!playbackThread->isDuplicating()) {
2708 closeOutputFinish(playbackThread);
2709 }
2710 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002711 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002712 mmapThread->exit();
2713 AudioStreamOut *out = mmapThread->clearOutput();
2714 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2715 // from now on thread->mOutput is NULL
2716 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 }
2718 return NO_ERROR;
2719}
2720
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002721void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002722{
2723 AudioStreamOut *out = thread->clearOutput();
2724 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2725 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002726 delete out;
2727}
2728
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002729void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002730{
2731 mPlaybackThreads.removeItem(thread->mId);
2732 thread->exit();
2733 closeOutputFinish(thread);
2734}
2735
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002736status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737{
2738 Mutex::Autolock _l(mLock);
2739 PlaybackThread *thread = checkPlaybackThread_l(output);
2740
2741 if (thread == NULL) {
2742 return BAD_VALUE;
2743 }
2744
Steve Block3856b092011-10-20 11:56:00 +01002745 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746 thread->suspend();
2747
2748 return NO_ERROR;
2749}
2750
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002751status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752{
2753 Mutex::Autolock _l(mLock);
2754 PlaybackThread *thread = checkPlaybackThread_l(output);
2755
2756 if (thread == NULL) {
2757 return BAD_VALUE;
2758 }
2759
Steve Block3856b092011-10-20 11:56:00 +01002760 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761
2762 thread->restore();
2763
2764 return NO_ERROR;
2765}
2766
Eric Laurentcf2c0212014-07-25 16:20:43 -07002767status_t AudioFlinger::openInput(audio_module_handle_t module,
2768 audio_io_handle_t *input,
2769 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002770 audio_devices_t *devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002771 const String8& address,
2772 audio_source_t source,
Glenn Kastenec40d282014-07-15 15:31:26 -07002773 audio_input_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774{
Eric Laurent83b88082014-06-20 18:31:16 -07002775 Mutex::Autolock _l(mLock);
2776
Glenn Kastene7d66712015-03-05 13:46:52 -08002777 if (*devices == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002778 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002779 }
2780
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002781 sp<ThreadBase> thread = openInput_l(
2782 module, input, config, *devices, address, source, flags, AUDIO_DEVICE_NONE, String8{});
Eric Laurent83b88082014-06-20 18:31:16 -07002783
2784 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002785 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002786 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002787 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002789 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002790}
Dima Zavin799a70e2011-04-18 16:57:27 -07002791
Eric Laurent6acd1d42017-01-04 14:23:29 -08002792sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002793 audio_io_handle_t *input,
2794 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002795 audio_devices_t devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002796 const String8& address,
2797 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002798 audio_input_flags_t flags,
2799 audio_devices_t outputDevice,
2800 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002801{
Glenn Kastene7d66712015-03-05 13:46:52 -08002802 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002803 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002804 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002805 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002806 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002807
Glenn Kasteneeecb982016-02-26 10:44:04 -08002808 // Audio Policy can request a specific handle for hardware hotword.
2809 // The goal here is not to re-open an already opened input.
2810 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002811 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002812 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2813 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2814 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2815 return 0;
2816 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2817 // This should not happen in a transient state with current design.
2818 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2819 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002820 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002821
Eric Laurentcf2c0212014-07-25 16:20:43 -07002822 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002823 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002824 sp<StreamInHalInterface> inStream;
2825 status_t status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002826 *input, devices, &halconfig, flags, address.string(), source,
2827 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002828 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2829 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002830 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002831 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002832 halconfig.sample_rate,
2833 halconfig.format,
2834 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002835 flags,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07002836 status, address.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002838 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002839 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002840 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002841 audio_is_linear_pcm(config->format) &&
2842 audio_is_linear_pcm(halconfig.format) &&
2843 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002844 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2845 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002846 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002847 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002848 inStream.clear();
2849 status = inHwHal->openInputStream(
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002850 *input, devices, &halconfig, flags, address.string(), source,
2851 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002852 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 }
2854
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002855 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002856 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002857 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2858 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002859 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002860 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002861 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2862 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002863 return thread;
2864 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002865 // Start record thread
2866 // RecordThread requires both input and output device indication to forward to audio
2867 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002868 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002869 mRecordThreads.add(*input, thread);
2870 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2871 return thread;
2872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 }
2874
Eric Laurentcf2c0212014-07-25 16:20:43 -07002875 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 return 0;
2877}
2878
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002879status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880{
Glenn Kastend96c5722012-04-25 13:44:49 -07002881 return closeInput_nonvirtual(input);
2882}
2883
2884status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 // keep strong reference on the record thread so that
2887 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002888 sp<RecordThread> recordThread;
2889 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 {
2891 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002892 recordThread = checkRecordThread_l(input);
2893 if (recordThread != 0) {
2894 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895
Andy Hungdc099c22018-09-18 13:46:39 -07002896 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07002897
Eric Laurent6acd1d42017-01-04 14:23:29 -08002898 // If we still have effect chains, it means that a client still holds a handle
2899 // on at least one effect. We must either move the chain to an existing thread with the
2900 // same session ID or put it aside in case a new record thread is opened for a
2901 // new capture on the same session
2902 sp<EffectChain> chain;
2903 {
2904 Mutex::Autolock _sl(recordThread->mLock);
2905 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
2906 // Note: maximum one chain per record thread
2907 if (effectChains.size() != 0) {
2908 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07002909 }
2910 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002911 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002912 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08002913 // This should only happen in case of overlap between one thread tear down and the
2914 // creation of its replacement
2915 size_t i;
2916 for (i = 0; i < mRecordThreads.size(); i++) {
2917 sp<RecordThread> t = mRecordThreads.valueAt(i);
2918 if (t == recordThread) {
2919 continue;
2920 }
2921 if (t->hasAudioSession(chain->sessionId()) != 0) {
2922 Mutex::Autolock _l(t->mLock);
2923 ALOGV("closeInput() found thread %d for effect session %d",
2924 t->id(), chain->sessionId());
2925 t->addEffectChain_l(chain);
2926 break;
2927 }
2928 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08002929 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08002930 if (i == mRecordThreads.size()) {
2931 putOrphanEffectChain_l(chain);
2932 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002933 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002934 mRecordThreads.removeItem(input);
2935 } else {
2936 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
2937 if (mmapThread == 0) {
2938 return BAD_VALUE;
2939 }
Andy Hungdc099c22018-09-18 13:46:39 -07002940 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002941 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07002942 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002943 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2944 ioDesc->mIoHandle = input;
2945 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 }
Eric Laurent83b88082014-06-20 18:31:16 -07002947 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
2948 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08002949 if (recordThread != 0) {
2950 closeInputFinish(recordThread);
2951 } else if (mmapThread != 0) {
2952 mmapThread->exit();
2953 AudioStreamIn *in = mmapThread->clearInput();
2954 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
2955 // from now on thread->mInput is NULL
2956 delete in;
2957 }
Eric Laurent83b88082014-06-20 18:31:16 -07002958 return NO_ERROR;
2959}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002961void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002962{
2963 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002964 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08002965 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002966 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07002967 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07002968}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002970void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002971{
2972 mRecordThreads.removeItem(thread->mId);
2973 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974}
2975
Glenn Kastend2304db2014-02-03 07:40:31 -08002976status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977{
2978 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08002979 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980
2981 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2982 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07002983 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07002984 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002985 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2986 mMmapThreads[i]->invalidateTracks(stream);
2987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 return NO_ERROR;
2989}
2990
2991
Glenn Kasteneeecb982016-02-26 10:44:04 -08002992audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993{
Glenn Kasten9d003132016-04-06 14:38:09 -07002994 // This is a binder API, so a malicious client could pass in a bad parameter.
2995 // Check for that before calling the internal API nextUniqueId().
2996 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
2997 ALOGE("newAudioUniqueId invalid use %d", use);
2998 return AUDIO_UNIQUE_ID_ALLOCATE;
2999 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003000 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001}
3002
Andy Hung8b0bfd92019-12-23 13:11:11 -08003003void AudioFlinger::acquireAudioSessionId(
3004 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003005{
3006 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003007 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003008 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003009 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003010 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3011 caller = pid; // check must match releaseAudioSessionId()
3012 }
3013 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3014 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003015 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003016
Eric Laurent021cf962014-05-13 10:18:14 -07003017 {
3018 Mutex::Autolock _cl(mClientLock);
3019 // Ignore requests received from processes not known as notification client. The request
3020 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3021 // called from a different pid leaving a stale session reference. Also we don't know how
3022 // to clear this reference if the client process dies.
3023 if (mNotificationClients.indexOfKey(caller) < 0) {
3024 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3025 return;
3026 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003027 }
3028
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003029 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003030 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003031 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003032 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3033 ref->mCnt++;
3034 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003035 return;
3036 }
3037 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003038 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003039 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003040}
3041
Glenn Kastend848eb42016-03-08 13:42:11 -08003042void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003043{
Eric Laurent6c796322019-04-09 14:13:17 -07003044 std::vector< sp<EffectModule> > removedEffects;
3045 {
3046 Mutex::Autolock _l(mLock);
3047 pid_t caller = IPCThreadState::self()->getCallingPid();
3048 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3049 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003050 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3051 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003052 }
Eric Laurent6c796322019-04-09 14:13:17 -07003053 size_t num = mAudioSessionRefs.size();
3054 for (size_t i = 0; i < num; i++) {
3055 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3056 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3057 ref->mCnt--;
3058 ALOGV(" decremented refcount to %d", ref->mCnt);
3059 if (ref->mCnt == 0) {
3060 mAudioSessionRefs.removeAt(i);
3061 delete ref;
3062 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3063 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3064 }
3065 goto Exit;
3066 }
3067 }
3068 // If the caller is audioserver it is likely that the session being released was acquired
3069 // on behalf of a process not in notification clients and we ignore the warning.
3070 ALOGW_IF(!isAudioServerUid(callerUid),
3071 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003072 }
Eric Laurent6c796322019-04-09 14:13:17 -07003073
3074Exit:
3075 for (auto& effect : removedEffects) {
3076 effect->updatePolicyState();
3077 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003078}
3079
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003080bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3081{
3082 size_t num = mAudioSessionRefs.size();
3083 for (size_t i = 0; i < num; i++) {
3084 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3085 if (ref->mSessionid == audioSession) {
3086 return true;
3087 }
3088 }
3089 return false;
3090}
3091
Eric Laurent6c796322019-04-09 14:13:17 -07003092std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003093
Steve Block3856b092011-10-20 11:56:00 +01003094 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003095
3096 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003097 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003098
3099 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3100 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003101 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003102 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3103 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003104 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003105 chains.push(ec);
3106 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003107 }
3108 }
Eric Laurent6c796322019-04-09 14:13:17 -07003109
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003110 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3111 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003112 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003113 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3114 sp<EffectChain> ec = t->mEffectChains[j];
3115 chains.push(ec);
3116 }
3117 }
3118
Eric Laurent6c796322019-04-09 14:13:17 -07003119 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3120 sp<MmapThread> t = mMmapThreads.valueAt(i);
3121 Mutex::Autolock _l(t->mLock);
3122 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3123 sp<EffectChain> ec = t->mEffectChains[j];
3124 chains.push(ec);
3125 }
3126 }
3127
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003128 for (size_t i = 0; i < chains.size(); i++) {
3129 sp<EffectChain> ec = chains[i];
3130 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003131 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003132 if (t == 0) {
3133 continue;
3134 }
3135 size_t numsessionrefs = mAudioSessionRefs.size();
3136 bool found = false;
3137 for (size_t k = 0; k < numsessionrefs; k++) {
3138 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003139 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003140 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003141 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003142 found = true;
3143 break;
3144 }
3145 }
3146 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003147 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003148 // remove all effects from the chain
3149 while (ec->mEffects.size()) {
3150 sp<EffectModule> effect = ec->mEffects[0];
3151 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003152 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003153 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003154 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003155 }
Eric Laurent6c796322019-04-09 14:13:17 -07003156 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003157 }
3158 }
3159 }
Eric Laurent6c796322019-04-09 14:13:17 -07003160 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003161}
3162
Andy Hungdc099c22018-09-18 13:46:39 -07003163// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3164void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3165{
3166 audio_utils::FdToString fdToString;
3167 const int fd = fdToString.fd();
3168 if (fd >= 0) {
3169 thread->dump(fd, {} /* args */);
3170 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3171 }
3172}
3173
Glenn Kasteneeecb982016-02-26 10:44:04 -08003174// checkThread_l() must be called with AudioFlinger::mLock held
3175AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3176{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003177 ThreadBase *thread = checkMmapThread_l(ioHandle);
3178 if (thread == 0) {
3179 switch (audio_unique_id_get_use(ioHandle)) {
3180 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3181 thread = checkPlaybackThread_l(ioHandle);
3182 break;
3183 case AUDIO_UNIQUE_ID_USE_INPUT:
3184 thread = checkRecordThread_l(ioHandle);
3185 break;
3186 default:
3187 break;
3188 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003189 }
3190 return thread;
3191}
3192
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003194AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195{
Glenn Kastena1117922012-01-26 10:53:32 -08003196 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197}
3198
3199// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003200AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201{
3202 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003203 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204}
3205
3206// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003207AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208{
Glenn Kastena1117922012-01-26 10:53:32 -08003209 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210}
3211
Eric Laurent6acd1d42017-01-04 14:23:29 -08003212// checkMmapThread_l() must be called with AudioFlinger::mLock held
3213AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3214{
3215 return mMmapThreads.valueFor(io).get();
3216}
3217
3218
3219// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3220AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3221{
Eric Laurent7459b902017-04-19 18:10:41 -07003222 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003223 if (volumeInterface == nullptr) {
3224 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3225 if (mmapThread != nullptr) {
3226 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003227 MmapPlaybackThread *mmapPlaybackThread =
3228 static_cast<MmapPlaybackThread *>(mmapThread);
3229 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003230 }
3231 }
3232 }
3233 return volumeInterface;
3234}
3235
3236Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3237{
3238 Vector <VolumeInterface *> volumeInterfaces;
3239 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003240 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003241 }
3242 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3243 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003244 MmapPlaybackThread *mmapPlaybackThread =
3245 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3246 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003247 }
3248 }
3249 return volumeInterfaces;
3250}
3251
Glenn Kasteneeecb982016-02-26 10:44:04 -08003252audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253{
Glenn Kasten9d003132016-04-06 14:38:09 -07003254 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003255 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003256 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3257 for (int retry = 0; retry < maxRetries; retry++) {
3258 // The cast allows wraparound from max positive to min negative instead of abort
3259 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3260 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3261 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3262 // allow wrap by skipping 0 and -1 for session ids
3263 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3264 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3265 return (audio_unique_id_t) (base | use);
3266 }
3267 }
3268 // We have no way of recovering from wraparound
3269 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3270 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271}
3272
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003273AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003274{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003275 AutoMutex lock(mHardwareLock);
3276 if (mPrimaryHardwareDev == nullptr) {
3277 return nullptr;
3278 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003279 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3280 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003281 if(thread->isDuplicating()) {
3282 continue;
3283 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003284 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003285 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003286 return thread;
3287 }
3288 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003289 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003290}
3291
jiabinc52b1ff2019-10-31 17:20:42 -07003292DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003293{
3294 PlaybackThread *thread = primaryPlaybackThread_l();
3295
3296 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003297 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003298 }
3299
jiabinc52b1ff2019-10-31 17:20:42 -07003300 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003301}
3302
Glenn Kastena7335632016-06-09 17:09:53 -07003303AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3304{
3305 size_t minFrameCount = 0;
3306 PlaybackThread *minThread = NULL;
3307 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3308 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3309 if (!thread->isDuplicating()) {
3310 size_t frameCount = thread->frameCountHAL();
3311 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3312 (frameCount == minFrameCount && thread->hasFastMixer() &&
3313 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3314 minFrameCount = frameCount;
3315 minThread = thread;
3316 }
3317 }
3318 }
3319 return minThread;
3320}
3321
jiabineb3bda02020-06-30 14:07:03 -07003322AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3323 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3324 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3325 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3326 return thread;
3327 }
3328 }
3329 return nullptr;
3330}
3331
Eric Laurenta011e352012-03-29 15:51:43 -07003332sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003333 audio_session_t triggerSession,
3334 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003335 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003336 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003337{
3338 Mutex::Autolock _l(mLock);
3339
3340 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3341 status_t playStatus = NAME_NOT_FOUND;
3342 status_t recStatus = NAME_NOT_FOUND;
3343 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3344 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3345 if (playStatus == NO_ERROR) {
3346 return event;
3347 }
3348 }
3349 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3350 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3351 if (recStatus == NO_ERROR) {
3352 return event;
3353 }
3354 }
3355 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3356 mPendingSyncEvents.add(event);
3357 } else {
3358 ALOGV("createSyncEvent() invalid event %d", event->type());
3359 event.clear();
3360 }
3361 return event;
3362}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003363
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364// ----------------------------------------------------------------------------
3365// Effect management
3366// ----------------------------------------------------------------------------
3367
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003368sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3369 return mEffectsFactoryHal;
3370}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371
Glenn Kastenf587ba52012-01-26 16:25:10 -08003372status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373{
3374 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003375 if (mEffectsFactoryHal.get()) {
3376 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3377 } else {
3378 return -ENODEV;
3379 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380}
3381
Glenn Kastenf587ba52012-01-26 16:25:10 -08003382status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383{
3384 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003385 if (mEffectsFactoryHal.get()) {
3386 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3387 } else {
3388 return -ENODEV;
3389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390}
3391
Glenn Kasten5e92a782012-01-30 07:40:52 -08003392status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003393 const effect_uuid_t *pTypeUuid,
3394 uint32_t preferredTypeFlag,
3395 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003397 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3398 return BAD_VALUE;
3399 }
3400
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003402
3403 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003404 return -ENODEV;
3405 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003407 status_t status = NO_ERROR;
3408 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3409 // If uuid is specified, request effect descriptor from that.
3410 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3411 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3412 // If uuid is not specified, look for an available implementation
3413 // of the required type instead.
3414
3415 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3416 effect_descriptor_t desc;
3417 desc.flags = 0; // prevent compiler warning
3418
3419 uint32_t numEffects = 0;
3420 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3421 if (status < 0) {
3422 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3423 return status;
3424 }
3425
3426 bool found = false;
3427 for (uint32_t i = 0; i < numEffects; i++) {
3428 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3429 if (status < 0) {
3430 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3431 continue;
3432 }
3433 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3434 // If matching type found save effect descriptor.
3435 found = true;
3436 *descriptor = desc;
3437
3438 // If there's no preferred flag or this descriptor matches the preferred
3439 // flag, success! If this descriptor doesn't match the preferred
3440 // flag, continue enumeration in case a better matching version of this
3441 // effect type is available. Note that this means if no effect with a
3442 // correct flag is found, the descriptor returned will correspond to the
3443 // last effect that at least had a matching type uuid (if any).
3444 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3445 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3446 break;
3447 }
3448 }
3449 }
3450
3451 if (!found) {
3452 status = NAME_NOT_FOUND;
3453 ALOGW("getEffectDescriptor(): Effect not found by type.");
3454 }
3455 } else {
3456 status = BAD_VALUE;
3457 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3458 }
3459 return status;
3460}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -07003462sp<media::IEffect> AudioFlinger::createEffect(
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 effect_descriptor_t *pDesc,
3464 const sp<IEffectClient>& effectClient,
3465 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003466 audio_io_handle_t io,
Glenn Kastend848eb42016-03-08 13:42:11 -08003467 audio_session_t sessionId,
Eric Laurentb82e6b72019-11-22 17:25:04 -08003468 const AudioDeviceTypeAddr& device,
Svet Ganovbe71aa22015-04-28 12:06:02 -07003469 const String16& opPackageName,
Eric Laurentb6436272016-12-07 19:24:50 -08003470 pid_t pid,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003471 bool probe,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 status_t *status,
3473 int *id,
3474 int *enabled)
3475{
3476 status_t lStatus = NO_ERROR;
3477 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479
Eric Laurentb6436272016-12-07 19:24:50 -08003480 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003481 if (pid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003482 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
3483 ALOGW_IF(pid != -1 && pid != callingPid,
3484 "%s uid %d pid %d tried to pass itself off as pid %d",
3485 __func__, callingUid, callingPid, pid);
3486 pid = callingPid;
3487 }
3488
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003489 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
3490 pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491
3492 if (pDesc == NULL) {
3493 lStatus = BAD_VALUE;
3494 goto Exit;
3495 }
3496
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003497 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003498 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003499 lStatus = NO_INIT;
3500 goto Exit;
3501 }
3502
Andy Hung6096dcd2019-03-13 13:20:30 -07003503 // check audio settings permission for global effects
3504 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3505 if (!settingsAllowed()) {
3506 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3507 lStatus = PERMISSION_DENIED;
3508 goto Exit;
3509 }
3510 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3511 if (!isAudioServerUid(callingUid)) {
3512 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3513 lStatus = PERMISSION_DENIED;
3514 goto Exit;
3515 }
3516
3517 if (io == AUDIO_IO_HANDLE_NONE) {
3518 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3519 lStatus = BAD_VALUE;
3520 goto Exit;
3521 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003522 } else if (sessionId == AUDIO_SESSION_DEVICE) {
3523 if (!modifyDefaultAudioEffectsAllowed(pid, callingUid)) {
3524 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3525 lStatus = PERMISSION_DENIED;
3526 goto Exit;
3527 }
Eric Laurent94876032019-11-13 12:45:28 -08003528 if (io != AUDIO_IO_HANDLE_NONE) {
3529 ALOGE("%s: io handle should not be specified for device effect", __func__);
3530 lStatus = BAD_VALUE;
3531 goto Exit;
3532 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003533 } else {
3534 // general sessionId.
3535
3536 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3537 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3538 lStatus = BAD_VALUE;
3539 goto Exit;
3540 }
3541
3542 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3543 // to prevent creating an effect when one doesn't actually have track with that session?
3544 }
3545
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003547 // Get the full effect descriptor from the uuid/type.
3548 // If the session is the output mix, prefer an auxiliary effect,
3549 // otherwise no preference.
3550 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3551 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
3552 lStatus = getEffectDescriptor(&pDesc->uuid, &pDesc->type, preferredType, &desc);
3553 if (lStatus < 0) {
3554 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3555 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 }
3557
3558 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003559 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3561 lStatus = INVALID_OPERATION;
3562 goto Exit;
3563 }
3564
Eric Laurent59255e42011-07-27 19:49:51 -07003565 // check recording permission for visualizer
3566 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003567 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003568 !recordingAllowed(opPackageName, pid, callingUid)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003569 lStatus = PERMISSION_DENIED;
3570 goto Exit;
3571 }
3572
jiabineb3bda02020-06-30 14:07:03 -07003573 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&desc.type);
3574 if (hapticPlaybackRequired
3575 && (sessionId == AUDIO_SESSION_DEVICE
3576 || sessionId == AUDIO_SESSION_OUTPUT_MIX
3577 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
3578 // haptic-generating effect is only valid when the session id is a general session id
3579 lStatus = INVALID_OPERATION;
3580 goto Exit;
3581 }
3582
Mathias Agopian65ab4712010-07-14 17:59:35 -07003583 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08003584 *pDesc = desc;
Glenn Kasten142f5192014-03-25 17:44:59 -07003585 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003586 // if the output returned by getOutputForEffect() is removed before we lock the
3587 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3588 // and we will exit safely
3589 io = AudioSystem::getOutputForEffect(&desc);
3590 ALOGV("createEffect got output %d", io);
3591 }
3592
3593 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594
Eric Laurentb82e6b72019-11-22 17:25:04 -08003595 if (sessionId == AUDIO_SESSION_DEVICE) {
3596 sp<Client> client = registerPid(pid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003597 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003598 handle = mDeviceEffectManager.createEffect_l(
3599 &desc, device, client, effectClient, mPatchPanel.patches_l(),
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003600 enabled, &lStatus, probe);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003601 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3602 // remove local strong reference to Client with mClientLock held
3603 Mutex::Autolock _cl(mClientLock);
3604 client.clear();
3605 } else {
3606 // handle must be valid here, but check again to be safe.
3607 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
3608 }
3609 goto Register;
3610 }
3611
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 // If output is not specified try to find a matching audio session ID in one of the
3613 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003614 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3615 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003616 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3617 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003618 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003619 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003620 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3621 if (io == AUDIO_IO_HANDLE_NONE) {
3622 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003624 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003625 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003626 }
Andy Hung444bb552019-03-14 17:06:39 -07003627
3628 // If you wish to create a Record preprocessing AudioEffect in Java,
3629 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3630 // Otherwise it will fail when created on a Playback thread by legacy
3631 // handling below. Ditto with Mmap, the associated Mmap track must be created
3632 // before creating the AudioEffect or the io handle must be specified.
3633 //
3634 // Detect if the effect is created after an AudioRecord is destroyed.
3635 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3636 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
3637 " for session %d no longer exists",
3638 __func__, desc.name, sessionId);
3639 lStatus = PERMISSION_DENIED;
3640 goto Exit;
3641 }
3642
3643 // Legacy handling of creating an effect on an expired or made-up
3644 // session id. We think that it is a Playback effect.
3645 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003646 // If no output thread contains the requested session ID, default to
3647 // first output. The effect chain will be moved to the correct output
3648 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003649 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003650 io = mPlaybackThreads.keyAt(0);
3651 }
Steve Block3856b092011-10-20 11:56:00 +01003652 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Andy Hung1631f062019-03-12 19:39:03 -07003653 } else if (checkPlaybackThread_l(io) != nullptr) {
3654 // allow only one effect chain per sessionId on mPlaybackThreads.
3655 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3656 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07003657 if (io == checkIo) {
3658 if (hapticPlaybackRequired
3659 && mPlaybackThreads.valueAt(i)
3660 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3661 ALOGE("%s: haptic playback thread is required while the required playback "
3662 "thread(io=%d) doesn't support", __func__, (int)io);
3663 lStatus = BAD_VALUE;
3664 goto Exit;
3665 }
3666 continue;
3667 }
Andy Hung1631f062019-03-12 19:39:03 -07003668 const uint32_t sessionType =
3669 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3670 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3671 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
3672 __func__, desc.name, (int)io, (int)sessionId, (int)checkIo);
3673 android_errorWriteLog(0x534e4554, "123237974");
3674 lStatus = BAD_VALUE;
3675 goto Exit;
3676 }
3677 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003678 }
3679 ThreadBase *thread = checkRecordThread_l(io);
3680 if (thread == NULL) {
3681 thread = checkPlaybackThread_l(io);
3682 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003683 thread = checkMmapThread_l(io);
3684 if (thread == NULL) {
3685 ALOGE("createEffect() unknown output thread");
3686 lStatus = BAD_VALUE;
3687 goto Exit;
3688 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003689 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003690 } else {
3691 // Check if one effect chain was awaiting for an effect to be created on this
3692 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003693 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003694 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003695 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003696 thread->addEffectChain_l(chain);
3697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003699
Eric Laurent021cf962014-05-13 10:18:14 -07003700 sp<Client> client = registerPid(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003702 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003703 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07003704 ThreadBase *oriThread = nullptr;
3705 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3706 ThreadBase *hapticThread = hapticPlaybackThread_l();
3707 if (hapticThread == nullptr) {
3708 ALOGE("%s haptic thread not found while it is required", __func__);
3709 lStatus = INVALID_OPERATION;
3710 goto Exit;
3711 }
3712 if (hapticThread != thread) {
3713 // Force to use haptic thread for haptic-generating effect.
3714 oriThread = thread;
3715 thread = hapticThread;
3716 }
3717 }
Eric Laurentde070132010-07-13 04:45:46 -07003718 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003719 &desc, enabled, &lStatus, pinned, probe);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003720 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003721 // remove local strong reference to Client with mClientLock held
3722 Mutex::Autolock _cl(mClientLock);
3723 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003724 } else {
3725 // handle must be valid here, but check again to be safe.
3726 if (handle.get() != nullptr && id != nullptr) *id = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07003727 // Invalidate audio session when haptic playback is created.
3728 if (hapticPlaybackRequired && oriThread != nullptr) {
3729 // invalidateTracksForAudioSession will trigger locking the thread.
3730 oriThread->invalidateTracksForAudioSession(sessionId);
3731 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003732 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733 }
3734
Eric Laurentb82e6b72019-11-22 17:25:04 -08003735Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003736 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003737 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003738 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003739 if (effect != nullptr) {
3740 status_t rStatus = effect->updatePolicyState();
3741 if (rStatus != NO_ERROR) {
3742 lStatus = rStatus;
3743 }
3744 }
3745 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003746 handle.clear();
3747 }
3748
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07003750 *status = lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003751 return handle;
3752}
3753
Glenn Kastend848eb42016-03-08 13:42:11 -08003754status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003755 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003756{
Steve Block3856b092011-10-20 11:56:00 +01003757 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003758 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003759 Mutex::Autolock _l(mLock);
3760 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003761 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003762 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 }
Eric Laurentde070132010-07-13 04:45:46 -07003764 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3765 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003766 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003767 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 }
Eric Laurentde070132010-07-13 04:45:46 -07003769 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3770 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003771 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003772 return BAD_VALUE;
3773 }
3774
3775 Mutex::Autolock _dl(dstThread->mLock);
3776 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003777 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003778}
3779
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003780
3781void AudioFlinger::setEffectSuspended(int effectId,
3782 audio_session_t sessionId,
3783 bool suspended)
3784{
3785 Mutex::Autolock _l(mLock);
3786
3787 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3788 if (thread == nullptr) {
3789 return;
3790 }
3791 Mutex::Autolock _sl(thread->mLock);
3792 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3793 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3794}
3795
3796
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003797// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003798status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003799 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003800 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003801{
Steve Block3856b092011-10-20 11:56:00 +01003802 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003803 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003804
Eric Laurent59255e42011-07-27 19:49:51 -07003805 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003806 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003807 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003808 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003809 return INVALID_OPERATION;
3810 }
3811
Eric Laurent4c415062016-06-17 16:14:16 -07003812 // Check whether the destination thread and all effects in the chain are compatible
3813 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003814 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003815 " destination thread %p is not compatible with effects in the chain",
3816 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003817 return INVALID_OPERATION;
3818 }
3819
Eric Laurent39e94f82010-07-28 01:32:47 -07003820 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003821 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003822 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003823 // removed.
3824 srcThread->removeEffectChain_l(chain);
3825
3826 // transfer all effects one by one so that new effect chain is created on new thread with
3827 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003828 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003829 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003830 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003831 Vector< sp<EffectModule> > removed;
3832 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003833 while (effect != 0) {
3834 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003835 removed.add(effect);
3836 status = dstThread->addEffect_l(effect);
3837 if (status != NO_ERROR) {
3838 break;
3839 }
Eric Laurentec35a142011-10-05 17:42:25 -07003840 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3841 if (effect->state() == EffectModule::ACTIVE ||
3842 effect->state() == EffectModule::STOPPING) {
3843 effect->start();
3844 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003845 // if the move request is not received from audio policy manager, the effect must be
3846 // re-registered with the new strategy and output
3847 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003848 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003849 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003850 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003851 status = NO_INIT;
3852 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003853 }
3854 strategy = dstChain->strategy();
3855 }
Eric Laurentde070132010-07-13 04:45:46 -07003856 effect = chain->getEffectFromId_l(0);
3857 }
3858
Eric Laurent5baf2af2013-09-12 17:37:00 -07003859 if (status != NO_ERROR) {
3860 for (size_t i = 0; i < removed.size(); i++) {
3861 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003862 }
3863 }
3864
3865 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866}
3867
Eric Laurent6c796322019-04-09 14:13:17 -07003868status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3869 const sp<PlaybackThread>& dstThread,
3870 sp<PlaybackThread> *srcThread)
3871{
3872 status_t status = NO_ERROR;
3873 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003874 sp<PlaybackThread> thread =
3875 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003876
3877 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3878 Mutex::Autolock _dl(dstThread->mLock);
3879 Mutex::Autolock _sl(thread->mLock);
3880 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3881 sp<EffectChain> dstChain;
3882 if (srcChain == 0) {
3883 return INVALID_OPERATION;
3884 }
3885
3886 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
3887 if (effect == 0) {
3888 return INVALID_OPERATION;
3889 }
3890 thread->removeEffect_l(effect);
3891 status = dstThread->addEffect_l(effect);
3892 if (status != NO_ERROR) {
3893 thread->addEffect_l(effect);
3894 status = INVALID_OPERATION;
3895 goto Exit;
3896 }
3897
Eric Laurent6b446ce2019-12-13 10:56:31 -08003898 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003899 if (dstChain == 0) {
3900 thread->addEffect_l(effect);
3901 status = INVALID_OPERATION;
3902 }
3903
3904Exit:
3905 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3906 if (effect->state() == EffectModule::ACTIVE ||
3907 effect->state() == EffectModule::STOPPING) {
3908 effect->start();
3909 }
3910 }
3911
3912 if (status == NO_ERROR && srcThread != nullptr) {
3913 *srcThread = thread;
3914 }
3915 return status;
3916}
3917
Eric Laurent5baf2af2013-09-12 17:37:00 -07003918bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07003919{
3920 if (mGlobalEffectEnableTime != 0 &&
3921 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
3922 return true;
3923 }
3924
3925 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3926 sp<EffectChain> ec =
3927 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003928 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07003929 return true;
3930 }
3931 }
3932 return false;
3933}
3934
Eric Laurent5baf2af2013-09-12 17:37:00 -07003935void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07003936{
3937 Mutex::Autolock _l(mLock);
3938
3939 mGlobalEffectEnableTime = systemTime();
3940
3941 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3942 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
3943 if (t->mType == ThreadBase::OFFLOAD) {
3944 t->invalidateTracks(AUDIO_STREAM_MUSIC);
3945 }
3946 }
3947
3948}
3949
Eric Laurentaaa44472014-09-12 17:41:50 -07003950status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
3951{
Eric Laurentd8365c52017-07-16 15:27:05 -07003952 // clear possible suspended state before parking the chain so that it starts in default state
3953 // when attached to a new record thread
3954 chain->setEffectSuspended_l(FX_IID_AEC, false);
3955 chain->setEffectSuspended_l(FX_IID_NS, false);
3956
Glenn Kastend848eb42016-03-08 13:42:11 -08003957 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003958 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003959 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003960 if (index >= 0) {
3961 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
3962 return ALREADY_EXISTS;
3963 }
3964 mOrphanEffectChains.add(session, chain);
3965 return NO_ERROR;
3966}
3967
3968sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
3969{
3970 sp<EffectChain> chain;
3971 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003972 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003973 if (index >= 0) {
3974 chain = mOrphanEffectChains.valueAt(index);
3975 mOrphanEffectChains.removeItemsAt(index);
3976 }
3977 return chain;
3978}
3979
3980bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
3981{
3982 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08003983 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07003984 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003985 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003986 if (index >= 0) {
3987 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003988 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003989 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07003990 mOrphanEffectChains.removeItemsAt(index);
3991 }
3992 return true;
3993 }
3994 return false;
3995}
3996
3997
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998// ----------------------------------------------------------------------------
3999
4000status_t AudioFlinger::onTransact(
4001 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4002{
4003 return BnAudioFlinger::onTransact(code, data, reply, flags);
4004}
4005
Glenn Kasten63238ef2015-03-02 15:50:29 -08004006} // namespace android