blob: 3562b00a761763e95c619d7d6e0d6e38c970e6ea [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
jiabina392a552019-09-23 10:34:20 -070022// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
23#define AUDIO_ARRAYS_STATIC_CHECK 1
24
Glenn Kasten153b9fe2013-07-15 11:23:36 -070025#include "Configuration.h"
Glenn Kastenda6ef132013-01-10 12:31:01 -080026#include <dirent.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include <math.h>
28#include <signal.h>
Eric Tan7b651152018-07-13 10:17:19 -070029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/time.h>
31#include <sys/resource.h>
Mikhail Naganov88b30d22020-03-09 19:43:13 +000032#include <thread>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -080034#include <android/media/IAudioPolicyService.h>
jiabin57303cc2018-12-18 15:45:57 -080035#include <android/os/IExternalVibratorService.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080036#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <binder/IServiceManager.h>
38#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070039#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/Parcel.h>
Mikhail Naganova0c91332016-09-19 10:01:12 -070041#include <media/audiohal/DeviceHalInterface.h>
42#include <media/audiohal/DevicesFactoryHalInterface.h>
43#include <media/audiohal/EffectsFactoryHalInterface.h>
Mikhail Naganov00260b52016-10-13 12:54:24 -070044#include <media/AudioParameter.h>
Andy Hungb68f5eb2019-12-03 16:49:17 -080045#include <media/MediaMetricsItem.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070046#include <media/TypeConverter.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080047#include <mediautils/TimeCheck.h>
Andy Hung35fec5f2016-04-13 14:21:48 -070048#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <utils/String16.h>
50#include <utils/threads.h>
51
Steven Morelandf0c02ce2018-02-23 14:53:55 -080052#include <cutils/atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <cutils/properties.h>
54
Dima Zavin64760242011-05-11 14:15:23 -070055#include <system/audio.h>
Mikhail Naganov2996f672019-04-18 12:29:59 -070056#include <audiomanager/AudioManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include "AudioFlinger.h"
Andy Hung8946a282018-04-19 20:04:56 -070059#include "NBAIO_Tee.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Andy Hung6770c6f2015-04-07 13:43:36 -070061#include <media/AudioResamplerPublic.h>
62
Mikhail Naganov9fe94012016-10-14 14:57:40 -070063#include <system/audio_effects/effect_visualizer.h>
64#include <system/audio_effects/effect_ns.h>
65#include <system/audio_effects/effect_aec.h>
jiabineb3bda02020-06-30 14:07:03 -070066#include <system/audio_effects/effect_hapticgenerator.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067
Glenn Kasten3b21c502011-12-15 09:52:39 -080068#include <audio_utils/primitives.h>
69
Eric Laurentfeb0db62011-07-22 09:04:31 -070070#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080071
Glenn Kasten9e58b552013-01-18 15:09:48 -080072#include <media/IMediaLogService.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070073#include <media/AidlConversion.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080074#include <media/AudioValidator.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080075#include <media/nbaio/Pipe.h>
76#include <media/nbaio/PipeReader.h>
Wei Jia3f273d12015-11-24 09:06:49 -080077#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070078#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070080#include <mediautils/TimeCheck.h>
Glenn Kasten4182c4e2013-07-15 14:45:07 -070081#include <private/android_filesystem_config.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080082
rago3bd1c872016-09-26 12:58:14 -070083//#define BUFLOG_NDEBUG 0
84#include <BufLog.h>
85
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080086#include "TypedLogger.h"
87
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700105using media::IEffectClient;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700106using media::permission::Identity;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700107
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800108static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
109static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Eric Laurent021cf962014-05-13 10:18:14 -0700110static const char kClientLockedString[] = "Client lock is taken\n";
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700111static const char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
Glenn Kasten58912562012-04-03 10:45:00 -0700113
John Grossman4ff14ba2012-02-08 16:37:41 -0800114nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800115
Eric Laurent81784c32012-11-19 14:55:58 -0800116uint32_t AudioFlinger::mScreenState;
Glenn Kasten3ed29202012-08-07 15:24:44 -0700117
Eric Laurent813e2a72013-08-31 12:59:48 -0700118// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
119// we define a minimum time during which a global effect is considered enabled.
120static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
121
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700122// Keep a strong reference to media.log service around forever.
123// The service is within our parent process so it can never die in a way that we could observe.
124// These two variables are const after initialization.
125static sp<IBinder> sMediaLogServiceAsBinder;
126static sp<IMediaLogService> sMediaLogService;
127
128static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
129
130static void sMediaLogInit()
131{
132 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
133 if (sMediaLogServiceAsBinder != 0) {
134 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
135 }
136}
137
jiabin57303cc2018-12-18 15:45:57 -0800138// Keep a strong reference to external vibrator service
139static sp<os::IExternalVibratorService> sExternalVibratorService;
140
141static sp<os::IExternalVibratorService> getExternalVibratorService() {
142 if (sExternalVibratorService == 0) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700143 sp<IBinder> binder = defaultServiceManager()->getService(
jiabin57303cc2018-12-18 15:45:57 -0800144 String16("external_vibrator_service"));
145 if (binder != 0) {
146 sExternalVibratorService =
147 interface_cast<os::IExternalVibratorService>(binder);
148 }
149 }
150 return sExternalVibratorService;
151}
152
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000153class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
154 public:
155 void onNewDevicesAvailable() override {
156 // Start a detached thread to execute notification in parallel.
157 // This is done to prevent mutual blocking of audio_flinger and
158 // audio_policy services during system initialization.
159 std::thread notifier([]() {
160 AudioSystem::onNewAudioModulesAvailable();
161 });
162 notifier.detach();
163 }
164};
165
Eric Laurentec376dc2021-04-08 20:41:22 +0200166// TODO b/182392769: use identity util
167/* static */
168media::permission::Identity AudioFlinger::checkIdentityPackage(
169 const media::permission::Identity& identity) {
170 Vector<String16> packages;
171 PermissionController{}.getPackagesForUid(identity.uid, packages);
172
173 Identity checkedIdentity = identity;
174 if (!identity.packageName.has_value() || identity.packageName.value().size() == 0) {
175 if (!packages.isEmpty()) {
176 checkedIdentity.packageName =
177 std::move(legacy2aidl_String16_string(packages[0]).value());
178 }
179 } else {
180 String16 opPackageLegacy = VALUE_OR_FATAL(
181 aidl2legacy_string_view_String16(identity.packageName.value_or("")));
182 if (std::find_if(packages.begin(), packages.end(),
183 [&opPackageLegacy](const auto& package) {
184 return opPackageLegacy == package; }) == packages.end()) {
185 ALOGW("The package name(%s) provided does not correspond to the uid %d",
186 identity.packageName.value_or("").c_str(), identity.uid);
187 checkedIdentity.packageName = std::optional<std::string>();
188 }
189 }
190 return checkedIdentity;
191}
192
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193// ----------------------------------------------------------------------------
194
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700195std::string formatToString(audio_format_t format) {
196 std::string result;
197 FormatConverter::toString(format, result);
198 return result;
Marco Nelissenb2208842014-02-07 14:00:50 -0800199}
200
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201// ----------------------------------------------------------------------------
202
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800203void AudioFlinger::instantiate() {
204 sp<IServiceManager> sm(defaultServiceManager());
205 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
206 new AudioFlingerServerAdapter(new AudioFlinger()), false,
207 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
208}
209
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210AudioFlinger::AudioFlinger()
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800211 : mMediaLogNotifier(new AudioFlinger::MediaLogNotifier()),
John Grossman4ff14ba2012-02-08 16:37:41 -0800212 mPrimaryHardwareDev(NULL),
Glenn Kasten9ea65d02014-01-17 10:21:24 -0800213 mAudioHwDevs(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700214 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800215 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mMasterMute(false),
Glenn Kastend2e67e12016-04-11 08:26:37 -0700217 // mNextUniqueId(AUDIO_UNIQUE_ID_USE_MAX),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMode(AUDIO_MODE_INVALID),
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700219 mBtNrecIsOff(false),
220 mIsLowRamDevice(true),
Eric Laurent813e2a72013-08-31 12:59:48 -0700221 mIsDeviceTypeKnown(false),
Andy Hung6f248bb2018-01-23 14:04:37 -0800222 mTotalMemory(0),
223 mClientSharedHeapSize(kMinimumClientSharedHeapSizeBytes),
Glenn Kasten4ea00a22014-06-02 08:29:22 -0700224 mGlobalEffectEnableTime(0),
Mikhail Naganovdea53042018-04-26 13:10:21 -0700225 mPatchPanel(this),
Eric Laurentb82e6b72019-11-22 17:25:04 -0800226 mDeviceEffectManager(this),
Eric Laurent72e3f392015-05-20 14:43:50 -0700227 mSystemReady(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100229 // Move the audio session unique ID generator start base as time passes to limit risk of
230 // generating the same ID again after an audioserver restart.
231 // This is important because clients will reuse previously allocated audio session IDs
232 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
233 // active clients.
234 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
235 // between allocation ranges and not reaching wrap around too soon.
236 timespec ts{};
237 clock_gettime(CLOCK_MONOTONIC, &ts);
238 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
239 uint32_t sessionBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700240 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
241 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100242 mNextUniqueIds[use] =
243 ((use == AUDIO_UNIQUE_ID_USE_SESSION) ? sessionBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700244 }
245
Eric Laurent94ca1142020-10-07 10:45:20 -0700246#if 1
247 // FIXME See bug 165702394 and bug 168511485
248 const bool doLog = false;
249#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800250 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700251#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800252 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800253 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
254 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700255 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800256 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700257
Wei Jia3f273d12015-11-24 09:06:49 -0800258 // reset battery stats.
259 // if the audio service has crashed, battery stats could be left
260 // in bad state, reset the state upon service start.
261 BatteryNotifier::getInstance().noteResetAudio();
262
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700263 mDevicesFactoryHal = DevicesFactoryHalInterface::create();
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700264 mEffectsFactoryHal = EffectsFactoryHalInterface::create();
265
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800266 mMediaLogNotifier->run("MediaLogNotifier");
Eric Laurent42896a02019-09-27 15:40:33 -0700267 std::vector<pid_t> halPids;
268 mDevicesFactoryHal->getHalPids(&halPids);
269 TimeCheck::setAudioHalPids(halPids);
Andy Hungb68f5eb2019-12-03 16:49:17 -0800270
271 // Notify that we have started (also called when audioserver service restarts)
272 mediametrics::LogItem(mMetricsId)
273 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
274 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700275}
276
277void AudioFlinger::onFirstRef()
278{
Eric Laurent93575202011-01-18 18:39:02 -0800279 Mutex::Autolock _l(mLock);
280
Dima Zavin799a70e2011-04-18 16:57:27 -0700281 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800282 char val_str[PROPERTY_VALUE_MAX] = { 0 };
283 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
284 uint32_t int_val;
285 if (1 == sscanf(val_str, "%u", &int_val)) {
286 mStandbyTimeInNsecs = milliseconds(int_val);
287 ALOGI("Using %u mSec as standby time.", int_val);
288 } else {
289 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
290 ALOGI("Using default %u mSec as standby time.",
291 (uint32_t)(mStandbyTimeInNsecs / 1000000));
292 }
293 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294
Eric Laurenta4c5a552012-03-29 10:12:40 -0700295 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800296
Andy Hung6626a012021-01-12 13:38:00 -0800297 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000298
299 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
300 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301}
302
Eric Laurent42896a02019-09-27 15:40:33 -0700303status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
304 TimeCheck::setAudioHalPids(pids);
305 return NO_ERROR;
306}
307
jiabin1319f5a2021-03-30 22:21:24 +0000308status_t AudioFlinger::setVibratorInfos(
309 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
310 Mutex::Autolock _l(mLock);
311 mAudioVibratorInfos = vibratorInfos;
312 return NO_ERROR;
313}
314
315// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
316const media::AudioVibratorInfo* AudioFlinger::getDefaultVibratorInfo_l() {
317 if (mAudioVibratorInfos.empty()) {
318 return nullptr;
319 }
320 return &mAudioVibratorInfos.front();
321}
322
Mathias Agopian65ab4712010-07-14 17:59:35 -0700323AudioFlinger::~AudioFlinger()
324{
325 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700326 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700327 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328 }
329 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700330 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700331 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332 }
Andy Hungb4946b62019-03-14 11:19:28 -0700333 while (!mMmapThreads.isEmpty()) {
334 const audio_io_handle_t io = mMmapThreads.keyAt(0);
335 if (mMmapThreads.valueAt(0)->isOutput()) {
336 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
337 } else {
338 closeInput_nonvirtual(io); // removes entry from mMmapThreads
339 }
340 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700341
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800342 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
343 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700344 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700346
347 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700348 if (sMediaLogService != 0) {
349 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
350 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
351 mUnregisteredWriters.pop();
352 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700353 }
354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355}
356
Eric Laurentfc235202016-12-20 18:48:17 -0800357//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800358__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800359status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
360 const audio_attributes_t *attr,
361 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700362 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800363 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800364 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800365 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700366 sp<MmapStreamInterface>& interface,
367 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800368{
Andy Hung6626a012021-01-12 13:38:00 -0800369 // TODO: Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
370 // This allows moving oboeservice (AAudio) to a separate process in the future.
371 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800372 status_t ret = NO_INIT;
373 if (af != 0) {
374 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800375 direction, attr, config, client, deviceId,
376 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800377 }
378 return ret;
379}
380
Eric Laurent6acd1d42017-01-04 14:23:29 -0800381status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
382 const audio_attributes_t *attr,
383 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700384 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800385 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800386 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800387 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700388 sp<MmapStreamInterface>& interface,
389 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800390{
391 status_t ret = initCheck();
392 if (ret != NO_ERROR) {
393 return ret;
394 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800395 audio_session_t actualSessionId = *sessionId;
396 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
397 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
398 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800399 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700400 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800401 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700402 audio_attributes_t localAttr = *attr;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800403 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
404 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
405 fullConfig.sample_rate = config->sample_rate;
406 fullConfig.channel_mask = config->channel_mask;
407 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800408 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurent42984412019-05-09 17:57:03 -0700409
410 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800411 actualSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700412 &streamType, client.identity,
Ricardo Correa57a37692020-03-23 17:27:25 -0700413 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800414 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
415 AUDIO_OUTPUT_FLAG_DIRECT),
Kevin Rocard153f92d2018-12-18 18:33:28 -0800416 deviceId, &portId, &secondaryOutputs);
417 ALOGW_IF(!secondaryOutputs.empty(),
418 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800419 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700420 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700421 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800422 actualSessionId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700423 client.identity,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800424 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700425 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800426 }
427 if (ret != NO_ERROR) {
428 return ret;
429 }
430
431 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
432 // audio policy manager and we can retrieve it
433 sp<MmapThread> thread = mMmapThreads.valueFor(io);
434 if (thread != 0) {
435 interface = new MmapThreadHandle(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700436 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700437 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800438 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800439 config->sample_rate = thread->sampleRate();
440 config->channel_mask = thread->channelMask();
441 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800442 } else {
Eric Laurentad2e7b92017-09-14 20:06:42 -0700443 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700444 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700445 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800446 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700447 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800448 ret = NO_INIT;
449 }
450
451 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
452
Eric Laurentfc235202016-12-20 18:48:17 -0800453 return ret;
454}
455
jiabin57303cc2018-12-18 15:45:57 -0800456/* static */
457int AudioFlinger::onExternalVibrationStart(const sp<os::ExternalVibration>& externalVibration) {
458 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
jiabin78dc9c82021-02-22 19:13:29 +0000459 if (evs != nullptr) {
jiabin57303cc2018-12-18 15:45:57 -0800460 int32_t ret;
461 binder::Status status = evs->onExternalVibrationStart(*externalVibration, &ret);
462 if (status.isOk()) {
jiabin78dc9c82021-02-22 19:13:29 +0000463 ALOGD("%s, start external vibration with intensity as %d", __func__, ret);
jiabin57303cc2018-12-18 15:45:57 -0800464 return ret;
465 }
466 }
jiabin78dc9c82021-02-22 19:13:29 +0000467 ALOGD("%s, start external vibration with intensity as MUTE due to %s",
468 __func__,
469 evs == nullptr ? "external vibration service not found"
470 : "error when querying intensity");
jiabine70bc7f2020-06-30 22:07:55 -0700471 return static_cast<int>(os::HapticScale::MUTE);
jiabin57303cc2018-12-18 15:45:57 -0800472}
473
474/* static */
475void AudioFlinger::onExternalVibrationStop(const sp<os::ExternalVibration>& externalVibration) {
476 sp<os::IExternalVibratorService> evs = getExternalVibratorService();
477 if (evs != 0) {
478 evs->onExternalVibrationStop(*externalVibration);
479 }
480}
481
Eric Laurentb82e6b72019-11-22 17:25:04 -0800482status_t AudioFlinger::addEffectToHal(audio_port_handle_t deviceId,
483 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700484 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800485 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
486 if (audioHwDevice == nullptr) {
487 return NO_INIT;
488 }
489 return audioHwDevice->hwDevice()->addDeviceEffect(deviceId, effect);
490}
491
492status_t AudioFlinger::removeEffectFromHal(audio_port_handle_t deviceId,
493 audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect) {
Eric Laurent00abf0d2020-04-22 19:28:22 -0700494 AutoMutex lock(mHardwareLock);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800495 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(hwModuleId);
496 if (audioHwDevice == nullptr) {
497 return NO_INIT;
498 }
499 return audioHwDevice->hwDevice()->removeDeviceEffect(deviceId, effect);
500}
501
Eric Laurenta4c5a552012-03-29 10:12:40 -0700502static const char * const audio_interfaces[] = {
503 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
504 AUDIO_HARDWARE_MODULE_ID_A2DP,
505 AUDIO_HARDWARE_MODULE_ID_USB,
506};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700507
Phil Burk062e67a2015-02-11 13:40:50 -0800508AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700509 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700510 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700511{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700512 // if module is 0, the request comes from an old policy manager and we should load
513 // well known modules
Eric Laurent00abf0d2020-04-22 19:28:22 -0700514 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700515 if (module == 0) {
516 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700517 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700518 loadHwModule_l(audio_interfaces[i]);
519 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700520 // then try to find a module supporting the requested device.
521 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
522 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700523 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
524 uint32_t supportedDevices;
525 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700526 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700527 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700528 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700529 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700530 } else {
531 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700532 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
533 if (audioHwDevice != NULL) {
534 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700535 }
536 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700537
Dima Zavin799a70e2011-04-18 16:57:27 -0700538 return NULL;
539}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540
Glenn Kasten0f11b512014-01-31 16:18:54 -0800541void AudioFlinger::dumpClients(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 String8 result;
544
545 result.append("Clients:\n");
546 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800547 sp<Client> client = mClients.valueAt(i).promote();
548 if (client != 0) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800549 result.appendFormat(" pid: %d\n", client->pid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550 }
551 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700552
Eric Laurentd1b28d42013-09-18 18:47:13 -0700553 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800554 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700555 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800556 const pid_t pid = mNotificationClients[i]->getPid();
557 const uid_t uid = mNotificationClients[i]->getUid();
558 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
559 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700560 }
561
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700562 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800563 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700564 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
565 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800566 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
567 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
568 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571}
572
573
Glenn Kasten0f11b512014-01-31 16:18:54 -0800574void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575{
576 const size_t SIZE = 256;
577 char buffer[SIZE];
578 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800579 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580
John Grossman4ff14ba2012-02-08 16:37:41 -0800581 snprintf(buffer, SIZE, "Hardware status: %d\n"
582 "Standby Time mSec: %u\n",
583 hardwareStatus,
584 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 result.append(buffer);
586 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587}
588
Glenn Kasten0f11b512014-01-31 16:18:54 -0800589void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590{
591 const size_t SIZE = 256;
592 char buffer[SIZE];
593 String8 result;
594 snprintf(buffer, SIZE, "Permission Denial: "
595 "can't dump AudioFlinger from pid=%d, uid=%d\n",
596 IPCThreadState::self()->getCallingPid(),
597 IPCThreadState::self()->getCallingUid());
598 result.append(buffer);
599 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600}
601
Eric Laurent81784c32012-11-19 14:55:58 -0800602bool AudioFlinger::dumpTryLock(Mutex& mutex)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603{
Mikhail Naganov959e2d02019-03-28 11:08:19 -0700604 status_t err = mutex.timedLock(kDumpLockTimeoutNs);
605 return err == NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606}
607
608status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
609{
Glenn Kasten44deb052012-02-05 18:09:08 -0800610 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 dumpPermissionDenial(fd, args);
612 } else {
613 // get state of hardware lock
Eric Laurent81784c32012-11-19 14:55:58 -0800614 bool hardwareLocked = dumpTryLock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 if (!hardwareLocked) {
616 String8 result(kHardwareLockedString);
617 write(fd, result.string(), result.size());
618 } else {
619 mHardwareLock.unlock();
620 }
621
Eric Tan7b651152018-07-13 10:17:19 -0700622 const bool locked = dumpTryLock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623
624 // failed to lock - AudioFlinger is probably deadlocked
625 if (!locked) {
626 String8 result(kDeadlockedString);
627 write(fd, result.string(), result.size());
628 }
629
Eric Laurent021cf962014-05-13 10:18:14 -0700630 bool clientLocked = dumpTryLock(mClientLock);
631 if (!clientLocked) {
632 String8 result(kClientLockedString);
633 write(fd, result.string(), result.size());
634 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700635
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700636 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700637 mEffectsFactoryHal->dumpEffects(fd);
638 } else {
639 String8 result(kNoEffectsFactory);
640 write(fd, result.string(), result.size());
641 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700642
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643 dumpClients(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700644 if (clientLocked) {
645 mClientLock.unlock();
646 }
647
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648 dumpInternals(fd, args);
649
650 // dump playback threads
651 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
652 mPlaybackThreads.valueAt(i)->dump(fd, args);
653 }
654
655 // dump record threads
656 for (size_t i = 0; i < mRecordThreads.size(); i++) {
657 mRecordThreads.valueAt(i)->dump(fd, args);
658 }
659
Eric Laurent6acd1d42017-01-04 14:23:29 -0800660 // dump mmap threads
661 for (size_t i = 0; i < mMmapThreads.size(); i++) {
662 mMmapThreads.valueAt(i)->dump(fd, args);
663 }
664
Eric Laurentaaa44472014-09-12 17:41:50 -0700665 // dump orphan effect chains
666 if (mOrphanEffectChains.size() != 0) {
667 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
668 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
669 mOrphanEffectChains.valueAt(i)->dump(fd, args);
670 }
671 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700672 // dump all hardware devs
673 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700674 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
675 dev->dump(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700677
Mikhail Naganov201369b2018-05-16 16:52:32 -0700678 mPatchPanel.dump(fd);
679
Eric Laurentb82e6b72019-11-22 17:25:04 -0800680 mDeviceEffectManager.dump(fd);
681
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700682 // dump external setParameters
683 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
684 dprintf(fd, "\n%s setParameters:\n", name);
685 logger.dump(fd, " " /* prefix */);
686 };
687 dumpLogger(mRejectedSetParameterLog, "Rejected");
688 dumpLogger(mAppSetParameterLog, "App");
689 dumpLogger(mSystemSetParameterLog, "System");
690
Andy Hunga8115dc2018-08-24 15:51:59 -0700691 // dump historical threads in the last 10 seconds
692 const std::string threadLog = mThreadLog.dumpToString(
693 "Historical Thread Log ", 0 /* lines */,
694 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
695 write(fd, threadLog.c_str(), threadLog.size());
696
rago3bd1c872016-09-26 12:58:14 -0700697 BUFLOG_RESET;
698
Glenn Kastend65d73c2012-06-22 17:21:07 -0700699 if (locked) {
700 mLock.unlock();
701 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800702
Andy Hung8946a282018-04-19 20:04:56 -0700703#ifdef TEE_SINK
704 // NBAIO_Tee dump is safe to call outside of AF lock.
705 NBAIO_Tee::dumpAll(fd, "_DUMP");
706#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800707 // append a copy of media.log here by forwarding fd to it, but don't attempt
708 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700709 if (sMediaLogServiceAsBinder != 0) {
710 dprintf(fd, "\nmedia.log:\n");
711 Vector<String16> args;
712 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800713 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700714
715 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700716 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700717 bool unreachableMemory = false;
718 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700719 if (arg == String16("-m")) {
720 dumpMem = true;
721 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700722 unreachableMemory = true;
723 }
724 }
725
Andy Hung07b745e2016-05-23 16:21:07 -0700726 if (dumpMem) {
727 dprintf(fd, "\nDumping memory:\n");
728 std::string s = dumpMemoryAddresses(100 /* limit */);
729 write(fd, s.c_str(), s.size());
730 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700731 if (unreachableMemory) {
732 dprintf(fd, "\nDumping unreachable memory:\n");
733 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700734 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700735 write(fd, s.c_str(), s.size());
736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 }
738 return NO_ERROR;
739}
740
Eric Laurent021cf962014-05-13 10:18:14 -0700741sp<AudioFlinger::Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800742{
Eric Laurent021cf962014-05-13 10:18:14 -0700743 Mutex::Autolock _cl(mClientLock);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800744 // If pid is already in the mClients wp<> map, then use that entry
745 // (for which promote() is always != 0), otherwise create a new entry and Client.
746 sp<Client> client = mClients.valueFor(pid).promote();
747 if (client == 0) {
748 client = new Client(this, pid);
749 mClients.add(pid, client);
750 }
751
752 return client;
753}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754
Glenn Kasten9e58b552013-01-18 15:09:48 -0800755sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
756{
Jiabin Huang60766082020-07-28 22:03:56 +0000757 // If there is no memory allocated for logs, return a no-op writer that does nothing.
758 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700759 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800760 return new NBLog::Writer();
761 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700762 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
763 // If allocation fails, consult the vector of previously unregistered writers
764 // and garbage-collect one or more them until an allocation succeeds
765 if (shared == 0) {
766 Mutex::Autolock _l(mUnregisteredWritersLock);
767 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
768 {
769 // Pick the oldest stale writer to garbage-collect
770 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
771 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700772 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700773 // Now the media.log remote reference to IMemory is gone. When our last local
774 // reference to IMemory also drops to zero at end of this block,
775 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
776 }
777 // Re-attempt the allocation
778 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
779 if (shared != 0) {
780 goto success;
781 }
782 }
783 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +0000784 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -0700785 return new NBLog::Writer();
786 }
787success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700788 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -0800789 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
790 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700791 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -0800792 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800793}
794
795void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
796{
Glenn Kasten685ef092013-02-04 08:15:34 -0800797 if (writer == 0) {
798 return;
799 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800800 sp<IMemory> iMemory(writer->getIMemory());
801 if (iMemory == 0) {
802 return;
803 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700804 // Rather than removing the writer immediately, append it to a queue of old writers to
805 // be garbage-collected later. This allows us to continue to view old logs for a while.
806 Mutex::Autolock _l(mUnregisteredWritersLock);
807 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800808}
809
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810// IAudioFlinger interface
811
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -0800812status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
813 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800815 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -0800816 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -0800817 CreateTrackOutput output;
818
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 sp<PlaybackThread::Track> track;
820 sp<TrackHandle> trackHandle;
821 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -0800823 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -0800824 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800825 std::vector<audio_io_handle_t> secondaryOutputs;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700827 // TODO b/182392553: refactor or make clearer
828 pid_t clientPid =
829 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.identity.pid));
830 bool updatePid = (clientPid == (pid_t)-1);
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700831 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700832 uid_t clientUid =
833 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.identity.uid));
Eric Laurent6c796322019-04-09 14:13:17 -0700834 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
835 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -0700836 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -0700837
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700838 Identity adjIdentity = input.clientInfo.identity;
Andy Hung4ef19fa2018-05-15 19:35:29 -0700839 if (!isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurent21da6472017-11-09 16:29:26 -0800840 ALOGW_IF(clientUid != callingUid,
841 "%s uid %d tried to pass itself off as %d",
842 __FUNCTION__, callingUid, clientUid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700843 adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Eric Laurent21da6472017-11-09 16:29:26 -0800844 clientUid = callingUid;
845 updatePid = true;
846 }
Eric Laurent09f1ed22019-04-24 17:45:17 -0700847 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Eric Laurent21da6472017-11-09 16:29:26 -0800848 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700849 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700850 "%s uid %d pid %d tried to pass itself off as pid %d",
Eric Laurent21da6472017-11-09 16:29:26 -0800851 __func__, callingUid, callingPid, clientPid);
852 clientPid = callingPid;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700853 adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -0700854 }
855
Eric Laurent21da6472017-11-09 16:29:26 -0800856 audio_session_t sessionId = input.sessionId;
857 if (sessionId == AUDIO_SESSION_ALLOCATE) {
858 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -0800859 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
860 lStatus = BAD_VALUE;
861 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -0800862 }
Eric Laurentf14db3c2017-12-08 14:20:36 -0800863
Eric Laurent21da6472017-11-09 16:29:26 -0800864 output.sessionId = sessionId;
865 output.outputId = AUDIO_IO_HANDLE_NONE;
866 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -0700867 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700868 adjIdentity, &input.config, input.flags,
Ricardo Correa57a37692020-03-23 17:27:25 -0700869 &output.selectedDeviceId, &portId, &secondaryOutputs);
Eric Laurent21da6472017-11-09 16:29:26 -0800870
871 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
872 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
873 goto Exit;
874 }
Glenn Kasten263709e2012-01-06 08:40:01 -0800875 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
876 // but if someone uses binder directly they could bypass that and cause us to crash
877 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000878 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879 lStatus = BAD_VALUE;
880 goto Exit;
881 }
882
Glenn Kasten53b5d092014-02-05 10:00:23 -0800883 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800884 if (!audio_is_output_channel(input.config.channel_mask)) {
885 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -0800886 lStatus = BAD_VALUE;
887 goto Exit;
888 }
889
Glenn Kastenc4b88a82014-04-30 16:54:30 -0700890 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -0800891 if (!audio_is_valid_format(input.config.format)) {
892 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -0700893 lStatus = BAD_VALUE;
894 goto Exit;
895 }
896
Mathias Agopian65ab4712010-07-14 17:59:35 -0700897 {
898 Mutex::Autolock _l(mLock);
Eric Laurent21da6472017-11-09 16:29:26 -0800899 PlaybackThread *thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -0800901 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 lStatus = BAD_VALUE;
903 goto Exit;
904 }
905
Eric Laurent21da6472017-11-09 16:29:26 -0800906 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700907
Glenn Kastene848bd92014-03-13 15:00:32 -0700908 PlaybackThread *effectThread = NULL;
Eric Laurent21da6472017-11-09 16:29:26 -0800909 // check if an effect chain with the same session ID is present on another
910 // output thread and move it here.
911 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
912 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
913 if (mPlaybackThreads.keyAt(i) != output.outputId) {
914 uint32_t sessions = t->hasAudioSession(sessionId);
915 if (sessions & ThreadBase::EFFECT_SESSION) {
916 effectThread = t.get();
917 break;
Eric Laurentde070132010-07-13 04:45:46 -0700918 }
919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
Eric Laurent21da6472017-11-09 16:29:26 -0800921 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922
Eric Laurent21da6472017-11-09 16:29:26 -0800923 output.sampleRate = input.config.sample_rate;
924 output.frameCount = input.frameCount;
925 output.notificationFrameCount = input.notificationFrameCount;
926 output.flags = input.flags;
927
Eric Laurent42984412019-05-09 17:57:03 -0700928 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -0700929 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -0800930 &output.frameCount, &output.notificationFrameCount,
931 input.notificationsPerBuffer, input.speed,
932 input.sharedBuffer, sessionId, &output.flags,
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700933 callingPid, adjIdentity, input.clientInfo.clientTid,
934 &lStatus, portId, input.audioTrackCallback);
Haynes Mathew George03e9e832013-12-13 15:40:13 -0800935 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -0700936 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -0700937
Eric Laurent21da6472017-11-09 16:29:26 -0800938 output.afFrameCount = thread->frameCount();
939 output.afSampleRate = thread->sampleRate();
940 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -0800941 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -0800942
Kevin Rocard153f92d2018-12-18 18:33:28 -0800943 if (lStatus == NO_ERROR) {
944 // Connect secondary outputs. Failure on a secondary output must not imped the primary
945 // Any secondary output setup failure will lead to a desync between the AP and AF until
946 // the track is destroyed.
947 TeePatches teePatches;
948 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
949 PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput);
950 if (secondaryThread == NULL) {
951 ALOGE("no playback thread found for secondary output %d", output.outputId);
952 continue;
953 }
954
Kevin Rocard01c7d9e2019-09-18 11:24:52 +0100955 size_t sourceFrameCount = thread->frameCount() * output.sampleRate
956 / thread->sampleRate();
957 size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate
958 / secondaryThread->sampleRate();
959 // If the secondary output has just been opened, the first secondaryThread write
960 // will not block as it will fill the empty startup buffer of the HAL,
961 // so a second sink buffer needs to be ready for the immediate next blocking write.
962 // Additionally, have a margin of one main thread buffer as the scheduling jitter
963 // can reorder the writes (eg if thread A&B have the same write intervale,
964 // the scheduler could schedule AB...BA)
965 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
966 // Total secondary output buffer must be at least as the read frames plus
967 // the margin of a few buffers on both sides in case the
968 // threads scheduling has some jitter.
969 // That value should not impact latency as the secondary track is started before
970 // its buffer is full, see frameCountToBeReady.
971 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
972 // The frameCount should also not be smaller than the secondary thread min frame
973 // count
974 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
975 [&] { Mutex::Autolock _l(secondaryThread->mLock);
976 return secondaryThread->latency_l(); }(),
977 secondaryThread->mNormalFrameCount,
978 secondaryThread->mSampleRate,
979 output.sampleRate,
980 input.speed);
981 frameCount = std::max(frameCount, minFrameCount);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800982
983 using namespace std::chrono_literals;
984 auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask);
985 sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */,
986 output.sampleRate,
987 inChannelMask,
988 input.config.format,
989 frameCount,
990 NULL /* buffer */,
991 (size_t)0 /* bufferSize */,
992 AUDIO_INPUT_FLAG_DIRECT,
993 0ns /* timeout */);
994 status_t status = patchRecord->initCheck();
995 if (status != NO_ERROR) {
996 ALOGE("Secondary output patchRecord init failed: %d", status);
997 continue;
998 }
Andy Hungae22b482019-05-09 15:38:55 -0700999
1000 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
1001 // for fast usage: thread has fast mixer, sample rate matches, etc.;
1002 // for now, we exclude fast tracks by removing the Fast flag.
1003 const audio_output_flags_t outputFlags =
1004 (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001005 sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread,
1006 streamType,
1007 output.sampleRate,
1008 input.config.channel_mask,
1009 input.config.format,
1010 frameCount,
1011 patchRecord->buffer(),
1012 patchRecord->bufferSize(),
Andy Hungae22b482019-05-09 15:38:55 -07001013 outputFlags,
Kevin Rocard01c7d9e2019-09-18 11:24:52 +01001014 0ns /* timeout */,
1015 frameCountToBeReady);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001016 status = patchTrack->initCheck();
1017 if (status != NO_ERROR) {
1018 ALOGE("Secondary output patchTrack init failed: %d", status);
1019 continue;
1020 }
1021 teePatches.push_back({patchRecord, patchTrack});
1022 secondaryThread->addPatchTrack(patchTrack);
Andy Hungabfab202019-03-07 19:45:54 -08001023 // In case the downstream patchTrack on the secondaryThread temporarily outlives
1024 // our created track, ensure the corresponding patchRecord is still alive.
1025 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
1026 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001027 }
1028 track->setTeePatches(std::move(teePatches));
1029 }
1030
Eric Laurent39e94f82010-07-28 01:32:47 -07001031 // move effect chain to this output thread if an effect on same session was waiting
1032 // for a track to be created
1033 if (lStatus == NO_ERROR && effectThread != NULL) {
Glenn Kasten2fc14732013-08-05 14:58:14 -07001034 // no risk of deadlock because AudioFlinger::mLock is held
Eric Laurent39e94f82010-07-28 01:32:47 -07001035 Mutex::Autolock _dl(thread->mLock);
1036 Mutex::Autolock _sl(effectThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07001037 if (moveEffectChain_l(sessionId, effectThread, thread) == NO_ERROR) {
1038 effectThreadId = thread->id();
1039 effectIds = thread->getEffectIds_l(sessionId);
1040 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001041 }
Eric Laurenta011e352012-03-29 15:51:43 -07001042
1043 // Look for sync events awaiting for a session to be used.
Mark Salyzyn3ab368e2014-04-15 14:55:53 -07001044 for (size_t i = 0; i < mPendingSyncEvents.size(); i++) {
Eric Laurent21da6472017-11-09 16:29:26 -08001045 if (mPendingSyncEvents[i]->triggerSession() == sessionId) {
Eric Laurenta011e352012-03-29 15:51:43 -07001046 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -07001047 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07001048 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -07001049 } else {
1050 mPendingSyncEvents[i]->cancel();
1051 }
Eric Laurenta011e352012-03-29 15:51:43 -07001052 mPendingSyncEvents.removeAt(i);
1053 i--;
1054 }
1055 }
1056 }
Glenn Kastene198c362013-08-13 09:13:36 -07001057
Eric Laurent21da6472017-11-09 16:29:26 -08001058 setAudioHwSyncForSession_l(thread, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001059 }
Glenn Kastene198c362013-08-13 09:13:36 -07001060
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001061 if (lStatus != NO_ERROR) {
1062 // remove local strong reference to Client before deleting the Track so that the
Eric Laurent021cf962014-05-13 10:18:14 -07001063 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001064 // Don't hold mClientLock when releasing the reference on the track as the
1065 // destructor will acquire it.
1066 {
1067 Mutex::Autolock _cl(mClientLock);
1068 client.clear();
1069 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001071 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 }
1073
Eric Laurent6c796322019-04-09 14:13:17 -07001074 // effectThreadId is not NONE if an effect chain corresponding to the track session
1075 // was found on another thread and must be moved on this thread
1076 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1077 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1078 }
1079
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001080 output.audioTrack = new TrackHandle(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001081 _output = VALUE_OR_FATAL(output.toAidl());
1082
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001084 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001085 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001086 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001087 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088}
1089
Glenn Kasten2c073da2016-02-26 09:14:08 -08001090uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001093 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001095 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 return 0;
1097 }
1098 return thread->sampleRate();
1099}
1100
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001101audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102{
1103 Mutex::Autolock _l(mLock);
1104 PlaybackThread *thread = checkPlaybackThread_l(output);
1105 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001106 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001107 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 }
1109 return thread->format();
1110}
1111
Glenn Kasten2c073da2016-02-26 09:14:08 -08001112size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001113{
1114 Mutex::Autolock _l(mLock);
Glenn Kasten2c073da2016-02-26 09:14:08 -08001115 ThreadBase *thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001117 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118 return 0;
1119 }
Glenn Kasten58912562012-04-03 10:45:00 -07001120 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1121 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 return thread->frameCount();
1123}
1124
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001125size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1126{
1127 Mutex::Autolock _l(mLock);
1128 ThreadBase *thread = checkThread_l(ioHandle);
1129 if (thread == NULL) {
1130 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1131 return 0;
1132 }
1133 return thread->frameCountHAL();
1134}
1135
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001136uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137{
1138 Mutex::Autolock _l(mLock);
1139 PlaybackThread *thread = checkPlaybackThread_l(output);
1140 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001141 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 return 0;
1143 }
1144 return thread->latency();
1145}
1146
1147status_t AudioFlinger::setMasterVolume(float value)
1148{
Eric Laurenta1884f92011-08-23 08:25:03 -07001149 status_t ret = initCheck();
1150 if (ret != NO_ERROR) {
1151 return ret;
1152 }
1153
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 // check calling permissions
1155 if (!settingsAllowed()) {
1156 return PERMISSION_DENIED;
1157 }
1158
Eric Laurenta4c5a552012-03-29 10:12:40 -07001159 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001160 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001161
John Grossmanee578c02012-07-23 17:05:46 -07001162 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001163 {
John Grossmanee578c02012-07-23 17:05:46 -07001164 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001165 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1166 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001167
Eric Laurent00abf0d2020-04-22 19:28:22 -07001168 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1169 if (dev->canSetMasterVolume()) {
1170 dev->hwDevice()->setMasterVolume(value);
1171 }
1172 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 }
John Grossmanee578c02012-07-23 17:05:46 -07001175 // Now set the master volume in each playback thread. Playback threads
1176 // assigned to HALs which do not have master volume support will apply
1177 // master volume during the mix operation. Threads with HALs which do
1178 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001179 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1180 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1181 continue;
1182 }
John Grossmanee578c02012-07-23 17:05:46 -07001183 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185
1186 return NO_ERROR;
1187}
1188
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001189status_t AudioFlinger::setMasterBalance(float balance)
1190{
1191 status_t ret = initCheck();
1192 if (ret != NO_ERROR) {
1193 return ret;
1194 }
1195
1196 // check calling permissions
1197 if (!settingsAllowed()) {
1198 return PERMISSION_DENIED;
1199 }
1200
1201 // check range
1202 if (isnan(balance) || fabs(balance) > 1.f) {
1203 return BAD_VALUE;
1204 }
1205
1206 Mutex::Autolock _l(mLock);
1207
1208 // short cut.
1209 if (mMasterBalance == balance) return NO_ERROR;
1210
1211 mMasterBalance = balance;
1212
1213 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1214 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1215 continue;
1216 }
1217 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1218 }
1219
1220 return NO_ERROR;
1221}
1222
Glenn Kastenf78aee72012-01-04 11:00:47 -08001223status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001224{
Eric Laurenta1884f92011-08-23 08:25:03 -07001225 status_t ret = initCheck();
1226 if (ret != NO_ERROR) {
1227 return ret;
1228 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229
1230 // check calling permissions
1231 if (!settingsAllowed()) {
1232 return PERMISSION_DENIED;
1233 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001234 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001235 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 return BAD_VALUE;
1237 }
1238
1239 { // scope for the lock
1240 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001241 if (mPrimaryHardwareDev == nullptr) {
1242 return INVALID_OPERATION;
1243 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001244 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001246 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 mHardwareStatus = AUDIO_HW_IDLE;
1248 }
1249
1250 if (NO_ERROR == ret) {
1251 Mutex::Autolock _l(mLock);
1252 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001253 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001254 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001255 }
1256
Joey Poomarin52989982020-03-05 17:40:49 +08001257 mediametrics::LogItem(mMetricsId)
1258 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1259 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1260 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001261 return ret;
1262}
1263
1264status_t AudioFlinger::setMicMute(bool state)
1265{
Eric Laurenta1884f92011-08-23 08:25:03 -07001266 status_t ret = initCheck();
1267 if (ret != NO_ERROR) {
1268 return ret;
1269 }
1270
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 // check calling permissions
1272 if (!settingsAllowed()) {
1273 return PERMISSION_DENIED;
1274 }
1275
1276 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001277 if (mPrimaryHardwareDev == nullptr) {
1278 return INVALID_OPERATION;
1279 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001280 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1281 if (primaryDev == nullptr) {
1282 ALOGW("%s: no primary HAL device", __func__);
1283 return INVALID_OPERATION;
1284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001286 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001287 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001288 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001289 if (dev != primaryDev) {
1290 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001291 }
1292 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001294 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 return ret;
1296}
1297
1298bool AudioFlinger::getMicMute() const
1299{
Eric Laurenta1884f92011-08-23 08:25:03 -07001300 status_t ret = initCheck();
1301 if (ret != NO_ERROR) {
1302 return false;
1303 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001304 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001305 if (mPrimaryHardwareDev == nullptr) {
1306 return false;
1307 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001308 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev->hwDevice();
1309 if (primaryDev == nullptr) {
1310 ALOGW("%s: no primary HAL device", __func__);
1311 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001312 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001313 bool state;
1314 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1315 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001317 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1318 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319}
1320
Eric Laurent5ada82e2019-08-29 17:53:54 -07001321void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001322{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001323 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001324
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001325 AutoMutex lock(mLock);
1326 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001327 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001328 }
1329 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001330 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001331 }
1332}
1333
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334status_t AudioFlinger::setMasterMute(bool muted)
1335{
John Grossmand8f178d2012-07-20 14:51:35 -07001336 status_t ret = initCheck();
1337 if (ret != NO_ERROR) {
1338 return ret;
1339 }
1340
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341 // check calling permissions
1342 if (!settingsAllowed()) {
1343 return PERMISSION_DENIED;
1344 }
1345
John Grossmanee578c02012-07-23 17:05:46 -07001346 Mutex::Autolock _l(mLock);
1347 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001348
John Grossmanee578c02012-07-23 17:05:46 -07001349 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001350 {
John Grossmanee578c02012-07-23 17:05:46 -07001351 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001352 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1353 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001354
Eric Laurent00abf0d2020-04-22 19:28:22 -07001355 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1356 if (dev->canSetMasterMute()) {
1357 dev->hwDevice()->setMasterMute(muted);
1358 }
1359 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001360 }
John Grossmand8f178d2012-07-20 14:51:35 -07001361 }
1362
John Grossmanee578c02012-07-23 17:05:46 -07001363 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001364 // assigned to HALs which do not have master mute support will apply master mute
1365 // during the mix operation. Threads with HALs which do support master mute
1366 // will simply ignore the setting.
Eric Laurent6acd1d42017-01-04 14:23:29 -08001367 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1368 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1369 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371
1372 return NO_ERROR;
1373}
1374
1375float AudioFlinger::masterVolume() const
1376{
Glenn Kasten98067102011-12-13 11:47:54 -08001377 Mutex::Autolock _l(mLock);
1378 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379}
1380
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001381status_t AudioFlinger::getMasterBalance(float *balance) const
1382{
1383 Mutex::Autolock _l(mLock);
1384 *balance = getMasterBalance_l();
1385 return NO_ERROR; // if called through binder, may return a transactional error
1386}
1387
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388bool AudioFlinger::masterMute() const
1389{
Glenn Kasten98067102011-12-13 11:47:54 -08001390 Mutex::Autolock _l(mLock);
1391 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392}
1393
John Grossman4ff14ba2012-02-08 16:37:41 -08001394float AudioFlinger::masterVolume_l() const
1395{
John Grossman4ff14ba2012-02-08 16:37:41 -08001396 return mMasterVolume;
1397}
1398
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001399float AudioFlinger::getMasterBalance_l() const
1400{
1401 return mMasterBalance;
1402}
1403
John Grossmand8f178d2012-07-20 14:51:35 -07001404bool AudioFlinger::masterMute_l() const
1405{
John Grossmanee578c02012-07-23 17:05:46 -07001406 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001407}
1408
Eric Laurent223fd5c2014-11-11 13:43:36 -08001409status_t AudioFlinger::checkStreamType(audio_stream_type_t stream) const
1410{
1411 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001412 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001413 return BAD_VALUE;
1414 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001415 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1416 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1417 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001418 return PERMISSION_DENIED;
1419 }
1420
1421 return NO_ERROR;
1422}
1423
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001424status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1425 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426{
1427 // check calling permissions
1428 if (!settingsAllowed()) {
1429 return PERMISSION_DENIED;
1430 }
1431
Eric Laurent223fd5c2014-11-11 13:43:36 -08001432 status_t status = checkStreamType(stream);
1433 if (status != NO_ERROR) {
1434 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001435 }
Eric Laurent98e38192018-02-15 18:31:53 -08001436 if (output == AUDIO_IO_HANDLE_NONE) {
1437 return BAD_VALUE;
1438 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001439 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1440 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441
1442 AutoMutex lock(mLock);
Eric Laurent98e38192018-02-15 18:31:53 -08001443 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1444 if (volumeInterface == NULL) {
1445 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446 }
Eric Laurent98e38192018-02-15 18:31:53 -08001447 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448
1449 return NO_ERROR;
1450}
1451
Glenn Kastenfff6d712012-01-12 16:38:12 -08001452status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453{
1454 // check calling permissions
1455 if (!settingsAllowed()) {
1456 return PERMISSION_DENIED;
1457 }
1458
Eric Laurent223fd5c2014-11-11 13:43:36 -08001459 status_t status = checkStreamType(stream);
1460 if (status != NO_ERROR) {
1461 return status;
1462 }
1463 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1464
1465 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001466 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 return BAD_VALUE;
1468 }
1469
Eric Laurent93575202011-01-18 18:39:02 -08001470 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -08001472 Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
1473 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1474 volumeInterfaces[i]->setStreamMute(stream, muted);
1475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476
1477 return NO_ERROR;
1478}
1479
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001480float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001482 status_t status = checkStreamType(stream);
1483 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 return 0.0f;
1485 }
Eric Laurent98e38192018-02-15 18:31:53 -08001486 if (output == AUDIO_IO_HANDLE_NONE) {
1487 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 }
1489
Eric Laurent98e38192018-02-15 18:31:53 -08001490 AutoMutex lock(mLock);
1491 VolumeInterface *volumeInterface = getVolumeInterface_l(output);
1492 if (volumeInterface == NULL) {
1493 return 0.0f;
1494 }
1495
1496 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497}
1498
Glenn Kastenfff6d712012-01-12 16:38:12 -08001499bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001501 status_t status = checkStreamType(stream);
1502 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 return true;
1504 }
1505
Glenn Kasten6637baa2012-01-09 09:40:36 -08001506 AutoMutex lock(mLock);
1507 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508}
1509
Eric Laurent054d9d32015-04-24 08:48:48 -07001510
Andy Hungd9ef4b12020-11-11 15:13:18 -08001511void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001512{
1513 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1514 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1515 }
1516}
1517
jiabinc52b1ff2019-10-31 17:20:42 -07001518void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1519{
1520 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1521 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1522 }
1523}
1524
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001525// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mLock held
1526void AudioFlinger::forwardParametersToDownstreamPatches_l(
1527 audio_io_handle_t upStream, const String8& keyValuePairs,
1528 std::function<bool(const sp<PlaybackThread>&)> useThread)
1529{
1530 std::vector<PatchPanel::SoftwarePatch> swPatches;
1531 if (mPatchPanel.getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1532 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1533 __func__, swPatches.size(), upStream);
1534 for (const auto& swPatch : swPatches) {
1535 sp<PlaybackThread> downStream = checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1536 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1537 downStream->setParameters(keyValuePairs);
1538 }
1539 }
1540}
1541
Eric Laurent74c38dc2020-12-23 18:19:44 +01001542// Update downstream patches for all playback threads attached to an MSD module
1543void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
1544 const std::set<audio_io_handle_t> streams)
1545{
1546 for (const audio_io_handle_t stream : streams) {
1547 PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
1548 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1549 continue;
1550 }
1551 playbackThread->setDownStreamPatch(patch);
1552 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1553 }
1554}
1555
Eric Laurentf1047e82018-04-16 19:18:20 -07001556// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1557// Some keys are used for audio routing and audio path configuration and should be reserved for use
1558// by audio policy and audio flinger for functional, privacy and security reasons.
1559void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1560{
1561 static const String8 kReservedParameters[] = {
1562 String8(AudioParameter::keyRouting),
1563 String8(AudioParameter::keySamplingRate),
1564 String8(AudioParameter::keyFormat),
1565 String8(AudioParameter::keyChannels),
1566 String8(AudioParameter::keyFrameCount),
1567 String8(AudioParameter::keyInputSource),
1568 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001569 String8(AudioParameter::keyDeviceConnect),
1570 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001571 String8(AudioParameter::keyStreamSupportedFormats),
1572 String8(AudioParameter::keyStreamSupportedChannels),
1573 String8(AudioParameter::keyStreamSupportedSamplingRates),
1574 };
1575
Andy Hung4ef19fa2018-05-15 19:35:29 -07001576 if (isAudioServerUid(callingUid)) {
1577 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001578 }
1579
1580 AudioParameter param = AudioParameter(keyValuePairs);
1581 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001582 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001583 for (auto& key : kReservedParameters) {
1584 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001585 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001586 param.remove(key);
1587 }
1588 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001589 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1590 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001591 keyValuePairs = param.toString();
1592}
1593
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001594void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1595 size_t rejectedKVPSize, const String8& rejectedKVPs,
1596 uid_t callingUid) {
1597 auto prefix = String8::format("UID %5d", callingUid);
1598 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1599 if (rejectedKVPSize != 0) {
1600 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1601 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1602 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1603 } else {
1604 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1605 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1606 }
1607}
1608
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001609status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610{
Eric Laurentf1047e82018-04-16 19:18:20 -07001611 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1612 ioHandle, keyValuePairs.string(),
1613 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001614
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 // check calling permissions
1616 if (!settingsAllowed()) {
1617 return PERMISSION_DENIED;
1618 }
1619
Eric Laurentf1047e82018-04-16 19:18:20 -07001620 String8 filteredKeyValuePairs = keyValuePairs;
1621 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1622
1623 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.string());
1624
Glenn Kasten142f5192014-03-25 17:44:59 -07001625 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1626 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001627 Mutex::Autolock _l(mLock);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001628 // result will remain NO_INIT if no audio device is present
1629 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001630 {
Eric Laurenta4c5a552012-03-29 10:12:40 -07001631 AutoMutex lock(mHardwareLock);
1632 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1633 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001634 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001635 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001636 // return success if at least one audio device accepts the parameters as not all
1637 // HALs are requested to support all parameters. If no audio device supports the
1638 // requested parameters, the last error is reported.
1639 if (final_result != NO_ERROR) {
1640 final_result = result;
1641 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001642 }
1643 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001644 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001645 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001646 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001647 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001648 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1649 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001650 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001651 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001652 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001653 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001654 }
1655 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001656 String8 screenState;
1657 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001658 bool isOff = (screenState == AudioParameter::valueOff);
Eric Laurent81784c32012-11-19 14:55:58 -08001659 if (isOff != (AudioFlinger::mScreenState & 1)) {
1660 AudioFlinger::mScreenState = ((AudioFlinger::mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001661 }
1662 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001663 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
1665
1666 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1667 // and the thread is exited once the lock is released
1668 sp<ThreadBase> thread;
1669 {
1670 Mutex::Autolock _l(mLock);
1671 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001672 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001674 if (thread == 0) {
1675 thread = checkMmapThread_l(ioHandle);
1676 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001677 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001678 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001679 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001680 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001681 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1682 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001683 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001684 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 }
1686 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001687 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001688 status_t result = thread->setParameters(filteredKeyValuePairs);
1689 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1690 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691 }
1692 return BAD_VALUE;
1693}
1694
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001695String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001697 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
1698 ioHandle, keys.string(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699
Eric Laurenta4c5a552012-03-29 10:12:40 -07001700 Mutex::Autolock _l(mLock);
1701
Glenn Kasten142f5192014-03-25 17:44:59 -07001702 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001703 String8 out_s8;
1704
Eric Laurent00abf0d2020-04-22 19:28:22 -07001705 AutoMutex lock(mHardwareLock);
Dima Zavin799a70e2011-04-18 16:57:27 -07001706 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001707 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001708 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001709 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001710 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001711 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001712 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001713 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001714 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 }
1716
Eric Laurent6acd1d42017-01-04 14:23:29 -08001717 ThreadBase *thread = (ThreadBase *)checkPlaybackThread_l(ioHandle);
1718 if (thread == NULL) {
1719 thread = (ThreadBase *)checkRecordThread_l(ioHandle);
1720 if (thread == NULL) {
1721 thread = (ThreadBase *)checkMmapThread_l(ioHandle);
1722 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001723 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001724 }
1725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001727 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728}
1729
Glenn Kastendd8104c2012-07-02 12:42:44 -07001730size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1731 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732{
Eric Laurenta1884f92011-08-23 08:25:03 -07001733 status_t ret = initCheck();
1734 if (ret != NO_ERROR) {
1735 return 0;
1736 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001737 if ((sampleRate == 0) ||
Phil Burkfdb3c072016-02-09 10:47:02 -08001738 !audio_is_valid_format(format) || !audio_has_proportional_frames(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001739 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07001740 return 0;
1741 }
Eric Laurenta1884f92011-08-23 08:25:03 -07001742
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001743 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001744 if (mPrimaryHardwareDev == nullptr) {
1745 return 0;
1746 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001747 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00001748
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001749 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Judy Hsiaoabab5222019-11-09 18:14:58 +08001750 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
1751 if (channelMask != AUDIO_CHANNEL_IN_MONO)
1752 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
1753 if (channelMask != AUDIO_CHANNEL_IN_STEREO)
1754 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
1755
1756 std::vector<audio_format_t> formats = {format};
1757 if (format != AUDIO_FORMAT_PCM_16_BIT)
1758 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
1759
1760 std::vector<uint32_t> sampleRates = {sampleRate};
1761 static const uint32_t SR_44100 = 44100;
1762 static const uint32_t SR_48000 = 48000;
1763
1764 if (sampleRate != SR_48000)
1765 sampleRates.push_back(SR_48000);
1766 if (sampleRate != SR_44100)
1767 sampleRates.push_back(SR_44100);
1768
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001769 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001770
Robin Lee9899ff72019-12-24 22:02:08 +01001771 // Change parameters of the configuration each iteration until we find a
1772 // configuration that the device will support.
1773 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08001774 for (auto testChannelMask : channelMasks) {
1775 config.channel_mask = testChannelMask;
1776 for (auto testFormat : formats) {
1777 config.format = testFormat;
1778 for (auto testSampleRate : sampleRates) {
1779 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01001780
Judy Hsiaoabab5222019-11-09 18:14:58 +08001781 size_t bytes = 0;
1782 status_t result = dev->getInputBufferSize(&config, &bytes);
1783 if (result != OK || bytes == 0) {
1784 continue;
1785 }
1786
1787 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
1788 config.format != format) {
1789 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
1790 uint32_t srcChannelCount =
1791 audio_channel_count_from_in_mask(config.channel_mask);
1792 size_t srcFrames =
1793 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
1794 size_t dstFrames = destinationFramesPossible(
1795 srcFrames, config.sample_rate, sampleRate);
1796 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
1797 }
1798 return bytes;
1799 }
1800 }
Andy Hung6770c6f2015-04-07 13:43:36 -07001801 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08001802
1803 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
1804 "format %#x, channelMask %#x",sampleRate, format, channelMask);
1805 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806}
1807
Glenn Kasten5f972c02014-01-13 09:59:31 -08001808uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 Mutex::Autolock _l(mLock);
1811
1812 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1813 if (recordThread != NULL) {
1814 return recordThread->getInputFramesLost();
1815 }
1816 return 0;
1817}
1818
1819status_t AudioFlinger::setVoiceVolume(float value)
1820{
Eric Laurenta1884f92011-08-23 08:25:03 -07001821 status_t ret = initCheck();
1822 if (ret != NO_ERROR) {
1823 return ret;
1824 }
1825
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 // check calling permissions
1827 if (!settingsAllowed()) {
1828 return PERMISSION_DENIED;
1829 }
1830
1831 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07001832 if (mPrimaryHardwareDev == nullptr) {
1833 return INVALID_OPERATION;
1834 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001835 sp<DeviceHalInterface> dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001836 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001837 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 mHardwareStatus = AUDIO_HW_IDLE;
1839
Joey Poomarin52989982020-03-05 17:40:49 +08001840 mediametrics::LogItem(mMetricsId)
1841 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
1842 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
1843 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 return ret;
1845}
1846
Kévin PETIT377b2ec2014-02-03 12:35:36 +00001847status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001848 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 Mutex::Autolock _l(mLock);
1851
1852 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1853 if (playbackThread != NULL) {
1854 return playbackThread->getRenderPosition(halFrames, dspFrames);
1855 }
1856
1857 return BAD_VALUE;
1858}
1859
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001860void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 Mutex::Autolock _l(mLock);
Eric Laurent44622db2014-08-01 19:00:33 -07001863 if (client == 0) {
1864 return;
1865 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001866 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08001867 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07001868 {
1869 Mutex::Autolock _cl(mClientLock);
Eric Laurent021cf962014-05-13 10:18:14 -07001870 if (mNotificationClients.indexOfKey(pid) < 0) {
1871 sp<NotificationClient> notificationClient = new NotificationClient(this,
1872 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08001873 pid,
1874 uid);
1875 ALOGV("registerClient() client %p, pid %d, uid %u",
1876 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877
Eric Laurent021cf962014-05-13 10:18:14 -07001878 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879
Marco Nelissen06b46062014-11-14 07:58:25 -08001880 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07001881 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07001882 }
1883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884
Eric Laurent021cf962014-05-13 10:18:14 -07001885 // mClientLock should not be held here because ThreadBase::sendIoConfigEvent() will lock the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001886 // ThreadBase mutex and the locking order is ThreadBase::mLock then AudioFlinger::mClientLock.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001887 // the config change is always sent from playback or record threads to avoid deadlock
1888 // with AudioSystem::gLock
1889 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001890 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001891 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001893 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001894 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895 }
1896}
1897
1898void AudioFlinger::removeNotificationClient(pid_t pid)
1899{
Eric Laurent6c796322019-04-09 14:13:17 -07001900 std::vector< sp<AudioFlinger::EffectModule> > removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07001901 {
Eric Laurent6c796322019-04-09 14:13:17 -07001902 Mutex::Autolock _l(mLock);
1903 {
1904 Mutex::Autolock _cl(mClientLock);
1905 mNotificationClients.removeItem(pid);
1906 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001907
Eric Laurent6c796322019-04-09 14:13:17 -07001908 ALOGV("%d died, releasing its sessions", pid);
1909 size_t num = mAudioSessionRefs.size();
1910 bool removed = false;
1911 for (size_t i = 0; i < num; ) {
1912 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1913 ALOGV(" pid %d @ %zu", ref->mPid, i);
1914 if (ref->mPid == pid) {
1915 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
1916 mAudioSessionRefs.removeAt(i);
1917 delete ref;
1918 removed = true;
1919 num--;
1920 } else {
1921 i++;
1922 }
1923 }
1924 if (removed) {
1925 removedEffects = purgeStaleEffects_l();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001926 }
1927 }
Eric Laurent6c796322019-04-09 14:13:17 -07001928 for (auto& effect : removedEffects) {
1929 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931}
1932
Eric Laurent73e26b62015-04-27 16:55:58 -07001933void AudioFlinger::ioConfigChanged(audio_io_config_event event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001934 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001935 pid_t pid) {
1936 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
1937 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
1938 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
1939 legacy2aidl_audio_io_config_event_AudioIoConfigEvent(event));
1940
Eric Laurent021cf962014-05-13 10:18:14 -07001941 Mutex::Autolock _l(mClientLock);
1942 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001944 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07001945 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
1946 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 }
1949}
1950
Eric Laurent021cf962014-05-13 10:18:14 -07001951// removeClient_l() must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952void AudioFlinger::removeClient_l(pid_t pid)
1953{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001954 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001955 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956 mClients.removeItem(pid);
1957}
1958
Eric Laurent717e1282012-06-29 16:36:52 -07001959// getEffectThread_l() must be called with AudioFlinger::mLock held
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001960sp<AudioFlinger::ThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
1961 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07001962{
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001963 sp<ThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07001964
1965 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001966 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
Eric Laurent717e1282012-06-29 16:36:52 -07001967 ALOG_ASSERT(thread == 0);
1968 thread = mPlaybackThreads.valueAt(i);
1969 }
1970 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07001971 if (thread != nullptr) {
1972 return thread;
1973 }
1974 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1975 if (mRecordThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1976 ALOG_ASSERT(thread == 0);
1977 thread = mRecordThreads.valueAt(i);
1978 }
1979 }
1980 if (thread != nullptr) {
1981 return thread;
1982 }
1983 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1984 if (mMmapThreads.valueAt(i)->getEffect(sessionId, effectId) != 0) {
1985 ALOG_ASSERT(thread == 0);
1986 thread = mMmapThreads.valueAt(i);
1987 }
1988 }
Eric Laurent717e1282012-06-29 16:36:52 -07001989 return thread;
1990}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993
1994// ----------------------------------------------------------------------------
1995
1996AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
1997 : RefBase(),
1998 mAudioFlinger(audioFlinger),
Glenn Kastend79072e2016-01-06 08:41:20 -08001999 mPid(pid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000{
Andy Hung6f248bb2018-01-23 14:04:37 -08002001 mMemoryDealer = new MemoryDealer(
2002 audioFlinger->getClientSharedHeapSize(),
2003 (std::string("AudioFlinger::Client(") + std::to_string(pid) + ")").c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004}
2005
Eric Laurent021cf962014-05-13 10:18:14 -07002006// Client destructor must be called with AudioFlinger::mClientLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007AudioFlinger::Client::~Client()
2008{
2009 mAudioFlinger->removeClient_l(mPid);
2010}
2011
Glenn Kasten435dbe62012-01-30 10:15:48 -08002012sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013{
2014 return mMemoryDealer;
2015}
2016
2017// ----------------------------------------------------------------------------
2018
2019AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002020 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002021 pid_t pid,
2022 uid_t uid)
2023 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024{
2025}
2026
2027AudioFlinger::NotificationClient::~NotificationClient()
2028{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029}
2030
Glenn Kasten0f11b512014-01-31 16:18:54 -08002031void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032{
2033 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08002034 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035}
2036
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002037// ----------------------------------------------------------------------------
2038AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2039 : mPendingRequests(false) {}
2040
2041
2042void AudioFlinger::MediaLogNotifier::requestMerge() {
2043 AutoMutex _l(mMutex);
2044 mPendingRequests = true;
2045 mCond.signal();
2046}
2047
2048bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002049 // Should already have been checked, but just in case
2050 if (sMediaLogService == 0) {
2051 return false;
2052 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002053 // Wait until there are pending requests
2054 {
2055 AutoMutex _l(mMutex);
2056 mPendingRequests = false; // to ignore past requests
2057 while (!mPendingRequests) {
2058 mCond.wait(mMutex);
2059 // TODO may also need an exitPending check
2060 }
2061 mPendingRequests = false;
2062 }
2063 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002064 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002065 usleep(kPostTriggerSleepPeriod);
2066 return true;
2067}
2068
2069void AudioFlinger::requestLogMerge() {
2070 mMediaLogNotifier->requestMerge();
2071}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072
2073// ----------------------------------------------------------------------------
2074
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002075status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2076 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002078 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002079 CreateRecordOutput output;
2080
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 sp<RecordThread::RecordTrack> recordTrack;
2082 sp<RecordHandle> recordHandle;
2083 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002085 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002086 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087
Eric Laurentf14db3c2017-12-08 14:20:36 -08002088 output.cblk.clear();
2089 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002090 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002091
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002092 // TODO b/182392553: refactor or clean up
2093 Identity adjIdentity = input.clientInfo.identity;
2094 bool updatePid = (adjIdentity.pid == -1);
Marco Nelissendcb346b2015-09-09 10:47:29 -07002095 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002096 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(adjIdentity.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -07002097 if (!isAudioServerOrMediaServerUid(callingUid)) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002098 ALOGW_IF(currentUid != callingUid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002099 "%s uid %d tried to pass itself off as %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002100 __FUNCTION__, callingUid, currentUid);
2101 adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002102 updatePid = true;
2103 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07002104 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002105 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjIdentity.pid));
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002106 if (updatePid) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002107 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002108 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002109 __func__, callingUid, callingPid, currentPid);
2110 adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
Marco Nelissendcb346b2015-09-09 10:47:29 -07002111 }
2112
Andy Hung6770c6f2015-04-07 13:43:36 -07002113 // we don't yet support anything other than linear PCM
Eric Laurentf14db3c2017-12-08 14:20:36 -08002114 if (!audio_is_valid_format(input.config.format) || !audio_is_linear_pcm(input.config.format)) {
2115 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002116 lStatus = BAD_VALUE;
2117 goto Exit;
2118 }
2119
Glenn Kasten53b5d092014-02-05 10:00:23 -08002120 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002121 if (!audio_is_input_channel(input.config.channel_mask)) {
2122 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002123 lStatus = BAD_VALUE;
2124 goto Exit;
2125 }
2126
Eric Laurentf14db3c2017-12-08 14:20:36 -08002127 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2128 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2129 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2130 lStatus = BAD_VALUE;
2131 goto Exit;
2132 }
2133
2134 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002135 output.selectedDeviceId = input.selectedDeviceId;
2136 output.flags = input.flags;
2137
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002138 client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjIdentity.pid)));
Eric Laurentf14db3c2017-12-08 14:20:36 -08002139
2140 // Not a conventional loop, but a retry loop for at most two iterations total.
2141 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2142 // Exits loop via break on no error of got exit on error
2143 // The sp<> references will be dropped when re-entering scope.
2144 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2145 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002146 // release previously opened input if retrying.
2147 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2148 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002149 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002150 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002151 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002152 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002153 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002154 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002155 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002156 sessionId,
2157 // FIXME compare to AudioTrack
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002158 adjIdentity,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002159 &input.config,
2160 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002161 if (lStatus != NO_ERROR) {
2162 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2163 goto Exit;
2164 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002165
Glenn Kasten05997e22014-03-13 15:08:33 -07002166 {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 Mutex::Autolock _l(mLock);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002168 RecordThread *thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002170 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2171 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 goto Exit;
2173 }
2174
Eric Laurentf14db3c2017-12-08 14:20:36 -08002175 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176
Eric Laurentf14db3c2017-12-08 14:20:36 -08002177 output.sampleRate = input.config.sample_rate;
2178 output.frameCount = input.frameCount;
2179 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002180
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002181 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002182 input.config.format, input.config.channel_mask,
2183 &output.frameCount, sessionId,
2184 &output.notificationFrameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002185 callingPid, adjIdentity, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002186 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002187 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002188 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002189
Eric Laurentf14db3c2017-12-08 14:20:36 -08002190 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2191 // audio policy manager without FAST constraint
2192 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002193 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002194 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002195
2196 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002197 goto Exit;
2198 }
2199
2200 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2201 // session and move it to this thread.
2202 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
2203 if (chain != 0) {
2204 Mutex::Autolock _l(thread->mLock);
2205 thread->addEffectChain_l(chain);
2206 }
2207 break;
2208 }
2209 // End of retry loop.
2210 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 }
Glenn Kastene198c362013-08-13 09:13:36 -07002212
Eric Laurentf14db3c2017-12-08 14:20:36 -08002213 output.cblk = recordTrack->getCblk();
2214 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002215 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002216
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002217 output.audioRecord = new RecordHandle(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002218 _output = VALUE_OR_FATAL(output.toAidl());
2219
Eric Laurentf14db3c2017-12-08 14:20:36 -08002220Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002221 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002222 // remove local strong reference to Client before deleting the RecordTrack so that the
Eric Laurent021cf962014-05-13 10:18:14 -07002223 // Client destructor is called by the TrackBase destructor with mClientLock held
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002224 // Don't hold mClientLock when releasing the reference on the track as the
2225 // destructor will acquire it.
2226 {
2227 Mutex::Autolock _cl(mClientLock);
2228 client.clear();
2229 }
Eric Laurent896c9672017-12-08 14:08:45 -08002230 recordTrack.clear();
2231 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002232 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 }
2235
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002236 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237}
2238
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002239
2240
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241// ----------------------------------------------------------------------------
2242
Eric Laurenta4c5a552012-03-29 10:12:40 -07002243audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2244{
Eric Laurent44622db2014-08-01 19:00:33 -07002245 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002246 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002247 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002248 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002249 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002250 }
2251 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002252 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002253 return loadHwModule_l(name);
2254}
2255
Eric Laurent00abf0d2020-04-22 19:28:22 -07002256// loadHwModule_l() must be called with AudioFlinger::mLock and AudioFlinger::mHardwareLock held
Eric Laurenta4c5a552012-03-29 10:12:40 -07002257audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
2258{
2259 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2260 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2261 ALOGW("loadHwModule() module %s already loaded", name);
2262 return mAudioHwDevs.keyAt(i);
2263 }
2264 }
2265
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002266 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002267
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002268 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002269 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002270 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002271 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002272 }
2273
2274 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002275 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002276 mHardwareStatus = AUDIO_HW_IDLE;
2277 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002278 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Glenn Kastena13cde92016-03-28 15:26:02 -07002279 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002280 }
2281
John Grossmanee578c02012-07-23 17:05:46 -07002282 // Check and cache this HAL's level of support for master mute and master
2283 // volume. If this is the first HAL opened, and it supports the get
2284 // methods, use the initial values provided by the HAL as the current
2285 // master mute and volume settings.
2286
2287 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002288 if (0 == mAudioHwDevs.size()) {
2289 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2290 float mv;
2291 if (OK == dev->getMasterVolume(&mv)) {
2292 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002293 }
2294
Eric Laurent00abf0d2020-04-22 19:28:22 -07002295 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2296 bool mm;
2297 if (OK == dev->getMasterMute(&mm)) {
2298 mMasterMute = mm;
John Grossmanee578c02012-07-23 17:05:46 -07002299 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002300 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002301
2302 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2303 if (OK == dev->setMasterVolume(mMasterVolume)) {
2304 flags = static_cast<AudioHwDevice::Flags>(flags |
2305 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2306 }
2307
2308 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2309 if (OK == dev->setMasterMute(mMasterMute)) {
2310 flags = static_cast<AudioHwDevice::Flags>(flags |
2311 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2312 }
2313
2314 mHardwareStatus = AUDIO_HW_IDLE;
2315
Mikhail Naganov97373b02018-07-23 13:27:24 -07002316 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002317 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2318 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2319 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002320
Glenn Kastena13cde92016-03-28 15:26:02 -07002321 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002322 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2323 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2324 mPrimaryHardwareDev = audioDevice;
2325 mHardwareStatus = AUDIO_HW_SET_MODE;
2326 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2327 mHardwareStatus = AUDIO_HW_IDLE;
2328 }
2329
2330 mAudioHwDevs.add(handle, audioDevice);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002331
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002332 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002333
2334 return handle;
2335
2336}
2337
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002338// ----------------------------------------------------------------------------
2339
Glenn Kasten3b16c762012-11-14 08:44:39 -08002340uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002341{
2342 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002343 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002344 return thread != NULL ? thread->sampleRate() : 0;
2345}
2346
Glenn Kastene33054e2012-11-14 12:54:39 -08002347size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002348{
2349 Mutex::Autolock _l(mLock);
Glenn Kastena7335632016-06-09 17:09:53 -07002350 PlaybackThread *thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002351 return thread != NULL ? thread->frameCountHAL() : 0;
2352}
2353
2354// ----------------------------------------------------------------------------
2355
Andy Hung6f248bb2018-01-23 14:04:37 -08002356status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002357{
2358 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002359 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002360 return PERMISSION_DENIED;
2361 }
2362 Mutex::Autolock _l(mLock);
2363 if (mIsDeviceTypeKnown) {
2364 return INVALID_OPERATION;
2365 }
2366 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002367 mTotalMemory = totalMemory;
2368 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2369 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2370 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2371 // though actual setting is determined through device configuration.
2372 constexpr int64_t GB = 1024 * 1024 * 1024;
2373 mClientSharedHeapSize =
2374 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2375 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2376 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2377 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2378 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002379 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002380
2381 // TODO: Cache the client shared heap size in a persistent property.
2382 // It's possible that a native process or Java service or app accesses audioserver
2383 // after it is registered by system server, but before AudioService updates
2384 // the memory info. This would occur immediately after boot or an audioserver
2385 // crash and restore. Before update from AudioService, the client would get the
2386 // minimum heap size.
2387
2388 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2389 (isLowRamDevice ? "true" : "false"),
2390 (long long)mTotalMemory,
2391 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002392 return NO_ERROR;
2393}
2394
Andy Hung6f248bb2018-01-23 14:04:37 -08002395size_t AudioFlinger::getClientSharedHeapSize() const
2396{
2397 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2398 if (heapSizeInBytes != 0) { // read-only property overrides all.
2399 return heapSizeInBytes;
2400 }
2401 return mClientSharedHeapSize;
2402}
2403
Mikhail Naganovdea53042018-04-26 13:10:21 -07002404status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2405{
2406 ALOGV(__func__);
2407
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002408 status_t status = AudioValidator::validateAudioPortConfig(*config);
2409 if (status != NO_ERROR) {
2410 return status;
2411 }
2412
Mikhail Naganovdea53042018-04-26 13:10:21 -07002413 audio_module_handle_t module;
2414 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2415 module = config->ext.device.hw_module;
2416 } else {
2417 module = config->ext.mix.hw_module;
2418 }
2419
2420 Mutex::Autolock _l(mLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002421 AutoMutex lock(mHardwareLock);
Mikhail Naganovdea53042018-04-26 13:10:21 -07002422 ssize_t index = mAudioHwDevs.indexOfKey(module);
2423 if (index < 0) {
2424 ALOGW("%s() bad hw module %d", __func__, module);
2425 return BAD_VALUE;
2426 }
2427
2428 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2429 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2430}
2431
Eric Laurent93c3d412014-08-01 14:48:35 -07002432audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2433{
2434 Mutex::Autolock _l(mLock);
Eric Laurentfa90e842014-10-17 18:12:31 -07002435
2436 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2437 if (index >= 0) {
2438 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2439 mHwAvSyncIds.valueAt(index), sessionId);
2440 return mHwAvSyncIds.valueAt(index);
2441 }
2442
Eric Laurent00abf0d2020-04-22 19:28:22 -07002443 sp<DeviceHalInterface> dev;
2444 {
2445 AutoMutex lock(mHardwareLock);
2446 if (mPrimaryHardwareDev == nullptr) {
2447 return AUDIO_HW_SYNC_INVALID;
2448 }
2449 dev = mPrimaryHardwareDev->hwDevice();
2450 }
2451 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002452 return AUDIO_HW_SYNC_INVALID;
2453 }
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002454 String8 reply;
2455 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002456 if (dev->getParameters(String8(AudioParameter::keyHwAvSync), &reply) == OK) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002457 param = AudioParameter(reply);
2458 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002459
2460 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07002461 if (param.getInt(String8(AudioParameter::keyHwAvSync), value) != NO_ERROR) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002462 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2463 return AUDIO_HW_SYNC_INVALID;
2464 }
2465
2466 // allow only one session for a given HW A/V sync ID.
2467 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2468 if (mHwAvSyncIds.valueAt(i) == (audio_hw_sync_t)value) {
2469 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2470 value, mHwAvSyncIds.keyAt(i));
2471 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002472 break;
2473 }
2474 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002475
2476 mHwAvSyncIds.add(sessionId, value);
2477
2478 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2479 sp<PlaybackThread> thread = mPlaybackThreads.valueAt(i);
2480 uint32_t sessions = thread->hasAudioSession(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07002481 if (sessions & ThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002482 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002483 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002484 String8 keyValuePairs = param.toString();
2485 thread->setParameters(keyValuePairs);
2486 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2487 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002488 break;
2489 }
2490 }
2491
2492 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2493 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002494}
2495
Eric Laurent72e3f392015-05-20 14:43:50 -07002496status_t AudioFlinger::systemReady()
2497{
2498 Mutex::Autolock _l(mLock);
2499 ALOGI("%s", __FUNCTION__);
2500 if (mSystemReady) {
2501 ALOGW("%s called twice", __FUNCTION__);
2502 return NO_ERROR;
2503 }
2504 mSystemReady = true;
2505 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2506 ThreadBase *thread = (ThreadBase *)mPlaybackThreads.valueAt(i).get();
2507 thread->systemReady();
2508 }
2509 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2510 ThreadBase *thread = (ThreadBase *)mRecordThreads.valueAt(i).get();
2511 thread->systemReady();
2512 }
2513 return NO_ERROR;
2514}
2515
jiabin46a76fa2018-01-05 10:18:21 -08002516status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfo> *microphones)
2517{
jiabin9ff780e2018-03-19 18:19:52 -07002518 AutoMutex lock(mHardwareLock);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002519 status_t status = INVALID_OPERATION;
2520
2521 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2522 std::vector<media::MicrophoneInfo> mics;
2523 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2524 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2525 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2526 mHardwareStatus = AUDIO_HW_IDLE;
2527 if (devStatus == NO_ERROR) {
2528 microphones->insert(microphones->begin(), mics.begin(), mics.end());
2529 // report success if at least one HW module supports the function.
2530 status = NO_ERROR;
2531 }
2532 }
2533
jiabin9ff780e2018-03-19 18:19:52 -07002534 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002535}
2536
Eric Laurentfa90e842014-10-17 18:12:31 -07002537// setAudioHwSyncForSession_l() must be called with AudioFlinger::mLock held
2538void AudioFlinger::setAudioHwSyncForSession_l(PlaybackThread *thread, audio_session_t sessionId)
2539{
2540 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2541 if (index >= 0) {
2542 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2543 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2544 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002545 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002546 String8 keyValuePairs = param.toString();
2547 thread->setParameters(keyValuePairs);
2548 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2549 [](const sp<PlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002550 }
2551}
2552
2553
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002554// ----------------------------------------------------------------------------
2555
Eric Laurent83b88082014-06-20 18:31:16 -07002556
Eric Laurent6acd1d42017-01-04 14:23:29 -08002557sp<AudioFlinger::ThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07002558 audio_io_handle_t *output,
2559 audio_config_t *config,
2560 audio_devices_t deviceType,
2561 const String8& address,
2562 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07002563{
jiabin43810402019-10-24 14:58:31 -07002564 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07002565 if (outHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002566 return 0;
Eric Laurent83b88082014-06-20 18:31:16 -07002567 }
2568
Eric Laurentcf2c0212014-07-25 16:20:43 -07002569 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002570 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
2571 } else {
2572 // Audio Policy does not currently request a specific output handle.
2573 // If this is ever needed, see openInput_l() for example code.
2574 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
2575 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002576 }
Eric Laurent83b88082014-06-20 18:31:16 -07002577
2578 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
2579
Eric Laurent83b88082014-06-20 18:31:16 -07002580 // FOR TESTING ONLY:
Andy Hung9a592762014-07-21 21:56:01 -07002581 // This if statement allows overriding the audio policy settings
2582 // and forcing a specific format or channel mask to the HAL/Sink device for testing.
2583 if (!(flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT))) {
2584 // Check only for Normal Mixing mode
2585 if (kEnableExtendedPrecision) {
2586 // Specify format (uncomment one below to choose)
2587 //config->format = AUDIO_FORMAT_PCM_FLOAT;
2588 //config->format = AUDIO_FORMAT_PCM_24_BIT_PACKED;
2589 //config->format = AUDIO_FORMAT_PCM_32_BIT;
2590 //config->format = AUDIO_FORMAT_PCM_8_24_BIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002591 // ALOGV("openOutput_l() upgrading format to %#08x", config->format);
Andy Hung9a592762014-07-21 21:56:01 -07002592 }
2593 if (kEnableExtendedChannels) {
2594 // Specify channel mask (uncomment one below to choose)
2595 //config->channel_mask = audio_channel_out_mask_from_count(4); // for USB 4ch
2596 //config->channel_mask = audio_channel_mask_from_representation_and_bits(
2597 // AUDIO_CHANNEL_REPRESENTATION_INDEX, (1 << 4) - 1); // another 4ch example
2598 }
Eric Laurent83b88082014-06-20 18:31:16 -07002599 }
2600
Phil Burk062e67a2015-02-11 13:40:50 -08002601 AudioStreamOut *outputStream = NULL;
2602 status_t status = outHwDev->openOutputStream(
2603 &outputStream,
2604 *output,
jiabin43810402019-10-24 14:58:31 -07002605 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08002606 flags,
2607 config,
2608 address.string());
Eric Laurent83b88082014-06-20 18:31:16 -07002609
2610 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07002611
Phil Burk062e67a2015-02-11 13:40:50 -08002612 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002613 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
2614 sp<MmapPlaybackThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002615 new MmapPlaybackThread(this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002616 mMmapThreads.add(*output, thread);
2617 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
2618 *output, thread.get());
2619 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002620 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002621 sp<PlaybackThread> thread;
2622 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002623 thread = new OffloadThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002624 ALOGV("openOutput_l() created offload output: ID %d thread %p",
2625 *output, thread.get());
2626 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
2627 || !isValidPcmSinkFormat(config->format)
2628 || !isValidPcmSinkChannelMask(config->channel_mask)) {
jiabinc52b1ff2019-10-31 17:20:42 -07002629 thread = new DirectOutputThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002630 ALOGV("openOutput_l() created direct output: ID %d thread %p",
2631 *output, thread.get());
2632 } else {
jiabinc52b1ff2019-10-31 17:20:42 -07002633 thread = new MixerThread(this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002634 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
2635 *output, thread.get());
2636 }
2637 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01002638 struct audio_patch patch;
2639 mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
2640 if (thread->isMsdDevice()) {
2641 thread->setDownStreamPatch(&patch);
2642 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002643 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07002644 }
Eric Laurent83b88082014-06-20 18:31:16 -07002645 }
2646
2647 return 0;
2648}
2649
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002650status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
2651 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002653 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
2654 aidl2legacy_int32_t_audio_module_handle_t(request.module));
2655 audio_config_t config = VALUE_OR_RETURN_STATUS(
2656 aidl2legacy_AudioConfig_audio_config_t(request.config));
2657 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
2658 aidl2legacy_DeviceDescriptorBase(request.device));
2659 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08002660 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002661
2662 audio_io_handle_t output;
2663 uint32_t latencyMs;
2664
jiabin43810402019-10-24 14:58:31 -07002665 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002666 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08002667 this, module,
jiabin43810402019-10-24 14:58:31 -07002668 device->toString().c_str(),
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002669 config.sample_rate,
2670 config.format,
2671 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07002672 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673
jiabin43810402019-10-24 14:58:31 -07002674 audio_devices_t deviceType = device->type();
2675 const String8 address = String8(device->address().c_str());
2676
2677 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002678 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002680
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 Mutex::Autolock _l(mLock);
2682
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002683 sp<ThreadBase> thread = openOutput_l(module, &output, &config, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07002684 if (thread != 0) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002685 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
2686 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002687 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002688
Eric Laurent6acd1d42017-01-04 14:23:29 -08002689 // notify client processes of the new output creation
2690 playbackThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002691
Eric Laurent00abf0d2020-04-22 19:28:22 -07002692 // the first primary output opened designates the primary hw device if no HW module
2693 // named "primary" was already loaded.
2694 AutoMutex lock(mHardwareLock);
2695 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08002696 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002697 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002698
Eric Laurent6acd1d42017-01-04 14:23:29 -08002699 mHardwareStatus = AUDIO_HW_SET_MODE;
2700 mPrimaryHardwareDev->hwDevice()->setMode(mMode);
2701 mHardwareStatus = AUDIO_HW_IDLE;
2702 }
2703 } else {
2704 MmapThread *mmapThread = (MmapThread *)thread.get();
2705 mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002706 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08002707 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
2708 response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config));
2709 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08002710 response->flags = VALUE_OR_RETURN_STATUS(
2711 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07002712 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 }
2714
Eric Laurentcf2c0212014-07-25 16:20:43 -07002715 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716}
2717
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002718audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
2719 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720{
2721 Mutex::Autolock _l(mLock);
2722 MixerThread *thread1 = checkMixerThread_l(output1);
2723 MixerThread *thread2 = checkMixerThread_l(output2);
2724
2725 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002726 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
2727 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07002728 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002729 }
2730
Glenn Kasteneeecb982016-02-26 10:44:04 -08002731 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Eric Laurent72e3f392015-05-20 14:43:50 -07002732 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 thread->addOutputTrack(thread2);
2734 mPlaybackThreads.add(id, thread);
2735 // notify client processes of the new output creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002736 thread->ioConfigChanged(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002737 return id;
2738}
2739
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002740status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741{
Glenn Kastend96c5722012-04-25 13:44:49 -07002742 return closeOutput_nonvirtual(output);
2743}
2744
2745status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
2746{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 // keep strong reference on the playback thread so that
2748 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002749 sp<PlaybackThread> playbackThread;
2750 sp<MmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 {
2752 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002753 playbackThread = checkPlaybackThread_l(output);
2754 if (playbackThread != NULL) {
2755 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
Andy Hungdc099c22018-09-18 13:46:39 -07002757 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07002758
Eric Laurent6acd1d42017-01-04 14:23:29 -08002759 if (playbackThread->type() == ThreadBase::MIXER) {
2760 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2761 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
2762 DuplicatingThread *dupThread =
2763 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
2764 dupThread->removeOutputTrack((MixerThread *)playbackThread.get());
2765 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002766 }
2767 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002768
2769
Eric Laurent6acd1d42017-01-04 14:23:29 -08002770 mPlaybackThreads.removeItem(output);
2771 // save all effects to the default thread
2772 if (mPlaybackThreads.size()) {
2773 PlaybackThread *dstThread = checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
2774 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002775 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Eric Laurent6acd1d42017-01-04 14:23:29 -08002776 Mutex::Autolock _dl(dstThread->mLock);
2777 Mutex::Autolock _sl(playbackThread->mLock);
2778 Vector< sp<EffectChain> > effectChains = playbackThread->getEffectChains_l();
2779 for (size_t i = 0; i < effectChains.size(); i ++) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08002780 moveEffectChain_l(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07002781 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 }
2784 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002785 } else {
2786 mmapThread = (MmapPlaybackThread *)checkMmapThread_l(output);
2787 if (mmapThread == 0) {
2788 return BAD_VALUE;
2789 }
Andy Hungdc099c22018-09-18 13:46:39 -07002790 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002791 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08002792 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 }
Eric Laurent73e26b62015-04-27 16:55:58 -07002794 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
2795 ioDesc->mIoHandle = output;
2796 ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc);
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002797 mPatchPanel.notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08002799 // The thread entity (active unit of execution) is no longer running here,
2800 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801
Eric Laurent6acd1d42017-01-04 14:23:29 -08002802 if (playbackThread != 0) {
2803 playbackThread->exit();
2804 if (!playbackThread->isDuplicating()) {
2805 closeOutputFinish(playbackThread);
2806 }
2807 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08002808 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002809 mmapThread->exit();
2810 AudioStreamOut *out = mmapThread->clearOutput();
2811 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2812 // from now on thread->mOutput is NULL
2813 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 }
2815 return NO_ERROR;
2816}
2817
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002818void AudioFlinger::closeOutputFinish(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002819{
2820 AudioStreamOut *out = thread->clearOutput();
2821 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
2822 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07002823 delete out;
2824}
2825
Mikhail Naganov444ecc32018-05-01 17:40:05 -07002826void AudioFlinger::closeThreadInternal_l(const sp<PlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07002827{
2828 mPlaybackThreads.removeItem(thread->mId);
2829 thread->exit();
2830 closeOutputFinish(thread);
2831}
2832
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002833status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834{
2835 Mutex::Autolock _l(mLock);
2836 PlaybackThread *thread = checkPlaybackThread_l(output);
2837
2838 if (thread == NULL) {
2839 return BAD_VALUE;
2840 }
2841
Steve Block3856b092011-10-20 11:56:00 +01002842 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843 thread->suspend();
2844
2845 return NO_ERROR;
2846}
2847
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002848status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849{
2850 Mutex::Autolock _l(mLock);
2851 PlaybackThread *thread = checkPlaybackThread_l(output);
2852
2853 if (thread == NULL) {
2854 return BAD_VALUE;
2855 }
2856
Steve Block3856b092011-10-20 11:56:00 +01002857 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
2859 thread->restore();
2860
2861 return NO_ERROR;
2862}
2863
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002864status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
2865 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866{
Eric Laurent83b88082014-06-20 18:31:16 -07002867 Mutex::Autolock _l(mLock);
2868
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002869 if (request.device.type == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002870 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07002871 }
2872
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002873 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
2874 aidl2legacy_int32_t_audio_io_handle_t(request.input));
2875 audio_config_t config = VALUE_OR_RETURN_STATUS(
2876 aidl2legacy_AudioConfig_audio_config_t(request.config));
2877 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
2878 aidl2legacy_AudioDeviceTypeAddress(request.device));
2879
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002880 sp<ThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002881 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
2882 &input,
2883 &config,
2884 device.mType,
2885 device.address().c_str(),
2886 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSourceType_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08002887 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002888 AUDIO_DEVICE_NONE,
2889 String8{});
2890
2891 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
2892 response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config));
2893 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07002894
2895 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07002896 // notify client processes of the new input creation
Eric Laurent73e26b62015-04-27 16:55:58 -07002897 thread->ioConfigChanged(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002898 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002899 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002900 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07002901}
Dima Zavin799a70e2011-04-18 16:57:27 -07002902
Eric Laurent6acd1d42017-01-04 14:23:29 -08002903sp<AudioFlinger::ThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002904 audio_io_handle_t *input,
2905 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08002906 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002907 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002908 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002909 audio_input_flags_t flags,
2910 audio_devices_t outputDevice,
2911 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07002912{
Glenn Kastene7d66712015-03-05 13:46:52 -08002913 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002914 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002915 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07002916 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07002917 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002918
Glenn Kasteneeecb982016-02-26 10:44:04 -08002919 // Audio Policy can request a specific handle for hardware hotword.
2920 // The goal here is not to re-open an already opened input.
2921 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07002922 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08002923 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
2924 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
2925 ALOGE("openInput_l() requested input handle %d is invalid", *input);
2926 return 0;
2927 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
2928 // This should not happen in a transient state with current design.
2929 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
2930 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002931 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002932
Eric Laurentcf2c0212014-07-25 16:20:43 -07002933 audio_config_t halconfig = *config;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002934 sp<DeviceHalInterface> inHwHal = inHwDev->hwDevice();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002935 sp<StreamInHalInterface> inStream;
2936 status_t status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002937 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002938 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002939 ALOGV("openInput_l() openInputStream returned input %p, devices %#x, SamplingRate %d"
2940 ", Format %#x, Channels %#x, flags %#x, status %d addr %s",
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002941 inStream.get(),
Mikhail Naganovf558e022016-11-14 17:45:17 -08002942 devices,
Eric Laurentcf2c0212014-07-25 16:20:43 -07002943 halconfig.sample_rate,
2944 halconfig.format,
2945 halconfig.channel_mask,
Glenn Kastenec40d282014-07-15 15:31:26 -07002946 flags,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002947 status, address);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002949 // If the input could not be opened with the requested parameters and we can handle the
Andy Hung6770c6f2015-04-07 13:43:36 -07002950 // conversion internally, try to open again with the proposed parameters.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07002951 if (status == BAD_VALUE &&
Andy Hung6770c6f2015-04-07 13:43:36 -07002952 audio_is_linear_pcm(config->format) &&
2953 audio_is_linear_pcm(halconfig.format) &&
2954 (halconfig.sample_rate <= AUDIO_RESAMPLER_DOWN_RATIO_MAX * config->sample_rate) &&
vivek mehta75346662016-05-04 18:45:46 -07002955 (audio_channel_count_from_in_mask(halconfig.channel_mask) <= FCC_8) &&
2956 (audio_channel_count_from_in_mask(config->channel_mask) <= FCC_8)) {
Glenn Kasten85948432013-08-19 12:09:05 -07002957 // FIXME describe the change proposed by HAL (save old values so we can log them here)
Eric Laurentcf2c0212014-07-25 16:20:43 -07002958 ALOGV("openInput_l() reopening with proposed sampling rate and channel mask");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002959 inStream.clear();
2960 status = inHwHal->openInputStream(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002961 *input, devices, &halconfig, flags, address, source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08002962 outputDevice, outputDeviceAddress, &inStream);
Glenn Kasten85948432013-08-19 12:09:05 -07002963 // FIXME log this new status; HAL should not propose any further changes
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 }
2965
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002966 if (status == NO_ERROR && inStream != 0) {
Eric Laurent05067782016-06-01 18:27:28 -07002967 AudioStreamIn *inputStream = new AudioStreamIn(inHwDev, inStream, flags);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002968 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2969 sp<MmapCaptureThread> thread =
jiabinc52b1ff2019-10-31 17:20:42 -07002970 new MmapCaptureThread(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002971 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08002972 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
2973 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08002974 return thread;
2975 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08002976 // Start record thread
2977 // RecordThread requires both input and output device indication to forward to audio
2978 // pre processing modules
jiabinc52b1ff2019-10-31 17:20:42 -07002979 sp<RecordThread> thread = new RecordThread(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002980 mRecordThreads.add(*input, thread);
2981 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
2982 return thread;
2983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 }
2985
Eric Laurentcf2c0212014-07-25 16:20:43 -07002986 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 return 0;
2988}
2989
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002990status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991{
Glenn Kastend96c5722012-04-25 13:44:49 -07002992 return closeInput_nonvirtual(input);
2993}
2994
2995status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
2996{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 // keep strong reference on the record thread so that
2998 // it is not destroyed while exit() is executed
Eric Laurent6acd1d42017-01-04 14:23:29 -08002999 sp<RecordThread> recordThread;
3000 sp<MmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 {
3002 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003003 recordThread = checkRecordThread_l(input);
3004 if (recordThread != 0) {
3005 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006
Andy Hungdc099c22018-09-18 13:46:39 -07003007 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07003008
Eric Laurent6acd1d42017-01-04 14:23:29 -08003009 // If we still have effect chains, it means that a client still holds a handle
3010 // on at least one effect. We must either move the chain to an existing thread with the
3011 // same session ID or put it aside in case a new record thread is opened for a
3012 // new capture on the same session
3013 sp<EffectChain> chain;
3014 {
3015 Mutex::Autolock _sl(recordThread->mLock);
3016 Vector< sp<EffectChain> > effectChains = recordThread->getEffectChains_l();
3017 // Note: maximum one chain per record thread
3018 if (effectChains.size() != 0) {
3019 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003020 }
3021 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003022 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003023 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003024 // This should only happen in case of overlap between one thread tear down and the
3025 // creation of its replacement
3026 size_t i;
3027 for (i = 0; i < mRecordThreads.size(); i++) {
3028 sp<RecordThread> t = mRecordThreads.valueAt(i);
3029 if (t == recordThread) {
3030 continue;
3031 }
3032 if (t->hasAudioSession(chain->sessionId()) != 0) {
3033 Mutex::Autolock _l(t->mLock);
3034 ALOGV("closeInput() found thread %d for effect session %d",
3035 t->id(), chain->sessionId());
3036 t->addEffectChain_l(chain);
3037 break;
3038 }
3039 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003040 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003041 if (i == mRecordThreads.size()) {
3042 putOrphanEffectChain_l(chain);
3043 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003044 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003045 mRecordThreads.removeItem(input);
3046 } else {
3047 mmapThread = (MmapCaptureThread *)checkMmapThread_l(input);
3048 if (mmapThread == 0) {
3049 return BAD_VALUE;
3050 }
Andy Hungdc099c22018-09-18 13:46:39 -07003051 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003052 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003053 }
Eric Laurent73e26b62015-04-27 16:55:58 -07003054 const sp<AudioIoDescriptor> ioDesc = new AudioIoDescriptor();
3055 ioDesc->mIoHandle = input;
3056 ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 }
Eric Laurent83b88082014-06-20 18:31:16 -07003058 // FIXME: calling thread->exit() without mLock held should not be needed anymore now that
3059 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003060 if (recordThread != 0) {
3061 closeInputFinish(recordThread);
3062 } else if (mmapThread != 0) {
3063 mmapThread->exit();
3064 AudioStreamIn *in = mmapThread->clearInput();
3065 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3066 // from now on thread->mInput is NULL
3067 delete in;
3068 }
Eric Laurent83b88082014-06-20 18:31:16 -07003069 return NO_ERROR;
3070}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003071
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003072void AudioFlinger::closeInputFinish(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003073{
3074 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003075 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003076 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003077 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003078 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003079}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080
Mikhail Naganov444ecc32018-05-01 17:40:05 -07003081void AudioFlinger::closeThreadInternal_l(const sp<RecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003082{
3083 mRecordThreads.removeItem(thread->mId);
3084 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085}
3086
Glenn Kastend2304db2014-02-03 07:40:31 -08003087status_t AudioFlinger::invalidateStream(audio_stream_type_t stream)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088{
3089 Mutex::Autolock _l(mLock);
Glenn Kastend2304db2014-02-03 07:40:31 -08003090 ALOGV("invalidateStream() stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091
3092 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3093 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07003094 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07003095 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003096 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3097 mMmapThreads[i]->invalidateTracks(stream);
3098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 return NO_ERROR;
3100}
3101
3102
Glenn Kasteneeecb982016-02-26 10:44:04 -08003103audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104{
Glenn Kasten9d003132016-04-06 14:38:09 -07003105 // This is a binder API, so a malicious client could pass in a bad parameter.
3106 // Check for that before calling the internal API nextUniqueId().
3107 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3108 ALOGE("newAudioUniqueId invalid use %d", use);
3109 return AUDIO_UNIQUE_ID_ALLOCATE;
3110 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003111 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112}
3113
Andy Hung8b0bfd92019-12-23 13:11:11 -08003114void AudioFlinger::acquireAudioSessionId(
3115 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003116{
3117 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08003118 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003119 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003120 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003121 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3122 caller = pid; // check must match releaseAudioSessionId()
3123 }
3124 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3125 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003126 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003127
Eric Laurent021cf962014-05-13 10:18:14 -07003128 {
3129 Mutex::Autolock _cl(mClientLock);
3130 // Ignore requests received from processes not known as notification client. The request
3131 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3132 // called from a different pid leaving a stale session reference. Also we don't know how
3133 // to clear this reference if the client process dies.
3134 if (mNotificationClients.indexOfKey(caller) < 0) {
3135 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3136 return;
3137 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003138 }
3139
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003140 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003141 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003142 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003143 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3144 ref->mCnt++;
3145 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003146 return;
3147 }
3148 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003149 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003150 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003151}
3152
Glenn Kastend848eb42016-03-08 13:42:11 -08003153void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003154{
Eric Laurent6c796322019-04-09 14:13:17 -07003155 std::vector< sp<EffectModule> > removedEffects;
3156 {
3157 Mutex::Autolock _l(mLock);
3158 pid_t caller = IPCThreadState::self()->getCallingPid();
3159 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3160 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003161 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3162 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003163 }
Eric Laurent6c796322019-04-09 14:13:17 -07003164 size_t num = mAudioSessionRefs.size();
3165 for (size_t i = 0; i < num; i++) {
3166 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3167 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3168 ref->mCnt--;
3169 ALOGV(" decremented refcount to %d", ref->mCnt);
3170 if (ref->mCnt == 0) {
3171 mAudioSessionRefs.removeAt(i);
3172 delete ref;
3173 std::vector< sp<EffectModule> > effects = purgeStaleEffects_l();
3174 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3175 }
3176 goto Exit;
3177 }
3178 }
3179 // If the caller is audioserver it is likely that the session being released was acquired
3180 // on behalf of a process not in notification clients and we ignore the warning.
3181 ALOGW_IF(!isAudioServerUid(callerUid),
3182 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003183 }
Eric Laurent6c796322019-04-09 14:13:17 -07003184
3185Exit:
3186 for (auto& effect : removedEffects) {
3187 effect->updatePolicyState();
3188 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003189}
3190
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003191bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3192{
3193 size_t num = mAudioSessionRefs.size();
3194 for (size_t i = 0; i < num; i++) {
3195 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3196 if (ref->mSessionid == audioSession) {
3197 return true;
3198 }
3199 }
3200 return false;
3201}
3202
Eric Laurent6c796322019-04-09 14:13:17 -07003203std::vector<sp<AudioFlinger::EffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003204
Steve Block3856b092011-10-20 11:56:00 +01003205 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003206
3207 Vector< sp<EffectChain> > chains;
Eric Laurent6c796322019-04-09 14:13:17 -07003208 std::vector< sp<EffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003209
3210 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3211 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003212 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003213 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3214 sp<EffectChain> ec = t->mEffectChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003215 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003216 chains.push(ec);
3217 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003218 }
3219 }
Eric Laurent6c796322019-04-09 14:13:17 -07003220
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003221 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3222 sp<RecordThread> t = mRecordThreads.valueAt(i);
Mateusz Kaplon2a6e1b02017-03-30 16:50:50 +02003223 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003224 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3225 sp<EffectChain> ec = t->mEffectChains[j];
3226 chains.push(ec);
3227 }
3228 }
3229
Eric Laurent6c796322019-04-09 14:13:17 -07003230 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3231 sp<MmapThread> t = mMmapThreads.valueAt(i);
3232 Mutex::Autolock _l(t->mLock);
3233 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
3234 sp<EffectChain> ec = t->mEffectChains[j];
3235 chains.push(ec);
3236 }
3237 }
3238
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003239 for (size_t i = 0; i < chains.size(); i++) {
3240 sp<EffectChain> ec = chains[i];
3241 int sessionid = ec->sessionId();
Eric Laurent6b446ce2019-12-13 10:56:31 -08003242 sp<ThreadBase> t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003243 if (t == 0) {
3244 continue;
3245 }
3246 size_t numsessionrefs = mAudioSessionRefs.size();
3247 bool found = false;
3248 for (size_t k = 0; k < numsessionrefs; k++) {
3249 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003250 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003251 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003252 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003253 found = true;
3254 break;
3255 }
3256 }
3257 if (!found) {
Glenn Kastene198c362013-08-13 09:13:36 -07003258 Mutex::Autolock _l(t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003259 // remove all effects from the chain
3260 while (ec->mEffects.size()) {
3261 sp<EffectModule> effect = ec->mEffects[0];
3262 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003263 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003264 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003265 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003266 }
Eric Laurent6c796322019-04-09 14:13:17 -07003267 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003268 }
3269 }
3270 }
Eric Laurent6c796322019-04-09 14:13:17 -07003271 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003272}
3273
Andy Hungdc099c22018-09-18 13:46:39 -07003274// dumpToThreadLog_l() must be called with AudioFlinger::mLock held
3275void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
3276{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303277 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3278 audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
Andy Hungdc099c22018-09-18 13:46:39 -07003279 const int fd = fdToString.fd();
3280 if (fd >= 0) {
3281 thread->dump(fd, {} /* args */);
3282 mThreadLog.logs(-1 /* time */, fdToString.getStringAndClose());
3283 }
3284}
3285
Glenn Kasteneeecb982016-02-26 10:44:04 -08003286// checkThread_l() must be called with AudioFlinger::mLock held
3287AudioFlinger::ThreadBase *AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3288{
Eric Laurent6acd1d42017-01-04 14:23:29 -08003289 ThreadBase *thread = checkMmapThread_l(ioHandle);
3290 if (thread == 0) {
3291 switch (audio_unique_id_get_use(ioHandle)) {
3292 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3293 thread = checkPlaybackThread_l(ioHandle);
3294 break;
3295 case AUDIO_UNIQUE_ID_USE_INPUT:
3296 thread = checkRecordThread_l(ioHandle);
3297 break;
3298 default:
3299 break;
3300 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003301 }
3302 return thread;
3303}
3304
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003306AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307{
Glenn Kastena1117922012-01-26 10:53:32 -08003308 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309}
3310
3311// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003312AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313{
3314 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08003315 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316}
3317
3318// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003319AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320{
Glenn Kastena1117922012-01-26 10:53:32 -08003321 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322}
3323
Eric Laurent6acd1d42017-01-04 14:23:29 -08003324// checkMmapThread_l() must be called with AudioFlinger::mLock held
3325AudioFlinger::MmapThread *AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3326{
3327 return mMmapThreads.valueFor(io).get();
3328}
3329
3330
3331// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
3332AudioFlinger::VolumeInterface *AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
3333{
Eric Laurent7459b902017-04-19 18:10:41 -07003334 VolumeInterface *volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003335 if (volumeInterface == nullptr) {
3336 MmapThread *mmapThread = mMmapThreads.valueFor(output).get();
3337 if (mmapThread != nullptr) {
3338 if (mmapThread->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003339 MmapPlaybackThread *mmapPlaybackThread =
3340 static_cast<MmapPlaybackThread *>(mmapThread);
3341 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003342 }
3343 }
3344 }
3345 return volumeInterface;
3346}
3347
3348Vector <AudioFlinger::VolumeInterface *> AudioFlinger::getAllVolumeInterfaces_l() const
3349{
3350 Vector <VolumeInterface *> volumeInterfaces;
3351 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7459b902017-04-19 18:10:41 -07003352 volumeInterfaces.add(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003353 }
3354 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3355 if (mMmapThreads.valueAt(i)->isOutput()) {
Eric Laurent7459b902017-04-19 18:10:41 -07003356 MmapPlaybackThread *mmapPlaybackThread =
3357 static_cast<MmapPlaybackThread *>(mMmapThreads.valueAt(i).get());
3358 volumeInterfaces.add(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003359 }
3360 }
3361 return volumeInterfaces;
3362}
3363
Glenn Kasteneeecb982016-02-26 10:44:04 -08003364audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365{
Glenn Kasten9d003132016-04-06 14:38:09 -07003366 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003367 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003368 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3369 for (int retry = 0; retry < maxRetries; retry++) {
3370 // The cast allows wraparound from max positive to min negative instead of abort
3371 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3372 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3373 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3374 // allow wrap by skipping 0 and -1 for session ids
3375 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3376 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3377 return (audio_unique_id_t) (base | use);
3378 }
3379 }
3380 // We have no way of recovering from wraparound
3381 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3382 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383}
3384
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003385AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003386{
Eric Laurent00abf0d2020-04-22 19:28:22 -07003387 AutoMutex lock(mHardwareLock);
3388 if (mPrimaryHardwareDev == nullptr) {
3389 return nullptr;
3390 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3392 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003393 if(thread->isDuplicating()) {
3394 continue;
3395 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003396 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003397 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003398 return thread;
3399 }
3400 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003401 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003402}
3403
jiabinc52b1ff2019-10-31 17:20:42 -07003404DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003405{
3406 PlaybackThread *thread = primaryPlaybackThread_l();
3407
3408 if (thread == NULL) {
jiabinc52b1ff2019-10-31 17:20:42 -07003409 return DeviceTypeSet();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003410 }
3411
jiabinc52b1ff2019-10-31 17:20:42 -07003412 return thread->outDeviceTypes();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003413}
3414
Glenn Kastena7335632016-06-09 17:09:53 -07003415AudioFlinger::PlaybackThread *AudioFlinger::fastPlaybackThread_l() const
3416{
3417 size_t minFrameCount = 0;
3418 PlaybackThread *minThread = NULL;
3419 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3420 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3421 if (!thread->isDuplicating()) {
3422 size_t frameCount = thread->frameCountHAL();
3423 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3424 (frameCount == minFrameCount && thread->hasFastMixer() &&
3425 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3426 minFrameCount = frameCount;
3427 minThread = thread;
3428 }
3429 }
3430 }
3431 return minThread;
3432}
3433
jiabineb3bda02020-06-30 14:07:03 -07003434AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const {
3435 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
3436 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
3437 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3438 return thread;
3439 }
3440 }
3441 return nullptr;
3442}
3443
Eric Laurenta011e352012-03-29 15:51:43 -07003444sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08003445 audio_session_t triggerSession,
3446 audio_session_t listenerSession,
Eric Laurenta011e352012-03-29 15:51:43 -07003447 sync_event_callback_t callBack,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003448 const wp<RefBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07003449{
3450 Mutex::Autolock _l(mLock);
3451
3452 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
3453 status_t playStatus = NAME_NOT_FOUND;
3454 status_t recStatus = NAME_NOT_FOUND;
3455 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3456 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
3457 if (playStatus == NO_ERROR) {
3458 return event;
3459 }
3460 }
3461 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3462 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
3463 if (recStatus == NO_ERROR) {
3464 return event;
3465 }
3466 }
3467 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
3468 mPendingSyncEvents.add(event);
3469 } else {
3470 ALOGV("createSyncEvent() invalid event %d", event->type());
3471 event.clear();
3472 }
3473 return event;
3474}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003475
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476// ----------------------------------------------------------------------------
3477// Effect management
3478// ----------------------------------------------------------------------------
3479
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003480sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
3481 return mEffectsFactoryHal;
3482}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483
Glenn Kastenf587ba52012-01-26 16:25:10 -08003484status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485{
3486 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003487 if (mEffectsFactoryHal.get()) {
3488 return mEffectsFactoryHal->queryNumberEffects(numEffects);
3489 } else {
3490 return -ENODEV;
3491 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492}
3493
Glenn Kastenf587ba52012-01-26 16:25:10 -08003494status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495{
3496 Mutex::Autolock _l(mLock);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003497 if (mEffectsFactoryHal.get()) {
3498 return mEffectsFactoryHal->getDescriptor(index, descriptor);
3499 } else {
3500 return -ENODEV;
3501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502}
3503
Glenn Kasten5e92a782012-01-30 07:40:52 -08003504status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003505 const effect_uuid_t *pTypeUuid,
3506 uint32_t preferredTypeFlag,
3507 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003509 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
3510 return BAD_VALUE;
3511 }
3512
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 Mutex::Autolock _l(mLock);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003514
3515 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003516 return -ENODEV;
3517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003519 status_t status = NO_ERROR;
3520 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
3521 // If uuid is specified, request effect descriptor from that.
3522 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
3523 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
3524 // If uuid is not specified, look for an available implementation
3525 // of the required type instead.
3526
3527 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
3528 effect_descriptor_t desc;
3529 desc.flags = 0; // prevent compiler warning
3530
3531 uint32_t numEffects = 0;
3532 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
3533 if (status < 0) {
3534 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
3535 return status;
3536 }
3537
3538 bool found = false;
3539 for (uint32_t i = 0; i < numEffects; i++) {
3540 status = mEffectsFactoryHal->getDescriptor(i, &desc);
3541 if (status < 0) {
3542 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
3543 continue;
3544 }
3545 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
3546 // If matching type found save effect descriptor.
3547 found = true;
3548 *descriptor = desc;
3549
3550 // If there's no preferred flag or this descriptor matches the preferred
3551 // flag, success! If this descriptor doesn't match the preferred
3552 // flag, continue enumeration in case a better matching version of this
3553 // effect type is available. Note that this means if no effect with a
3554 // correct flag is found, the descriptor returned will correspond to the
3555 // last effect that at least had a matching type uuid (if any).
3556 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
3557 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
3558 break;
3559 }
3560 }
3561 }
3562
3563 if (!found) {
3564 status = NAME_NOT_FOUND;
3565 ALOGW("getEffectDescriptor(): Effect not found by type.");
3566 }
3567 } else {
3568 status = BAD_VALUE;
3569 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
3570 }
3571 return status;
3572}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003574status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
3575 media::CreateEffectResponse* response) {
3576 const sp<IEffectClient>& effectClient = request.client;
3577 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003578 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003579 aidl2legacy_AudioDeviceTypeAddress(request.device));
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003580 Identity adjIdentity = request.identity;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003581 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003582 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003583 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
3584 aidl2legacy_int32_t_audio_io_handle_t(request.output));
3585 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003586 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
3587 const bool probe = request.probe;
3588
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 sp<EffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003590 effect_descriptor_t descOut;
3591 int enabledOut = 0;
3592 int idOut = -1;
3593
3594 status_t lStatus = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003596 // TODO b/182392553: refactor or make clearer
Eric Laurentb6436272016-12-07 19:24:50 -08003597 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003598 adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
3599 pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjIdentity.pid));
3600 if (currentPid == -1 || !isAudioServerOrMediaServerUid(callingUid)) {
Eric Laurentb6436272016-12-07 19:24:50 -08003601 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003602 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
Eric Laurentb6436272016-12-07 19:24:50 -08003603 "%s uid %d pid %d tried to pass itself off as pid %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003604 __func__, callingUid, callingPid, currentPid);
3605 adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid));
3606 currentPid = callingPid;
Eric Laurentb6436272016-12-07 19:24:50 -08003607 }
3608
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003609 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003610 adjIdentity.pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003612 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07003613 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07003614 lStatus = NO_INIT;
3615 goto Exit;
3616 }
3617
Andy Hung6096dcd2019-03-13 13:20:30 -07003618 // check audio settings permission for global effects
3619 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
3620 if (!settingsAllowed()) {
3621 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
3622 lStatus = PERMISSION_DENIED;
3623 goto Exit;
3624 }
3625 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
3626 if (!isAudioServerUid(callingUid)) {
3627 ALOGE("%s: only APM can create using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3628 lStatus = PERMISSION_DENIED;
3629 goto Exit;
3630 }
3631
3632 if (io == AUDIO_IO_HANDLE_NONE) {
3633 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
3634 lStatus = BAD_VALUE;
3635 goto Exit;
3636 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003637 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003638 if (!modifyDefaultAudioEffectsAllowed(adjIdentity)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003639 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
3640 lStatus = PERMISSION_DENIED;
3641 goto Exit;
3642 }
Eric Laurent94876032019-11-13 12:45:28 -08003643 if (io != AUDIO_IO_HANDLE_NONE) {
3644 ALOGE("%s: io handle should not be specified for device effect", __func__);
3645 lStatus = BAD_VALUE;
3646 goto Exit;
3647 }
Andy Hung6096dcd2019-03-13 13:20:30 -07003648 } else {
3649 // general sessionId.
3650
3651 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
3652 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
3653 lStatus = BAD_VALUE;
3654 goto Exit;
3655 }
3656
3657 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
3658 // to prevent creating an effect when one doesn't actually have track with that session?
3659 }
3660
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003662 // Get the full effect descriptor from the uuid/type.
3663 // If the session is the output mix, prefer an auxiliary effect,
3664 // otherwise no preference.
3665 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
3666 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003667 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07003668 if (lStatus < 0) {
3669 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
3670 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671 }
3672
3673 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07003674 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003675 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 lStatus = INVALID_OPERATION;
3677 goto Exit;
3678 }
3679
Eric Laurent59255e42011-07-27 19:49:51 -07003680 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003681 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08003682 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003683 !recordingAllowed(adjIdentity)) {
Eric Laurent59255e42011-07-27 19:49:51 -07003684 lStatus = PERMISSION_DENIED;
3685 goto Exit;
3686 }
3687
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003688 const bool hapticPlaybackRequired = EffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07003689 if (hapticPlaybackRequired
3690 && (sessionId == AUDIO_SESSION_DEVICE
3691 || sessionId == AUDIO_SESSION_OUTPUT_MIX
3692 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
3693 // haptic-generating effect is only valid when the session id is a general session id
3694 lStatus = INVALID_OPERATION;
3695 goto Exit;
3696 }
3697
Glenn Kasten142f5192014-03-25 17:44:59 -07003698 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003699 // if the output returned by getOutputForEffect() is removed before we lock the
3700 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
3701 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003702 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07003703 ALOGV("createEffect got output %d", io);
3704 }
3705
3706 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707
Eric Laurentb82e6b72019-11-22 17:25:04 -08003708 if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003709 sp<Client> client = registerPid(currentPid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003710 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Eric Laurentb82e6b72019-11-22 17:25:04 -08003711 handle = mDeviceEffectManager.createEffect_l(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003712 &descOut, device, client, effectClient, mPatchPanel.patches_l(),
3713 &enabledOut, &lStatus, probe);
Eric Laurentb82e6b72019-11-22 17:25:04 -08003714 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
3715 // remove local strong reference to Client with mClientLock held
3716 Mutex::Autolock _cl(mClientLock);
3717 client.clear();
3718 } else {
3719 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003720 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08003721 }
3722 goto Register;
3723 }
3724
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 // If output is not specified try to find a matching audio session ID in one of the
3726 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07003727 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
3728 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07003729 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
3730 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07003731 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07003732 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07003733 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
3734 if (io == AUDIO_IO_HANDLE_NONE) {
3735 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003737 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07003738 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003739 }
Andy Hung444bb552019-03-14 17:06:39 -07003740
3741 // If you wish to create a Record preprocessing AudioEffect in Java,
3742 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
3743 // Otherwise it will fail when created on a Playback thread by legacy
3744 // handling below. Ditto with Mmap, the associated Mmap track must be created
3745 // before creating the AudioEffect or the io handle must be specified.
3746 //
3747 // Detect if the effect is created after an AudioRecord is destroyed.
3748 if (getOrphanEffectChain_l(sessionId).get() != nullptr) {
3749 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003750 " for session %d no longer exists",
3751 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07003752 lStatus = PERMISSION_DENIED;
3753 goto Exit;
3754 }
3755
3756 // Legacy handling of creating an effect on an expired or made-up
3757 // session id. We think that it is a Playback effect.
3758 //
Eric Laurent84e9a102010-09-23 16:10:16 -07003759 // If no output thread contains the requested session ID, default to
3760 // first output. The effect chain will be moved to the correct output
3761 // thread when a track with the same session ID is created
Glenn Kasten142f5192014-03-25 17:44:59 -07003762 if (io == AUDIO_IO_HANDLE_NONE && mPlaybackThreads.size() > 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003763 io = mPlaybackThreads.keyAt(0);
3764 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003765 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Andy Hung1631f062019-03-12 19:39:03 -07003766 } else if (checkPlaybackThread_l(io) != nullptr) {
3767 // allow only one effect chain per sessionId on mPlaybackThreads.
3768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3769 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07003770 if (io == checkIo) {
3771 if (hapticPlaybackRequired
3772 && mPlaybackThreads.valueAt(i)
3773 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3774 ALOGE("%s: haptic playback thread is required while the required playback "
3775 "thread(io=%d) doesn't support", __func__, (int)io);
3776 lStatus = BAD_VALUE;
3777 goto Exit;
3778 }
3779 continue;
3780 }
Andy Hung1631f062019-03-12 19:39:03 -07003781 const uint32_t sessionType =
3782 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
3783 if ((sessionType & ThreadBase::EFFECT_SESSION) != 0) {
3784 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003785 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07003786 android_errorWriteLog(0x534e4554, "123237974");
3787 lStatus = BAD_VALUE;
3788 goto Exit;
3789 }
3790 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003791 }
3792 ThreadBase *thread = checkRecordThread_l(io);
3793 if (thread == NULL) {
3794 thread = checkPlaybackThread_l(io);
3795 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003796 thread = checkMmapThread_l(io);
3797 if (thread == NULL) {
3798 ALOGE("createEffect() unknown output thread");
3799 lStatus = BAD_VALUE;
3800 goto Exit;
3801 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003802 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003803 } else {
3804 // Check if one effect chain was awaiting for an effect to be created on this
3805 // session and used it instead of creating a new one.
Glenn Kastend848eb42016-03-08 13:42:11 -08003806 sp<EffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07003807 if (chain != 0) {
Eric Laurent1b928682014-10-02 19:41:47 -07003808 Mutex::Autolock _l(thread->mLock);
Eric Laurentaaa44472014-09-12 17:41:50 -07003809 thread->addEffectChain_l(chain);
3810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003811 }
Eric Laurent84e9a102010-09-23 16:10:16 -07003812
Philip P. Moltmannbda45752020-07-17 16:41:18 -07003813 sp<Client> client = registerPid(currentPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003815 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003816 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
jiabineb3bda02020-06-30 14:07:03 -07003817 ThreadBase *oriThread = nullptr;
3818 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
3819 ThreadBase *hapticThread = hapticPlaybackThread_l();
3820 if (hapticThread == nullptr) {
3821 ALOGE("%s haptic thread not found while it is required", __func__);
3822 lStatus = INVALID_OPERATION;
3823 goto Exit;
3824 }
3825 if (hapticThread != thread) {
3826 // Force to use haptic thread for haptic-generating effect.
3827 oriThread = thread;
3828 thread = hapticThread;
3829 }
3830 }
Eric Laurentde070132010-07-13 04:45:46 -07003831 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003832 &descOut, &enabledOut, &lStatus, pinned, probe);
haobo101735295ff7b0d2017-03-17 17:44:03 +08003833 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003834 // remove local strong reference to Client with mClientLock held
3835 Mutex::Autolock _cl(mClientLock);
3836 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08003837 } else {
3838 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003839 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07003840 // Invalidate audio session when haptic playback is created.
3841 if (hapticPlaybackRequired && oriThread != nullptr) {
3842 // invalidateTracksForAudioSession will trigger locking the thread.
3843 oriThread->invalidateTracksForAudioSession(sessionId);
3844 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07003845 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 }
3847
Eric Laurentb82e6b72019-11-22 17:25:04 -08003848Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07003849 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent6c796322019-04-09 14:13:17 -07003850 // Check CPU and memory usage
Eric Laurent41709552019-12-16 19:34:05 -08003851 sp<EffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07003852 if (effect != nullptr) {
3853 status_t rStatus = effect->updatePolicyState();
3854 if (rStatus != NO_ERROR) {
3855 lStatus = rStatus;
3856 }
3857 }
3858 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08003859 handle.clear();
3860 }
3861
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003862 response->id = idOut;
3863 response->enabled = enabledOut != 0;
3864 response->effect = handle;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003865 response->desc = VALUE_OR_RETURN_STATUS(
3866 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003867
Mathias Agopian65ab4712010-07-14 17:59:35 -07003868Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08003869 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870}
3871
Glenn Kastend848eb42016-03-08 13:42:11 -08003872status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003873 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07003874{
Steve Block3856b092011-10-20 11:56:00 +01003875 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07003876 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003877 Mutex::Autolock _l(mLock);
3878 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003879 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003880 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881 }
Eric Laurentde070132010-07-13 04:45:46 -07003882 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
3883 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003884 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003885 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 }
Eric Laurentde070132010-07-13 04:45:46 -07003887 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
3888 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003889 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07003890 return BAD_VALUE;
3891 }
3892
3893 Mutex::Autolock _dl(dstThread->mLock);
3894 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent6c796322019-04-09 14:13:17 -07003895 return moveEffectChain_l(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003896}
3897
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003898
3899void AudioFlinger::setEffectSuspended(int effectId,
3900 audio_session_t sessionId,
3901 bool suspended)
3902{
3903 Mutex::Autolock _l(mLock);
3904
3905 sp<ThreadBase> thread = getEffectThread_l(sessionId, effectId);
3906 if (thread == nullptr) {
3907 return;
3908 }
3909 Mutex::Autolock _sl(thread->mLock);
3910 sp<EffectModule> effect = thread->getEffect_l(sessionId, effectId);
3911 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
3912}
3913
3914
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003915// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Glenn Kastend848eb42016-03-08 13:42:11 -08003916status_t AudioFlinger::moveEffectChain_l(audio_session_t sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07003917 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent6c796322019-04-09 14:13:17 -07003918 AudioFlinger::PlaybackThread *dstThread)
Eric Laurentde070132010-07-13 04:45:46 -07003919{
Steve Block3856b092011-10-20 11:56:00 +01003920 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003921 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07003922
Eric Laurent59255e42011-07-27 19:49:51 -07003923 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07003924 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003925 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07003926 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07003927 return INVALID_OPERATION;
3928 }
3929
Eric Laurent4c415062016-06-17 16:14:16 -07003930 // Check whether the destination thread and all effects in the chain are compatible
3931 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung9a592762014-07-21 21:56:01 -07003932 ALOGW("moveEffectChain_l() effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07003933 " destination thread %p is not compatible with effects in the chain",
3934 dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07003935 return INVALID_OPERATION;
3936 }
3937
Eric Laurent39e94f82010-07-28 01:32:47 -07003938 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07003939 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07003940 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07003941 // removed.
3942 srcThread->removeEffectChain_l(chain);
3943
3944 // transfer all effects one by one so that new effect chain is created on new thread with
3945 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07003946 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003947 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07003948 sp<EffectModule> effect = chain->getEffectFromId_l(0);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003949 Vector< sp<EffectModule> > removed;
3950 status_t status = NO_ERROR;
Eric Laurentde070132010-07-13 04:45:46 -07003951 while (effect != 0) {
3952 srcThread->removeEffect_l(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003953 removed.add(effect);
3954 status = dstThread->addEffect_l(effect);
3955 if (status != NO_ERROR) {
3956 break;
3957 }
Eric Laurentec35a142011-10-05 17:42:25 -07003958 // removeEffect_l() has stopped the effect if it was active so it must be restarted
3959 if (effect->state() == EffectModule::ACTIVE ||
3960 effect->state() == EffectModule::STOPPING) {
3961 effect->start();
3962 }
Eric Laurent39e94f82010-07-28 01:32:47 -07003963 // if the move request is not received from audio policy manager, the effect must be
3964 // re-registered with the new strategy and output
3965 if (dstChain == 0) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003966 dstChain = effect->callback()->chain().promote();
Eric Laurent39e94f82010-07-28 01:32:47 -07003967 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003968 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07003969 status = NO_INIT;
3970 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07003971 }
3972 strategy = dstChain->strategy();
3973 }
Eric Laurentde070132010-07-13 04:45:46 -07003974 effect = chain->getEffectFromId_l(0);
3975 }
3976
Eric Laurent5baf2af2013-09-12 17:37:00 -07003977 if (status != NO_ERROR) {
3978 for (size_t i = 0; i < removed.size(); i++) {
3979 srcThread->addEffect_l(removed[i]);
Eric Laurent5baf2af2013-09-12 17:37:00 -07003980 }
3981 }
3982
3983 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984}
3985
Eric Laurent6c796322019-04-09 14:13:17 -07003986status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
3987 const sp<PlaybackThread>& dstThread,
3988 sp<PlaybackThread> *srcThread)
3989{
3990 status_t status = NO_ERROR;
3991 Mutex::Autolock _l(mLock);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07003992 sp<PlaybackThread> thread =
3993 static_cast<PlaybackThread *>(getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId).get());
Eric Laurent6c796322019-04-09 14:13:17 -07003994
3995 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
3996 Mutex::Autolock _dl(dstThread->mLock);
3997 Mutex::Autolock _sl(thread->mLock);
3998 sp<EffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3999 sp<EffectChain> dstChain;
4000 if (srcChain == 0) {
4001 return INVALID_OPERATION;
4002 }
4003
4004 sp<EffectModule> effect = srcChain->getEffectFromId_l(EffectId);
4005 if (effect == 0) {
4006 return INVALID_OPERATION;
4007 }
4008 thread->removeEffect_l(effect);
4009 status = dstThread->addEffect_l(effect);
4010 if (status != NO_ERROR) {
4011 thread->addEffect_l(effect);
4012 status = INVALID_OPERATION;
4013 goto Exit;
4014 }
4015
Eric Laurent6b446ce2019-12-13 10:56:31 -08004016 dstChain = effect->callback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004017 if (dstChain == 0) {
4018 thread->addEffect_l(effect);
4019 status = INVALID_OPERATION;
4020 }
4021
4022Exit:
4023 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4024 if (effect->state() == EffectModule::ACTIVE ||
4025 effect->state() == EffectModule::STOPPING) {
4026 effect->start();
4027 }
4028 }
4029
4030 if (status == NO_ERROR && srcThread != nullptr) {
4031 *srcThread = thread;
4032 }
4033 return status;
4034}
4035
Eric Laurent5baf2af2013-09-12 17:37:00 -07004036bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l()
Eric Laurent813e2a72013-08-31 12:59:48 -07004037{
4038 if (mGlobalEffectEnableTime != 0 &&
4039 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
4040 return true;
4041 }
4042
4043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4044 sp<EffectChain> ec =
4045 mPlaybackThreads.valueAt(i)->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004046 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004047 return true;
4048 }
4049 }
4050 return false;
4051}
4052
Eric Laurent5baf2af2013-09-12 17:37:00 -07004053void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07004054{
4055 Mutex::Autolock _l(mLock);
4056
4057 mGlobalEffectEnableTime = systemTime();
4058
4059 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4060 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
4061 if (t->mType == ThreadBase::OFFLOAD) {
4062 t->invalidateTracks(AUDIO_STREAM_MUSIC);
4063 }
4064 }
4065
4066}
4067
Eric Laurentaaa44472014-09-12 17:41:50 -07004068status_t AudioFlinger::putOrphanEffectChain_l(const sp<AudioFlinger::EffectChain>& chain)
4069{
Eric Laurentd8365c52017-07-16 15:27:05 -07004070 // clear possible suspended state before parking the chain so that it starts in default state
4071 // when attached to a new record thread
4072 chain->setEffectSuspended_l(FX_IID_AEC, false);
4073 chain->setEffectSuspended_l(FX_IID_NS, false);
4074
Glenn Kastend848eb42016-03-08 13:42:11 -08004075 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004076 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004077 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004078 if (index >= 0) {
4079 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
4080 return ALREADY_EXISTS;
4081 }
4082 mOrphanEffectChains.add(session, chain);
4083 return NO_ERROR;
4084}
4085
4086sp<AudioFlinger::EffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
4087{
4088 sp<EffectChain> chain;
4089 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004090 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004091 if (index >= 0) {
4092 chain = mOrphanEffectChains.valueAt(index);
4093 mOrphanEffectChains.removeItemsAt(index);
4094 }
4095 return chain;
4096}
4097
4098bool AudioFlinger::updateOrphanEffectChains(const sp<AudioFlinger::EffectModule>& effect)
4099{
4100 Mutex::Autolock _l(mLock);
Glenn Kastend848eb42016-03-08 13:42:11 -08004101 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004102 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004103 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004104 if (index >= 0) {
4105 sp<EffectChain> chain = mOrphanEffectChains.valueAt(index);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08004106 if (chain->removeEffect_l(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004107 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004108 mOrphanEffectChains.removeItemsAt(index);
4109 }
4110 return true;
4111 }
4112 return false;
4113}
4114
4115
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116// ----------------------------------------------------------------------------
4117
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004118status_t AudioFlinger::onTransactWrapper(TransactionCode code,
4119 const Parcel& data,
4120 uint32_t flags,
4121 const std::function<status_t()>& delegate) {
4122 (void) data;
4123 (void) flags;
4124
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004125 // make sure transactions reserved to AudioPolicyManager do not come from other processes
4126 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004127 case TransactionCode::SET_STREAM_VOLUME:
4128 case TransactionCode::SET_STREAM_MUTE:
4129 case TransactionCode::OPEN_OUTPUT:
4130 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
4131 case TransactionCode::CLOSE_OUTPUT:
4132 case TransactionCode::SUSPEND_OUTPUT:
4133 case TransactionCode::RESTORE_OUTPUT:
4134 case TransactionCode::OPEN_INPUT:
4135 case TransactionCode::CLOSE_INPUT:
4136 case TransactionCode::INVALIDATE_STREAM:
4137 case TransactionCode::SET_VOICE_VOLUME:
4138 case TransactionCode::MOVE_EFFECTS:
4139 case TransactionCode::SET_EFFECT_SUSPENDED:
4140 case TransactionCode::LOAD_HW_MODULE:
4141 case TransactionCode::GET_AUDIO_PORT:
4142 case TransactionCode::CREATE_AUDIO_PATCH:
4143 case TransactionCode::RELEASE_AUDIO_PATCH:
4144 case TransactionCode::LIST_AUDIO_PATCHES:
4145 case TransactionCode::SET_AUDIO_PORT_CONFIG:
4146 case TransactionCode::SET_RECORD_SILENCED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004147 ALOGW("%s: transaction %d received from PID %d",
4148 __func__, code, IPCThreadState::self()->getCallingPid());
4149 // return status only for non void methods
4150 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004151 case TransactionCode::SET_RECORD_SILENCED:
4152 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004153 break;
4154 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004155 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004156 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004157 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004158 return OK;
4159 default:
4160 break;
4161 }
4162
4163 // make sure the following transactions come from system components
4164 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004165 case TransactionCode::SET_MASTER_VOLUME:
4166 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08004167 case TransactionCode::MASTER_MUTE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004168 case TransactionCode::SET_MODE:
4169 case TransactionCode::SET_MIC_MUTE:
4170 case TransactionCode::SET_LOW_RAM_DEVICE:
4171 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00004172 case TransactionCode::SET_AUDIO_HAL_PIDS:
4173 case TransactionCode::SET_VIBRATOR_INFOS: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004174 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
4175 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
4176 __func__, code, IPCThreadState::self()->getCallingPid(),
4177 IPCThreadState::self()->getCallingUid());
4178 // return status only for non void methods
4179 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004180 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004181 break;
4182 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004183 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004184 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004185 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004186 return OK;
4187 }
4188 } break;
4189 default:
4190 break;
4191 }
4192
4193 // List of relevant events that trigger log merging.
4194 // Log merging should activate during audio activity of any kind. This are considered the
4195 // most relevant events.
4196 // TODO should select more wisely the items from the list
4197 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004198 case TransactionCode::CREATE_TRACK:
4199 case TransactionCode::CREATE_RECORD:
4200 case TransactionCode::SET_MASTER_VOLUME:
4201 case TransactionCode::SET_MASTER_MUTE:
4202 case TransactionCode::SET_MIC_MUTE:
4203 case TransactionCode::SET_PARAMETERS:
4204 case TransactionCode::CREATE_EFFECT:
4205 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004206 requestLogMerge();
4207 break;
4208 }
4209 default:
4210 break;
4211 }
4212
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08004213 std::string tag("IAudioFlinger command " +
4214 std::to_string(static_cast<std::underlying_type_t<TransactionCode>>(code)));
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08004215 TimeCheck check(tag.c_str());
4216
4217 // Make sure we connect to Audio Policy Service before calling into AudioFlinger:
4218 // - AudioFlinger can call into Audio Policy Service with its global mutex held
4219 // - If this is the first time Audio Policy Service is queried from inside audioserver process
4220 // this will trigger Audio Policy Manager initialization.
4221 // - Audio Policy Manager initialization calls into AudioFlinger which will try to lock
4222 // its global mutex and a deadlock will occur.
4223 if (IPCThreadState::self()->getCallingPid() != getpid()) {
4224 AudioSystem::get_audio_policy_service();
4225 }
4226
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07004227 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228}
4229
Glenn Kasten63238ef2015-03-02 15:50:29 -08004230} // namespace android