blob: c67fa134158a6cd2585c6e81624543f564ad1426 [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
Mathias Agopian65ab4712010-07-14 17:59:35 -070018#define LOG_TAG "AudioFlinger"
19//#define LOG_NDEBUG 0
Ming-Shin Lua6429b32024-09-15 14:22:34 +000020#define ATRACE_TAG ATRACE_TAG_AUDIO
21#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070022
jiabina392a552019-09-23 10:34:20 -070023// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
24#define AUDIO_ARRAYS_STATIC_CHECK 1
25
Glenn Kasten153b9fe2013-07-15 11:23:36 -070026#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070027#include "AudioFlinger.h"
Andy Hung9a57fc32023-07-19 18:02:19 -070028
Atneya Nairf94040f2024-10-07 16:00:49 -070029#include <afutils/FallibleLockGuard.h>
Ziyang Cheng4216c1a2023-11-02 00:17:15 +000030#include <afutils/NBAIO_Tee.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070031#include <afutils/Permission.h>
Andy Hungdcd74052023-06-15 18:52:23 -070032#include <afutils/PropertyUtils.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070033#include <afutils/TypedLogger.h>
Atneya Nair50ffdd12023-12-05 20:42:35 -080034#include <android-base/errors.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070035#include <android-base/stringprintf.h>
36#include <android/media/IAudioPolicyService.h>
37#include <audiomanager/IAudioManager.h>
38#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
40#include <binder/Parcel.h>
41#include <cutils/properties.h>
Atneya Nair5997a652024-06-14 17:24:45 -070042#include <com_android_media_audio.h>
Atneya Nair50ffdd12023-12-05 20:42:35 -080043#include <com_android_media_audioserver.h>
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -070044#include <media/AidlConversion.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070045#include <media/AudioParameter.h>
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -080046#include <media/AudioValidator.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070047#include <media/IMediaLogService.h>
Atneya Nair5997a652024-06-14 17:24:45 -070048#include <media/IPermissionProvider.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070049#include <media/MediaMetricsItem.h>
Atneya Nair5997a652024-06-14 17:24:45 -070050#include <media/NativePermissionController.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070051#include <media/TypeConverter.h>
Atneya Nair5997a652024-06-14 17:24:45 -070052#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080053#include <mediautils/BatteryNotifier.h>
Andy Hunge9eb03e2020-04-04 14:08:23 -070054#include <mediautils/MemoryLeakTrackUtil.h>
Andy Hungc747c532022-03-07 21:41:14 -080055#include <mediautils/MethodStatistics.h>
Andy Hungab7ef302018-05-15 19:35:29 -070056#include <mediautils/ServiceUtilities.h>
Eric Laurent42896a02019-09-27 15:40:33 -070057#include <mediautils/TimeCheck.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070058#include <memunreachable/memunreachable.h>
59// required for effect matching
60#include <system/audio_effects/effect_aec.h>
61#include <system/audio_effects/effect_ns.h>
62#include <system/audio_effects/effect_spatializer.h>
63#include <system/audio_effects/effect_visualizer.h>
64#include <utils/Log.h>
Glenn Kastenda6ef132013-01-10 12:31:01 -080065
Andy Hung9a57fc32023-07-19 18:02:19 -070066// not needed with the includes above, added to prevent transitive include dependency.
67#include <chrono>
68#include <thread>
Atneya Nairf94040f2024-10-07 16:00:49 -070069#include <string_view>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080070
Mathias Agopian65ab4712010-07-14 17:59:35 -070071// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
John Grossman1c345192012-03-27 14:00:17 -070073// Note: the following macro is used for extremely verbose logging message. In
74// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
75// 0; but one side effect of this is to turn all LOGV's as well. Some messages
76// are so verbose that we want to suppress them even when we have ALOG_ASSERT
77// turned on. Do not uncomment the #def below unless you really know what you
78// are doing and want to see all of the extremely verbose messages.
79//#define VERY_VERY_VERBOSE_LOGGING
80#ifdef VERY_VERY_VERBOSE_LOGGING
81#define ALOGVV ALOGV
82#else
83#define ALOGVV(a...) do { } while(0)
84#endif
Eric Laurentde070132010-07-13 04:45:46 -070085
Mathias Agopian65ab4712010-07-14 17:59:35 -070086namespace android {
87
Atneya Nairf94040f2024-10-07 16:00:49 -070088using namespace std::string_view_literals;
89
Andy Hung03410c02022-01-27 08:24:31 -080090using ::android::base::StringPrintf;
Atneya Nair5997a652024-06-14 17:24:45 -070091using aidl_utils::statusTFromBinderStatus;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -070092using media::IEffectClient;
jiabine99d0882021-09-17 05:21:25 +000093using media::audio::common::AudioMMapPolicyInfo;
94using media::audio::common::AudioMMapPolicyType;
Mikhail Naganovffd97712023-05-03 17:45:36 -070095using media::audio::common::AudioMode;
Svet Ganov33761132021-05-13 22:51:08 +000096using android::content::AttributionSourceState;
Shunkai Yao2b8fed42022-12-09 01:12:02 +000097using android::detail::AudioHalVersionInfo;
Atneya Nair5997a652024-06-14 17:24:45 -070098using com::android::media::permission::INativePermissionController;
99using com::android::media::permission::IPermissionProvider;
100using com::android::media::permission::NativePermissionController;
101using com::android::media::permission::ValidatedAttributionSourceState;
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000102
103static const AudioHalVersionInfo kMaxAAudioPropertyDeviceHalVersion =
104 AudioHalVersionInfo(AudioHalVersionInfo::Type::HIDL, 7, 1);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700105
Atneya Nairf94040f2024-10-07 16:00:49 -0700106constexpr auto kDeadlockedString = "AudioFlinger may be deadlocked\n"sv;
107constexpr auto kHardwareLockedString = "Hardware lock is taken\n"sv;
108constexpr auto kClientLockedString = "Client lock is taken\n"sv;
109constexpr auto kNoEffectsFactory = "Effects Factory is absent\n"sv;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
Vlad Popae8d99472022-06-30 16:02:48 +0200111static constexpr char kAudioServiceName[] = "audio";
Glenn Kasten58912562012-04-03 10:45:00 -0700112
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700113// Keep a strong reference to media.log service around forever.
114// The service is within our parent process so it can never die in a way that we could observe.
115// These two variables are const after initialization.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700116static sp<IMediaLogService> sMediaLogService;
117
118static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
119
120static void sMediaLogInit()
121{
Atneya Nairf94040f2024-10-07 16:00:49 -0700122 auto sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700123 if (sMediaLogServiceAsBinder != 0) {
124 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
125 }
126}
127
Atneya Nairf94040f2024-10-07 16:00:49 -0700128static int writeStr(int fd, std::string_view s) {
129 return write(fd, s.data(), s.size());
130}
131
132static int writeStr(int fd, const String8& s) {
133 return write(fd, s.c_str(), s.size());
134}
135
Atneya Nair5997a652024-06-14 17:24:45 -0700136static error::BinderResult<ValidatedAttributionSourceState>
137validateAttributionFromContextOrTrustedCaller(AttributionSourceState attr,
138 const IPermissionProvider& provider) {
139 const auto callingUid = IPCThreadState::self()->getCallingUid();
140 // We trust the following UIDs to appropriate validated identities above us
141 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
142 // Legacy paths may not properly populate package name, so we attempt to handle.
143 if (!attr.packageName.has_value() || attr.packageName.value() == "") {
144 ALOGW("Trusted client %d provided attr with missing package name" , callingUid);
145 attr.packageName = VALUE_OR_RETURN(provider.getPackagesForUid(callingUid))[0];
146 }
147 // Behavior change: In the case of delegation, if pid is invalid,
148 // filling it in with the callingPid will cause a mismatch between the
149 // pid and the uid in the attribution, which is error-prone.
150 // Instead, assert that the pid from a trusted source is valid
151 if (attr.pid == -1) {
152 if (callingUid != static_cast<uid_t>(attr.uid)) {
153 return error::unexpectedExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
154 "validateAttribution: Invalid pid from delegating trusted source");
155 } else {
156 // Legacy handling for trusted clients which may not fill pid correctly
157 attr.pid = IPCThreadState::self()->getCallingPid();
158 }
159 }
160 return ValidatedAttributionSourceState::createFromTrustedSource(std::move(attr));
161 } else {
162 // Behavior change: Populate pid with callingPid unconditionally. Previously, we
163 // allowed caller provided pid, if uid matched calling context, but this is error-prone
164 // since it allows mismatching uid/pid
165 return ValidatedAttributionSourceState::createFromBinderContext(std::move(attr), provider);
166 }
167}
168
169#define VALUE_OR_RETURN_CONVERTED(exp) \
170 ({ \
171 auto _tmp = (exp); \
172 if (!_tmp.ok()) { \
173 ALOGE("Function: %s Line: %d Failed result (%s)", __FUNCTION__, __LINE__, \
174 errorToString(_tmp.error()).c_str()); \
175 return statusTFromBinderStatus(_tmp.error()); \
176 } \
177 std::move(_tmp.value()); \
178 })
179
180
181
Andy Hungc747c532022-03-07 21:41:14 -0800182// Creates association between Binder code to name for IAudioFlinger.
183#define IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST \
184BINDER_METHOD_ENTRY(createTrack) \
185BINDER_METHOD_ENTRY(createRecord) \
186BINDER_METHOD_ENTRY(sampleRate) \
187BINDER_METHOD_ENTRY(format) \
188BINDER_METHOD_ENTRY(frameCount) \
189BINDER_METHOD_ENTRY(latency) \
190BINDER_METHOD_ENTRY(setMasterVolume) \
191BINDER_METHOD_ENTRY(setMasterMute) \
192BINDER_METHOD_ENTRY(masterVolume) \
193BINDER_METHOD_ENTRY(masterMute) \
194BINDER_METHOD_ENTRY(setStreamVolume) \
195BINDER_METHOD_ENTRY(setStreamMute) \
Andy Hung6b137d12024-08-27 22:35:17 +0000196BINDER_METHOD_ENTRY(setPortsVolume) \
Andy Hungc747c532022-03-07 21:41:14 -0800197BINDER_METHOD_ENTRY(setMode) \
198BINDER_METHOD_ENTRY(setMicMute) \
199BINDER_METHOD_ENTRY(getMicMute) \
200BINDER_METHOD_ENTRY(setRecordSilenced) \
201BINDER_METHOD_ENTRY(setParameters) \
202BINDER_METHOD_ENTRY(getParameters) \
203BINDER_METHOD_ENTRY(registerClient) \
204BINDER_METHOD_ENTRY(getInputBufferSize) \
205BINDER_METHOD_ENTRY(openOutput) \
206BINDER_METHOD_ENTRY(openDuplicateOutput) \
207BINDER_METHOD_ENTRY(closeOutput) \
208BINDER_METHOD_ENTRY(suspendOutput) \
209BINDER_METHOD_ENTRY(restoreOutput) \
210BINDER_METHOD_ENTRY(openInput) \
211BINDER_METHOD_ENTRY(closeInput) \
Andy Hungc747c532022-03-07 21:41:14 -0800212BINDER_METHOD_ENTRY(setVoiceVolume) \
213BINDER_METHOD_ENTRY(getRenderPosition) \
214BINDER_METHOD_ENTRY(getInputFramesLost) \
215BINDER_METHOD_ENTRY(newAudioUniqueId) \
216BINDER_METHOD_ENTRY(acquireAudioSessionId) \
217BINDER_METHOD_ENTRY(releaseAudioSessionId) \
218BINDER_METHOD_ENTRY(queryNumberEffects) \
219BINDER_METHOD_ENTRY(queryEffect) \
220BINDER_METHOD_ENTRY(getEffectDescriptor) \
221BINDER_METHOD_ENTRY(createEffect) \
222BINDER_METHOD_ENTRY(moveEffects) \
223BINDER_METHOD_ENTRY(loadHwModule) \
224BINDER_METHOD_ENTRY(getPrimaryOutputSamplingRate) \
225BINDER_METHOD_ENTRY(getPrimaryOutputFrameCount) \
226BINDER_METHOD_ENTRY(setLowRamDevice) \
227BINDER_METHOD_ENTRY(getAudioPort) \
228BINDER_METHOD_ENTRY(createAudioPatch) \
229BINDER_METHOD_ENTRY(releaseAudioPatch) \
230BINDER_METHOD_ENTRY(listAudioPatches) \
231BINDER_METHOD_ENTRY(setAudioPortConfig) \
232BINDER_METHOD_ENTRY(getAudioHwSyncForSession) \
233BINDER_METHOD_ENTRY(systemReady) \
234BINDER_METHOD_ENTRY(audioPolicyReady) \
235BINDER_METHOD_ENTRY(frameCountHAL) \
236BINDER_METHOD_ENTRY(getMicrophones) \
237BINDER_METHOD_ENTRY(setMasterBalance) \
238BINDER_METHOD_ENTRY(getMasterBalance) \
239BINDER_METHOD_ENTRY(setEffectSuspended) \
240BINDER_METHOD_ENTRY(setAudioHalPids) \
241BINDER_METHOD_ENTRY(setVibratorInfos) \
242BINDER_METHOD_ENTRY(updateSecondaryOutputs) \
243BINDER_METHOD_ENTRY(getMmapPolicyInfos) \
244BINDER_METHOD_ENTRY(getAAudioMixerBurstCount) \
245BINDER_METHOD_ENTRY(getAAudioHardwareBurstMinUsec) \
246BINDER_METHOD_ENTRY(setDeviceConnectedState) \
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700247BINDER_METHOD_ENTRY(setSimulateDeviceConnections) \
Eric Laurent076e7c72022-05-03 18:12:28 +0200248BINDER_METHOD_ENTRY(setRequestedLatencyMode) \
249BINDER_METHOD_ENTRY(getSupportedLatencyModes) \
Eric Laurent50d72582022-12-20 20:20:23 +0100250BINDER_METHOD_ENTRY(setBluetoothVariableLatencyEnabled) \
251BINDER_METHOD_ENTRY(isBluetoothVariableLatencyEnabled) \
252BINDER_METHOD_ENTRY(supportsBluetoothVariableLatency) \
Vlad Popae3fd1c22022-11-07 21:03:18 +0100253BINDER_METHOD_ENTRY(getSoundDoseInterface) \
Mikhail Naganovffd97712023-05-03 17:45:36 -0700254BINDER_METHOD_ENTRY(getAudioPolicyConfig) \
jiabin12537fc2023-10-12 17:56:08 +0000255BINDER_METHOD_ENTRY(getAudioMixPort) \
Shraddha Basantwania6dadac2024-06-06 16:28:52 +0000256BINDER_METHOD_ENTRY(resetReferencesForTest) \
Andy Hungc747c532022-03-07 21:41:14 -0800257
258// singleton for Binder Method Statistics for IAudioFlinger
259static auto& getIAudioFlingerStatistics() {
260 using Code = android::AudioFlingerServerAdapter::Delegate::TransactionCode;
261
262#pragma push_macro("BINDER_METHOD_ENTRY")
263#undef BINDER_METHOD_ENTRY
264#define BINDER_METHOD_ENTRY(ENTRY) \
265 {(Code)media::BnAudioFlingerService::TRANSACTION_##ENTRY, #ENTRY},
266
267 static mediautils::MethodStatistics<Code> methodStatistics{
268 IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST
269 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
270 };
271#pragma pop_macro("BINDER_METHOD_ENTRY")
272
273 return methodStatistics;
274}
275
Atneya Nair50ffdd12023-12-05 20:42:35 -0800276namespace base {
277template <typename T>
278struct OkOrFail<std::optional<T>> {
279 using opt_t = std::optional<T>;
280 OkOrFail() = delete;
281 OkOrFail(const opt_t&) = delete;
282
283 static bool IsOk(const opt_t& opt) { return opt.has_value(); }
284 static T Unwrap(opt_t&& opt) { return std::move(opt.value()); }
285 static std::string ErrorMessage(const opt_t&) { return "Empty optional"; }
286 static void Fail(opt_t&&) {}
287};
288}
289
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000290class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
291 public:
292 void onNewDevicesAvailable() override {
293 // Start a detached thread to execute notification in parallel.
294 // This is done to prevent mutual blocking of audio_flinger and
295 // audio_policy services during system initialization.
296 std::thread notifier([]() {
297 AudioSystem::onNewAudioModulesAvailable();
298 });
299 notifier.detach();
300 }
301};
302
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303// ----------------------------------------------------------------------------
304
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800305void AudioFlinger::instantiate() {
306 sp<IServiceManager> sm(defaultServiceManager());
307 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
308 new AudioFlingerServerAdapter(new AudioFlinger()), false,
309 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
310}
311
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312AudioFlinger::AudioFlinger()
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100314 // Move the audio session unique ID generator start base as time passes to limit risk of
315 // generating the same ID again after an audioserver restart.
316 // This is important because clients will reuse previously allocated audio session IDs
317 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
318 // active clients.
319 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
320 // between allocation ranges and not reaching wrap around too soon.
321 timespec ts{};
322 clock_gettime(CLOCK_MONOTONIC, &ts);
323 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
Eric Laurentf37f1982021-06-01 13:23:27 +0200324 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700325 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
326 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100327 mNextUniqueIds[use] =
Eric Laurentf37f1982021-06-01 13:23:27 +0200328 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
329 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700330 }
331
Eric Laurent94ca1142020-10-07 10:45:20 -0700332#if 1
333 // FIXME See bug 165702394 and bug 168511485
334 const bool doLog = false;
335#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800336 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700337#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800338 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800339 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
340 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700341 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800342 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700343
Wei Jia3f273d12015-11-24 09:06:49 -0800344 // reset battery stats.
345 // if the audio service has crashed, battery stats could be left
346 // in bad state, reset the state upon service start.
347 BatteryNotifier::getInstance().noteResetAudio();
348
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800349 mMediaLogNotifier->run("MediaLogNotifier");
Andy Hungb68f5eb2019-12-03 16:49:17 -0800350
351 // Notify that we have started (also called when audioserver service restarts)
352 mediametrics::LogItem(mMetricsId)
353 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
354 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700355}
356
357void AudioFlinger::onFirstRef()
358{
Andy Hung954b9712023-08-28 18:36:53 -0700359 audio_utils::lock_guard _l(mutex());
Eric Laurent93575202011-01-18 18:39:02 -0800360
Eric Laurenta4c5a552012-03-29 10:12:40 -0700361 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800362
Andy Hung6626a012021-01-12 13:38:00 -0800363 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Andy Hung692f0452023-07-17 13:45:55 -0700364 mDeviceEffectManager = sp<DeviceEffectManager>::make(
365 sp<IAfDeviceEffectManagerCallback>::fromExisting(this)),
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000366 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
367 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
jiabine504e7b2021-09-18 00:27:08 +0000368
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000369 if (mDevicesFactoryHal->getHalVersion() <= kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +0000370 mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty();
371 mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty();
372 }
Andy Hungb60a2c82023-07-17 14:02:52 -0700373
Andy Hung2dc61c42023-07-17 14:36:08 -0700374 mPatchPanel = IAfPatchPanel::create(sp<IAfPatchPanelCallback>::fromExisting(this));
Vlad Popa1c67ad62024-01-19 17:53:42 -0800375 mMelReporter = sp<MelReporter>::make(sp<IAfMelReporterCallback>::fromExisting(this),
376 mPatchPanel);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377}
378
Eric Laurent42896a02019-09-27 15:40:33 -0700379status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
Andy Hung5c6d68a2022-03-09 21:54:59 -0800380 mediautils::TimeCheck::setAudioHalPids(pids);
Eric Laurent42896a02019-09-27 15:40:33 -0700381 return NO_ERROR;
382}
383
jiabin1319f5a2021-03-30 22:21:24 +0000384status_t AudioFlinger::setVibratorInfos(
385 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
Andy Hung954b9712023-08-28 18:36:53 -0700386 audio_utils::lock_guard _l(mutex());
jiabin1319f5a2021-03-30 22:21:24 +0000387 mAudioVibratorInfos = vibratorInfos;
388 return NO_ERROR;
389}
390
jiabinf042b9b2021-05-07 23:46:28 +0000391status_t AudioFlinger::updateSecondaryOutputs(
392 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
Andy Hung954b9712023-08-28 18:36:53 -0700393 audio_utils::lock_guard _l(mutex());
jiabinf042b9b2021-05-07 23:46:28 +0000394 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
395 size_t i = 0;
396 for (; i < mPlaybackThreads.size(); ++i) {
Andy Hung87c693c2023-07-06 20:56:16 -0700397 IAfPlaybackThread* thread = mPlaybackThreads.valueAt(i).get();
Andy Hungc5007f82023-08-29 14:26:09 -0700398 audio_utils::lock_guard _tl(thread->mutex());
Andy Hungd29af632023-06-23 19:27:19 -0700399 sp<IAfTrack> track = thread->getTrackById_l(trackId);
jiabinf042b9b2021-05-07 23:46:28 +0000400 if (track != nullptr) {
401 ALOGD("%s trackId: %u", __func__, trackId);
402 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
403 break;
404 }
405 }
406 ALOGW_IF(i >= mPlaybackThreads.size(),
407 "%s cannot find track with id %u", __func__, trackId);
408 }
409 return NO_ERROR;
410}
411
Jiabin Huangebe64102021-09-07 20:01:07 +0000412status_t AudioFlinger::getMmapPolicyInfos(
jiabine99d0882021-09-17 05:21:25 +0000413 AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
Andy Hung954b9712023-08-28 18:36:53 -0700414 audio_utils::lock_guard _l(mutex());
Jiabin Huangebe64102021-09-07 20:01:07 +0000415 if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) {
416 *policyInfos = it->second;
417 return NO_ERROR;
418 }
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000419 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
Andy Hung954b9712023-08-28 18:36:53 -0700420 audio_utils::lock_guard lock(hardwareMutex());
Jiabin Huangebe64102021-09-07 20:01:07 +0000421 for (size_t i = 0; i < mAudioHwDevs.size(); ++i) {
422 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
jiabine99d0882021-09-17 05:21:25 +0000423 std::vector<AudioMMapPolicyInfo> infos;
Jiabin Huangebe64102021-09-07 20:01:07 +0000424 status_t status = dev->getMmapPolicyInfos(policyType, &infos);
425 if (status != NO_ERROR) {
426 ALOGE("Failed to query mmap policy info of %d, error %d",
427 mAudioHwDevs.keyAt(i), status);
428 continue;
429 }
430 policyInfos->insert(policyInfos->end(), infos.begin(), infos.end());
431 }
432 mPolicyInfos[policyType] = *policyInfos;
433 } else {
434 getMmapPolicyInfosFromSystemProperty(policyType, policyInfos);
435 mPolicyInfos[policyType] = *policyInfos;
436 }
437 return NO_ERROR;
438}
439
Andy Hungcdd80ef2023-07-17 11:37:26 -0700440int32_t AudioFlinger::getAAudioMixerBurstCount() const {
Andy Hung954b9712023-08-28 18:36:53 -0700441 audio_utils::lock_guard _l(mutex());
jiabine504e7b2021-09-18 00:27:08 +0000442 return mAAudioBurstsPerBuffer;
443}
444
Andy Hungcdd80ef2023-07-17 11:37:26 -0700445int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() const {
Andy Hung954b9712023-08-28 18:36:53 -0700446 audio_utils::lock_guard _l(mutex());
jiabine504e7b2021-09-18 00:27:08 +0000447 return mAAudioHwBurstMinMicros;
448}
449
jiabinc0048632023-04-27 22:04:31 +0000450status_t AudioFlinger::setDeviceConnectedState(const struct audio_port_v7 *port,
451 media::DeviceConnectedState state) {
Mikhail Naganov516d3982022-02-01 23:53:59 +0000452 status_t final_result = NO_INIT;
Andy Hung954b9712023-08-28 18:36:53 -0700453 audio_utils::lock_guard _l(mutex());
454 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganov516d3982022-02-01 23:53:59 +0000455 mHardwareStatus = AUDIO_HW_SET_CONNECTED_STATE;
456 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
457 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
jiabinc0048632023-04-27 22:04:31 +0000458 status_t result = state == media::DeviceConnectedState::PREPARE_TO_DISCONNECT
459 ? dev->prepareToDisconnectExternalDevice(port)
460 : dev->setConnectedState(port, state == media::DeviceConnectedState::CONNECTED);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000461 // Same logic as with setParameter: it's a success if at least one
462 // HAL module accepts the update.
463 if (final_result != NO_ERROR) {
464 final_result = result;
465 }
466 }
467 mHardwareStatus = AUDIO_HW_IDLE;
468 return final_result;
469}
470
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700471status_t AudioFlinger::setSimulateDeviceConnections(bool enabled) {
472 bool at_least_one_succeeded = false;
473 status_t last_error = INVALID_OPERATION;
Andy Hung954b9712023-08-28 18:36:53 -0700474 audio_utils::lock_guard _l(mutex());
475 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700476 mHardwareStatus = AUDIO_HW_SET_SIMULATE_CONNECTIONS;
477 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
478 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
479 status_t result = dev->setSimulateDeviceConnections(enabled);
480 if (result == OK) {
481 at_least_one_succeeded = true;
482 } else {
483 last_error = result;
484 }
485 }
486 mHardwareStatus = AUDIO_HW_IDLE;
487 return at_least_one_succeeded ? OK : last_error;
488}
489
jiabin1319f5a2021-03-30 22:21:24 +0000490// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
Andy Hung583043b2023-07-17 17:05:00 -0700491std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() const {
jiabin1319f5a2021-03-30 22:21:24 +0000492 if (mAudioVibratorInfos.empty()) {
Lais Andradebc3f37a2021-07-02 00:13:19 +0100493 return {};
jiabin1319f5a2021-03-30 22:21:24 +0000494 }
Lais Andradebc3f37a2021-07-02 00:13:19 +0100495 return mAudioVibratorInfos.front();
jiabin1319f5a2021-03-30 22:21:24 +0000496}
497
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498AudioFlinger::~AudioFlinger()
499{
500 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700501 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700502 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503 }
504 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700505 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700506 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700507 }
Andy Hungb4946b62019-03-14 11:19:28 -0700508 while (!mMmapThreads.isEmpty()) {
509 const audio_io_handle_t io = mMmapThreads.keyAt(0);
510 if (mMmapThreads.valueAt(0)->isOutput()) {
511 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
512 } else {
513 closeInput_nonvirtual(io); // removes entry from mMmapThreads
514 }
515 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700516
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800517 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Andy Hung954b9712023-08-28 18:36:53 -0700518 // no hardwareMutex() needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700519 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700521
522 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700523 if (sMediaLogService != 0) {
524 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
525 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
526 mUnregisteredWriters.pop();
527 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700528 }
529 }
Shraddha Basantwania6dadac2024-06-06 16:28:52 +0000530 mMediaLogNotifier->requestExit();
531 mPatchCommandThread->exit();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532}
533
Eric Laurentfc235202016-12-20 18:48:17 -0800534//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800535__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800536status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
537 const audio_attributes_t *attr,
538 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700539 const AudioClient& client,
Robert Wuaeb1d002024-10-30 23:19:44 +0000540 DeviceIdVector *deviceIds,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800541 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800542 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700543 sp<MmapStreamInterface>& interface,
544 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800545{
Andy Hung9a57fc32023-07-19 18:02:19 -0700546 // TODO(b/292281786): Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
Andy Hung6626a012021-01-12 13:38:00 -0800547 // This allows moving oboeservice (AAudio) to a separate process in the future.
548 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800549 status_t ret = NO_INIT;
550 if (af != 0) {
551 ret = af->openMmapStream(
Robert Wuaeb1d002024-10-30 23:19:44 +0000552 direction, attr, config, client, deviceIds,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800553 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800554 }
555 return ret;
556}
557
Eric Laurent6acd1d42017-01-04 14:23:29 -0800558status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
559 const audio_attributes_t *attr,
560 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700561 const AudioClient& client,
Robert Wuaeb1d002024-10-30 23:19:44 +0000562 DeviceIdVector *deviceIds,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800563 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800564 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700565 sp<MmapStreamInterface>& interface,
566 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800567{
568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800572 audio_session_t actualSessionId = *sessionId;
573 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
574 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
575 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800576 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700577 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800578 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700579 audio_attributes_t localAttr = *attr;
Eric Laurent9ff3e532022-11-10 16:04:44 +0100580
581 // TODO b/182392553: refactor or make clearer
Atneya Nair5997a652024-06-14 17:24:45 -0700582 AttributionSourceState adjAttributionSource;
583 if (!com::android::media::audio::audioserver_permissions()) {
584 pid_t clientPid =
585 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(client.attributionSource.pid));
586 bool updatePid = (clientPid == (pid_t)-1);
587 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent9ff3e532022-11-10 16:04:44 +0100588
Atneya Nair5997a652024-06-14 17:24:45 -0700589 adjAttributionSource = client.attributionSource;
590 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
591 uid_t clientUid =
592 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(client.attributionSource.uid));
593 ALOGW_IF(clientUid != callingUid,
594 "%s uid %d tried to pass itself off as %d",
595 __FUNCTION__, callingUid, clientUid);
596 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
597 legacy2aidl_uid_t_int32_t(callingUid));
598 updatePid = true;
599 }
600 if (updatePid) {
601 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
602 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
603 "%s uid %d pid %d tried to pass itself off as pid %d",
604 __func__, callingUid, callingPid, clientPid);
605 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
606 legacy2aidl_pid_t_int32_t(callingPid));
607 }
608 adjAttributionSource = afutils::checkAttributionSourcePackage(
Pechetty Sravani55532052024-06-14 03:30:13 +0000609 adjAttributionSource);
Atneya Nair5997a652024-06-14 17:24:45 -0700610 } else {
611 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
612 validateAttributionFromContextOrTrustedCaller(client.attributionSource,
613 getPermissionProvider()
614 ));
615 // TODO pass wrapped object around
616 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
617 }
Eric Laurent9ff3e532022-11-10 16:04:44 +0100618
Eric Laurent6acd1d42017-01-04 14:23:29 -0800619 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
620 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
621 fullConfig.sample_rate = config->sample_rate;
622 fullConfig.channel_mask = config->channel_mask;
623 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800624 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200625 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +0000626 bool isBitPerfect;
Andy Hung6b137d12024-08-27 22:35:17 +0000627 float volume;
Vlad Popa1e865e62024-08-15 19:11:42 -0700628 bool muted;
Eric Laurent42984412019-05-09 17:57:03 -0700629 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800630 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100631 &streamType, adjAttributionSource,
Ricardo Correa57a37692020-03-23 17:27:25 -0700632 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800633 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
634 AUDIO_OUTPUT_FLAG_DIRECT),
Robert Wuaeb1d002024-10-30 23:19:44 +0000635 deviceIds, &portId, &secondaryOutputs,
Robert Wufb971192024-10-30 21:54:35 +0000636 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +0000637 &isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -0700638 &volume,
639 &muted);
jiabinf1c73972022-04-14 16:28:52 -0700640 if (ret != NO_ERROR) {
641 config->sample_rate = fullConfig.sample_rate;
642 config->channel_mask = fullConfig.channel_mask;
643 config->format = fullConfig.format;
644 }
Kevin Rocard153f92d2018-12-18 18:33:28 -0800645 ALOGW_IF(!secondaryOutputs.empty(),
646 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800647 } else {
Robert Wuaeb1d002024-10-30 23:19:44 +0000648 audio_port_handle_t deviceId = getFirstDeviceId(*deviceIds);
Eric Laurent42984412019-05-09 17:57:03 -0700649 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700650 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800651 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100652 adjAttributionSource,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800653 config,
Robert Wuaeb1d002024-10-30 23:19:44 +0000654 AUDIO_INPUT_FLAG_MMAP_NOIRQ, &deviceId, &portId);
655 deviceIds->clear();
656 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
657 deviceIds->push_back(deviceId);
658 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800659 }
660 if (ret != NO_ERROR) {
661 return ret;
662 }
663
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700664 // use unique_lock as we may selectively unlock.
665 audio_utils::unique_lock l(mutex());
666
Eric Laurent6acd1d42017-01-04 14:23:29 -0800667 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
668 // audio policy manager and we can retrieve it
Andy Hung7aa7d102023-07-07 15:58:48 -0700669 const sp<IAfMmapThread> thread = mMmapThreads.valueFor(io);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800670 if (thread != 0) {
Andy Hung7aa7d102023-07-07 15:58:48 -0700671 interface = IAfMmapThread::createMmapStreamInterfaceAdapter(thread);
Robert Wuaeb1d002024-10-30 23:19:44 +0000672 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceIds, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700673 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800674 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800675 config->sample_rate = thread->sampleRate();
676 config->channel_mask = thread->channelMask();
677 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800678 } else {
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700679 l.unlock();
Eric Laurentad2e7b92017-09-14 20:06:42 -0700680 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700681 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700682 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800683 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700684 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800685 ret = NO_INIT;
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700686 // we don't reacquire the lock here as nothing left to do.
Eric Laurent6acd1d42017-01-04 14:23:29 -0800687 }
688
689 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
690
Eric Laurentfc235202016-12-20 18:48:17 -0800691 return ret;
692}
693
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700694status_t AudioFlinger::addEffectToHal(
695 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
Andy Hung954b9712023-08-28 18:36:53 -0700696 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700697 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800698 if (audioHwDevice == nullptr) {
699 return NO_INIT;
700 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700701 return audioHwDevice->hwDevice()->addDeviceEffect(device, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800702}
703
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700704status_t AudioFlinger::removeEffectFromHal(
705 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
Andy Hung954b9712023-08-28 18:36:53 -0700706 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700707 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800708 if (audioHwDevice == nullptr) {
709 return NO_INIT;
710 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700711 return audioHwDevice->hwDevice()->removeDeviceEffect(device, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800712}
713
Eric Laurenta4c5a552012-03-29 10:12:40 -0700714static const char * const audio_interfaces[] = {
715 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
716 AUDIO_HARDWARE_MODULE_ID_A2DP,
717 AUDIO_HARDWARE_MODULE_ID_USB,
718};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700719
Phil Burk062e67a2015-02-11 13:40:50 -0800720AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700721 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700722 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700723{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700724 // if module is 0, the request comes from an old policy manager and we should load
725 // well known modules
Andy Hung954b9712023-08-28 18:36:53 -0700726 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -0700727 if (module == 0) {
728 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700729 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700730 loadHwModule_ll(audio_interfaces[i]);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700731 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700732 // then try to find a module supporting the requested device.
733 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
734 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700735 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
736 uint32_t supportedDevices;
737 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700738 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700739 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700740 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700741 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700742 } else {
743 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700744 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
745 if (audioHwDevice != NULL) {
746 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700747 }
748 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700749
Dima Zavin799a70e2011-04-18 16:57:27 -0700750 return NULL;
751}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752
Atneya Nairf94040f2024-10-07 16:00:49 -0700753void AudioFlinger::dumpClients_ll(int fd, bool dumpAllocators) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 String8 result;
755
Atneya Nairf94040f2024-10-07 16:00:49 -0700756 if (dumpAllocators) {
757 result.append("Client Allocators:\n");
758 for (size_t i = 0; i < mClients.size(); ++i) {
759 sp<Client> client = mClients.valueAt(i).promote();
760 if (client != 0) {
761 result.appendFormat("Client: %d\n", client->pid());
762 result.append(client->allocator().dump().c_str());
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 }
Atneya Nairf94040f2024-10-07 16:00:49 -0700765 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700766
Eric Laurentd1b28d42013-09-18 18:47:13 -0700767 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800768 result.append(" pid uid name\n");
Andy Hung05b0ffe2024-08-30 17:18:37 -0700769 for (const auto& [ _, client ] : mNotificationClients) {
770 const uid_t uid = client->getUid();
Andy Hungb26a1c82024-08-30 11:54:40 -0700771 const std::shared_ptr<const mediautils::UidInfo::Info> info =
772 mediautils::UidInfo::getInfo(uid);
Andy Hung05b0ffe2024-08-30 17:18:37 -0700773 result.appendFormat("%6d %6u %s\n",
774 client->getPid(), uid, info->package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700775 }
776
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700777 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800778 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700779 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
780 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hungb26a1c82024-08-30 11:54:40 -0700781 const std::shared_ptr<const mediautils::UidInfo::Info> info =
782 mediautils::UidInfo::getInfo(r->mUid);
Andy Hung8b0bfd92019-12-23 13:11:11 -0800783 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
Andy Hungb26a1c82024-08-30 11:54:40 -0700784 r->mUid, info->package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700785 }
Atneya Nairf94040f2024-10-07 16:00:49 -0700786 writeStr(fd, result);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787}
788
789
Atneya Nairf94040f2024-10-07 16:00:49 -0700790void AudioFlinger::dumpInternals_l(int fd) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 const size_t SIZE = 256;
792 char buffer[SIZE];
793 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800794 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795
Andy Hung8fe87eb2023-07-20 21:31:38 -0700796 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 result.append(buffer);
Atneya Nairf94040f2024-10-07 16:00:49 -0700798 writeStr(fd, result);
jiabinc47acf22022-04-01 23:47:52 +0000799
800 dprintf(fd, "Vibrator infos(size=%zu):\n", mAudioVibratorInfos.size());
801 for (const auto& vibratorInfo : mAudioVibratorInfos) {
802 dprintf(fd, " - %s\n", vibratorInfo.toString().c_str());
803 }
Eric Laurent90cea102023-05-15 15:08:27 +0200804 dprintf(fd, "Bluetooth latency modes are %senabled\n",
805 mBluetoothLatencyModesEnabled ? "" : "not ");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806}
807
Atneya Nairf94040f2024-10-07 16:00:49 -0700808void AudioFlinger::dumpStats(int fd) {
809 // Dump binder stats
810 dprintf(fd, "\nIAudioFlinger binder call profile:\n");
811 writeStr(fd, getIAudioFlingerStatistics().dump());
812
813 extern mediautils::MethodStatistics<int>& getIEffectStatistics();
814 dprintf(fd, "\nIEffect binder call profile:\n");
815 writeStr(fd, getIEffectStatistics().dump());
816
817 // Automatically fetch HIDL or AIDL statistics.
818 const std::string_view halType = (mDevicesFactoryHal->getHalVersion().getType() ==
819 AudioHalVersionInfo::Type::HIDL)
820 ? METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL
821 : METHOD_STATISTICS_MODULE_NAME_AUDIO_AIDL;
822 const std::shared_ptr<std::vector<std::string>> halClassNames =
823 mediautils::getStatisticsClassesForModule(halType);
824 if (halClassNames) {
825 for (const auto& className : *halClassNames) {
826 auto stats = mediautils::getStatisticsForClass(className);
827 if (stats) {
828 dprintf(fd, "\n%s binder call profile:\n", className.c_str());
829 writeStr(fd, stats->dump());
830 }
831 }
832 }
833
834 dprintf(fd, "\nTimeCheck:\n");
835 writeStr(fd, mediautils::TimeCheck::toString());
836 dprintf(fd, "\n");
837 // dump mutex stats
838 writeStr(fd, audio_utils::mutex::all_stats_to_string());
839 // dump held mutexes
840 writeStr(fd, audio_utils::mutex::all_threads_to_string());
841
842}
843
844void AudioFlinger::dumpPermissionDenial(int fd) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 const size_t SIZE = 256;
846 char buffer[SIZE];
847 String8 result;
848 snprintf(buffer, SIZE, "Permission Denial: "
849 "can't dump AudioFlinger from pid=%d, uid=%d\n",
850 IPCThreadState::self()->getCallingPid(),
851 IPCThreadState::self()->getCallingUid());
852 result.append(buffer);
Atneya Nairf94040f2024-10-07 16:00:49 -0700853 writeStr(fd, result);
854}
855
856static void dump_printHelp(int fd) {
857 constexpr static auto helpStr =
858 "AudioFlinger dumpsys help options\n"
859 " -h/--help: Print this help text\n"
860 " --hal: Include dump of audio hal\n"
861 " --stats: Include call/lock/watchdog stats\n"
862 " --effects: Include effect definitions\n"
863 " --memory: Include memory dump\n"
864 " -a/--all: Print all except --memory\n"sv;
865
866 write(fd, helpStr.data(), helpStr.length());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867}
868
Mathias Agopian65ab4712010-07-14 17:59:35 -0700869status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
870{
Atneya Nairf94040f2024-10-07 16:00:49 -0700871 using afutils::FallibleLockGuard;
Glenn Kasten44deb052012-02-05 18:09:08 -0800872 if (!dumpAllowed()) {
Atneya Nairf94040f2024-10-07 16:00:49 -0700873 dumpPermissionDenial(fd);
874 return NO_ERROR;
875 }
876 // Arg parsing
877 struct {
878 bool shouldDumpMem, shouldDumpStats, shouldDumpHal, shouldDumpEffects;
879 } parsedArgs {}; // zero-init
880
881 for (const auto& arg : args) {
882 const String8 utf8arg{arg};
883 if (utf8arg == "-h" || utf8arg == "--help") {
884 dump_printHelp(fd);
885 return NO_ERROR;
886 }
887 if (utf8arg == "-a" || utf8arg == "--all") {
888 parsedArgs.shouldDumpStats = true;
889 parsedArgs.shouldDumpHal = true;
890 parsedArgs.shouldDumpEffects = true;
891 continue;
892 }
893 if (utf8arg == "--hal") {
894 parsedArgs.shouldDumpHal = true;
895 continue;
896 }
897 if (utf8arg == "--stats") {
898 parsedArgs.shouldDumpStats = true;
899 continue;
900 }
901 if (utf8arg == "--effects") {
902 parsedArgs.shouldDumpEffects = true;
903 continue;
904 }
905 if (utf8arg == "--memory") {
906 parsedArgs.shouldDumpMem = true;
907 continue;
908 }
909 // Unknown arg silently ignored
910 }
911
Atneya Nair970dc0d2024-10-08 21:57:17 -0700912 {
913 std::string res;
914 res.reserve(100);
915 res += "Start begin: ";
916 const auto startTimeStr = audio_utils_time_string_from_ns(mStartTime);
917 res += startTimeStr.time;
918 const auto startFinishedTime = getStartupFinishedTime();
919 if (startFinishedTime != 0) {
920 res += "\nStart end: ";
921 const auto startEndStr = audio_utils_time_string_from_ns(startFinishedTime);
922 res += startEndStr.time;
923 } else {
924 res += "\nStartup not yet finished!";
925 }
926 const auto nowTimeStr = audio_utils_time_string_from_ns(audio_utils_get_real_time_ns());
927 res += "\nNow: ";
928 res += nowTimeStr.time;
929 res += "\n";
930 writeStr(fd, res);
931 }
Atneya Nairf94040f2024-10-07 16:00:49 -0700932 // get state of hardware lock
933 {
934 FallibleLockGuard l{hardwareMutex()};
935 if (!l) writeStr(fd, kHardwareLockedString);
936 }
937 {
938 FallibleLockGuard l{mutex()};
939 if (!l) writeStr(fd, kDeadlockedString);
940 {
941 FallibleLockGuard ll{clientMutex()};
942 if (!ll) writeStr(fd, kClientLockedString);
943 dumpClients_ll(fd, parsedArgs.shouldDumpMem);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945
Atneya Nairf94040f2024-10-07 16:00:49 -0700946 dumpInternals_l(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947
Atneya Nairf94040f2024-10-07 16:00:49 -0700948 dprintf(fd, "\n ## BEGIN thread dump \n");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 // dump playback threads
950 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
951 mPlaybackThreads.valueAt(i)->dump(fd, args);
952 }
953
954 // dump record threads
955 for (size_t i = 0; i < mRecordThreads.size(); i++) {
956 mRecordThreads.valueAt(i)->dump(fd, args);
957 }
958
Eric Laurent6acd1d42017-01-04 14:23:29 -0800959 // dump mmap threads
960 for (size_t i = 0; i < mMmapThreads.size(); i++) {
961 mMmapThreads.valueAt(i)->dump(fd, args);
962 }
963
Eric Laurentaaa44472014-09-12 17:41:50 -0700964 // dump orphan effect chains
965 if (mOrphanEffectChains.size() != 0) {
Atneya Nairf94040f2024-10-07 16:00:49 -0700966 writeStr(fd, " Orphan Effect Chains\n");
Eric Laurentaaa44472014-09-12 17:41:50 -0700967 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
968 mOrphanEffectChains.valueAt(i)->dump(fd, args);
969 }
970 }
Atneya Nairf94040f2024-10-07 16:00:49 -0700971 // dump historical threads in the last 10 seconds
972 writeStr(fd, mThreadLog.dumpToString(
973 "Historical Thread Log ", 0 /* lines */,
974 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND));
Vlad Popab042ee62022-10-20 18:05:00 +0200975
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700976 // dump external setParameters
Atneya Nairf94040f2024-10-07 16:00:49 -0700977 dprintf(fd, "\n ## BEGIN setParameters dump \n");
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700978 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
Atneya Nairf94040f2024-10-07 16:00:49 -0700979 dprintf(fd, "\n %s setParameters:\n", name);
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700980 logger.dump(fd, " " /* prefix */);
981 };
982 dumpLogger(mRejectedSetParameterLog, "Rejected");
983 dumpLogger(mAppSetParameterLog, "App");
984 dumpLogger(mSystemSetParameterLog, "System");
985
Andy Hunga8115dc2018-08-24 15:51:59 -0700986
Atneya Nairf94040f2024-10-07 16:00:49 -0700987 dprintf(fd, "\n ## BEGIN misc af dump \n");
988 mPatchPanel->dump(fd);
989 mDeviceEffectManager->dump(fd);
990 writeStr(fd, mMelReporter->dump());
rago3bd1c872016-09-26 12:58:14 -0700991
Andy Hung88a7afe2024-08-12 20:00:46 -0700992 if (media::psh_utils::AudioPowerManager::enabled()) {
993 char value[PROPERTY_VALUE_MAX];
994 property_get("ro.build.display.id", value, "Unknown build");
995 std::string build(value);
Atneya Nairf94040f2024-10-07 16:00:49 -0700996 writeStr(fd, build + "\n");
997 writeStr(fd, media::psh_utils::AudioPowerManager::getAudioPowerManager().toString());
Andy Hung88a7afe2024-08-12 20:00:46 -0700998 }
999
Atneya Nairf94040f2024-10-07 16:00:49 -07001000 if (parsedArgs.shouldDumpEffects) {
1001 dprintf(fd, "\n ## BEGIN effects dump \n");
1002 if (mEffectsFactoryHal != 0) {
1003 mEffectsFactoryHal->dumpEffects(fd);
1004 } else {
1005 writeStr(fd, kNoEffectsFactory);
Andy Hung35fec5f2016-04-13 14:21:48 -07001006 }
1007 }
1008
Atneya Nairf94040f2024-10-07 16:00:49 -07001009 if (parsedArgs.shouldDumpHal) {
1010 dprintf(fd, "\n ## BEGIN HAL dump \n");
1011 FallibleLockGuard ll{hardwareMutex()};
1012 // dump all hardware devs
1013 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1014 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1015 dev->dump(fd, args);
Andy Hung224f82f2022-03-22 00:00:49 -07001016 }
Andy Hungc747c532022-03-07 21:41:14 -08001017 }
Atneya Nairf94040f2024-10-07 16:00:49 -07001018 } // end af lock
Andy Hungc6877d62023-10-17 18:43:12 -07001019
Atneya Nairf94040f2024-10-07 16:00:49 -07001020 if (parsedArgs.shouldDumpStats) {
1021 dprintf(fd, "\n ## BEGIN stats dump \n");
1022 dumpStats(fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 }
Atneya Nairf94040f2024-10-07 16:00:49 -07001024
1025 if (parsedArgs.shouldDumpMem) {
1026 dprintf(fd, "\n ## BEGIN memory dump \n");
1027 writeStr(fd, dumpMemoryAddresses(100 /* limit */));
1028 dprintf(fd, "\nDumping unreachable memory:\n");
1029 // TODO - should limit be an argument parameter?
1030 writeStr(fd, GetUnreachableMemoryString(true /* contents */, 100 /* limit */));
1031 }
1032
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 return NO_ERROR;
1034}
1035
Atneya Nairb01390f2024-10-09 23:33:27 +00001036sp<Client> AudioFlinger::registerClient(pid_t pid, uid_t uid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -08001037{
Andy Hung954b9712023-08-28 18:36:53 -07001038 audio_utils::lock_guard _cl(clientMutex());
Glenn Kasten98ec94c2012-01-25 14:28:29 -08001039 // If pid is already in the mClients wp<> map, then use that entry
1040 // (for which promote() is always != 0), otherwise create a new entry and Client.
1041 sp<Client> client = mClients.valueFor(pid).promote();
1042 if (client == 0) {
Atneya Nairb01390f2024-10-09 23:33:27 +00001043 client = sp<Client>::make(sp<IAfClientCallback>::fromExisting(this), pid, uid);
Glenn Kasten98ec94c2012-01-25 14:28:29 -08001044 mClients.add(pid, client);
1045 }
1046
1047 return client;
1048}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049
Glenn Kasten9e58b552013-01-18 15:09:48 -08001050sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
1051{
Jiabin Huang60766082020-07-28 22:03:56 +00001052 // If there is no memory allocated for logs, return a no-op writer that does nothing.
1053 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001054 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -08001055 return new NBLog::Writer();
1056 }
Glenn Kasten481fb672013-09-30 14:39:28 -07001057 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1058 // If allocation fails, consult the vector of previously unregistered writers
1059 // and garbage-collect one or more them until an allocation succeeds
1060 if (shared == 0) {
Andy Hung954b9712023-08-28 18:36:53 -07001061 audio_utils::lock_guard _l(unregisteredWritersMutex());
Glenn Kasten481fb672013-09-30 14:39:28 -07001062 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
1063 {
1064 // Pick the oldest stale writer to garbage-collect
1065 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
1066 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001067 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -07001068 // Now the media.log remote reference to IMemory is gone. When our last local
1069 // reference to IMemory also drops to zero at end of this block,
1070 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
1071 }
1072 // Re-attempt the allocation
1073 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1074 if (shared != 0) {
1075 goto success;
1076 }
1077 }
1078 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +00001079 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -07001080 return new NBLog::Writer();
1081 }
1082success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001083 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -08001084 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
1085 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001086 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -08001087 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001088}
1089
1090void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
1091{
Glenn Kasten685ef092013-02-04 08:15:34 -08001092 if (writer == 0) {
1093 return;
1094 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08001095 sp<IMemory> iMemory(writer->getIMemory());
1096 if (iMemory == 0) {
1097 return;
1098 }
Glenn Kasten481fb672013-09-30 14:39:28 -07001099 // Rather than removing the writer immediately, append it to a queue of old writers to
1100 // be garbage-collected later. This allows us to continue to view old logs for a while.
Andy Hung954b9712023-08-28 18:36:53 -07001101 audio_utils::lock_guard _l(unregisteredWritersMutex());
Glenn Kasten481fb672013-09-30 14:39:28 -07001102 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001103}
1104
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105// IAudioFlinger interface
1106
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001107status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
1108 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109{
Ming-Shin Lua6429b32024-09-15 14:22:34 +00001110 ATRACE_CALL();
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001111 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08001112 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001113 CreateTrackOutput output;
1114
Andy Hungd29af632023-06-23 19:27:19 -07001115 sp<IAfTrack> track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -08001118 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -08001119 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001120 std::vector<audio_io_handle_t> secondaryOutputs;
jiabinc658e452022-10-21 20:52:21 +00001121 bool isSpatialized = false;
1122 bool isBitPerfect = false;
Andy Hung6b137d12024-08-27 22:35:17 +00001123 float volume;
Vlad Popa1e865e62024-08-15 19:11:42 -07001124 bool muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125
Eric Laurent6c796322019-04-09 14:13:17 -07001126 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
1127 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -07001128 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -07001129
Atneya Nair5997a652024-06-14 17:24:45 -07001130 AttributionSourceState adjAttributionSource;
1131 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1132 if (!com::android::media::audio::audioserver_permissions()) {
1133 adjAttributionSource = input.clientInfo.attributionSource;
1134 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1135 uid_t clientUid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(
1136 input.clientInfo.attributionSource.uid));
1137 pid_t clientPid =
1138 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
1139 input.clientInfo.attributionSource.pid));
1140 bool updatePid = (clientPid == (pid_t)-1);
1141
1142 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
1143 ALOGW_IF(clientUid != callingUid,
1144 "%s uid %d tried to pass itself off as %d",
1145 __FUNCTION__, callingUid, clientUid);
1146 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
1147 legacy2aidl_uid_t_int32_t(callingUid));
1148 clientUid = callingUid;
1149 updatePid = true;
1150 }
1151 if (updatePid) {
1152 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
1153 "%s uid %d pid %d tried to pass itself off as pid %d",
1154 __func__, callingUid, callingPid, clientPid);
1155 clientPid = callingPid;
1156 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
1157 legacy2aidl_pid_t_int32_t(callingPid));
1158 }
1159 adjAttributionSource = afutils::checkAttributionSourcePackage(
1160 adjAttributionSource);
1161
1162 } else {
1163 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
1164 validateAttributionFromContextOrTrustedCaller(input.clientInfo.attributionSource,
1165 getPermissionProvider()
1166 ));
1167 // TODO pass wrapped object around
1168 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
Eric Laurent21da6472017-11-09 16:29:26 -08001169 }
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001170
Robert Wufb971192024-10-30 21:54:35 +00001171 DeviceIdVector selectedDeviceIds;
Eric Laurent21da6472017-11-09 16:29:26 -08001172 audio_session_t sessionId = input.sessionId;
1173 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1174 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001175 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1176 lStatus = BAD_VALUE;
1177 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -08001178 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001179
Eric Laurent21da6472017-11-09 16:29:26 -08001180 output.sessionId = sessionId;
1181 output.outputId = AUDIO_IO_HANDLE_NONE;
Robert Wufb971192024-10-30 21:54:35 +00001182 if (input.selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1183 selectedDeviceIds.push_back(input.selectedDeviceId);
1184 }
Eric Laurent42984412019-05-09 17:57:03 -07001185 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Svet Ganov33761132021-05-13 22:51:08 +00001186 adjAttributionSource, &input.config, input.flags,
Robert Wufb971192024-10-30 21:54:35 +00001187 &selectedDeviceIds, &portId, &secondaryOutputs,
Vlad Popa1e865e62024-08-15 19:11:42 -07001188 &isSpatialized, &isBitPerfect, &volume, &muted);
Robert Wub7f8edc2024-11-04 19:54:38 +00001189 output.selectedDeviceIds = selectedDeviceIds;
Eric Laurent21da6472017-11-09 16:29:26 -08001190
1191 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1192 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
1193 goto Exit;
1194 }
Glenn Kasten263709e2012-01-06 08:40:01 -08001195 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
1196 // but if someone uses binder directly they could bypass that and cause us to crash
1197 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001198 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
1202
Glenn Kasten53b5d092014-02-05 10:00:23 -08001203 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001204 if (!audio_is_output_channel(input.config.channel_mask)) {
1205 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001206 lStatus = BAD_VALUE;
1207 goto Exit;
1208 }
1209
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001210 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001211 if (!audio_is_valid_format(input.config.format)) {
1212 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -07001213 lStatus = BAD_VALUE;
1214 goto Exit;
1215 }
1216
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 {
Andy Hung954b9712023-08-28 18:36:53 -07001218 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001219 IAfPlaybackThread* thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -08001221 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 lStatus = BAD_VALUE;
1223 goto Exit;
1224 }
1225
Atneya Nairb01390f2024-10-09 23:33:27 +00001226 client = registerClient(adjAttributionSource.pid, adjAttributionSource.uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227
Andy Hung87c693c2023-07-06 20:56:16 -07001228 IAfPlaybackThread* effectThread = nullptr;
Shunkai Yao29d10572024-03-19 04:31:47 +00001229 sp<IAfEffectChain> effectChain = nullptr;
Eric Laurent21da6472017-11-09 16:29:26 -08001230 // check if an effect chain with the same session ID is present on another
1231 // output thread and move it here.
1232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07001233 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
Eric Laurent21da6472017-11-09 16:29:26 -08001234 if (mPlaybackThreads.keyAt(i) != output.outputId) {
1235 uint32_t sessions = t->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07001236 if (sessions & IAfThreadBase::EFFECT_SESSION) {
Eric Laurent21da6472017-11-09 16:29:26 -08001237 effectThread = t.get();
1238 break;
Eric Laurentde070132010-07-13 04:45:46 -07001239 }
1240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 }
Shunkai Yao29d10572024-03-19 04:31:47 +00001242 // Check if an orphan effect chain exists for this session
1243 if (effectThread == nullptr) {
1244 effectChain = getOrphanEffectChain_l(sessionId);
1245 }
Vlad Popa1e865e62024-08-15 19:11:42 -07001246 ALOGV("createTrack() sessionId: %d volume: %f muted %d", sessionId, volume, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247
Eric Laurent21da6472017-11-09 16:29:26 -08001248 output.sampleRate = input.config.sample_rate;
1249 output.frameCount = input.frameCount;
1250 output.notificationFrameCount = input.notificationFrameCount;
1251 output.flags = input.flags;
Andy Hunga2159aa2021-07-20 13:01:52 -07001252 output.streamType = streamType;
Eric Laurent21da6472017-11-09 16:29:26 -08001253
Eric Laurent42984412019-05-09 17:57:03 -07001254 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001255 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -08001256 &output.frameCount, &output.notificationFrameCount,
1257 input.notificationsPerBuffer, input.speed,
1258 input.sharedBuffer, sessionId, &output.flags,
Svet Ganov33761132021-05-13 22:51:08 +00001259 callingPid, adjAttributionSource, input.clientInfo.clientTid,
jiabinc658e452022-10-21 20:52:21 +00001260 &lStatus, portId, input.audioTrackCallback, isSpatialized,
Vlad Popa1e865e62024-08-15 19:11:42 -07001261 isBitPerfect, &output.afTrackFlags, volume, muted);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001262 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -07001263 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -07001264
Eric Laurent21da6472017-11-09 16:29:26 -08001265 output.afFrameCount = thread->frameCount();
1266 output.afSampleRate = thread->sampleRate();
Robert Wu310037a2022-09-06 21:48:18 +00001267 output.afChannelMask = static_cast<audio_channel_mask_t>(thread->channelMask() |
1268 thread->hapticChannelMask());
1269 output.afFormat = thread->format();
Eric Laurent21da6472017-11-09 16:29:26 -08001270 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -08001271 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -08001272
Kevin Rocard153f92d2018-12-18 18:33:28 -08001273 if (lStatus == NO_ERROR) {
Andy Hung954b9712023-08-28 18:36:53 -07001274 // no risk of deadlock because AudioFlinger::mutex() is held
Andy Hungc5007f82023-08-29 14:26:09 -07001275 audio_utils::lock_guard _dl(thread->mutex());
Kevin Rocard153f92d2018-12-18 18:33:28 -08001276 // Connect secondary outputs. Failure on a secondary output must not imped the primary
1277 // Any secondary output setup failure will lead to a desync between the AP and AF until
1278 // the track is destroyed.
jiabinf042b9b2021-05-07 23:46:28 +00001279 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
jiabin87991352023-04-25 20:59:55 +00001280 // move effect chain to this output thread if an effect on same session was waiting
1281 // for a track to be created
1282 if (effectThread != nullptr) {
Andy Hung972bec12023-08-31 16:13:39 -07001283 // No thread safety analysis: double lock on a thread capability.
1284 audio_utils::lock_guard_no_thread_safety_analysis _sl(effectThread->mutex());
1285 if (moveEffectChain_ll(sessionId, effectThread, thread) == NO_ERROR) {
jiabin87991352023-04-25 20:59:55 +00001286 effectThreadId = thread->id();
1287 effectIds = thread->getEffectIds_l(sessionId);
1288 }
Eric Laurent6c796322019-04-09 14:13:17 -07001289 }
Shunkai Yao29d10572024-03-19 04:31:47 +00001290 if (effectChain != nullptr) {
1291 if (moveEffectChain_ll(sessionId, nullptr, thread, effectChain.get())
1292 == NO_ERROR) {
1293 effectThreadId = thread->id();
1294 effectIds = thread->getEffectIds_l(sessionId);
1295 }
1296 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001297 }
Eric Laurenta011e352012-03-29 15:51:43 -07001298
1299 // Look for sync events awaiting for a session to be used.
Andy Hung068e08e2023-05-15 19:02:55 -07001300 for (auto it = mPendingSyncEvents.begin(); it != mPendingSyncEvents.end();) {
1301 if ((*it)->triggerSession() == sessionId) {
1302 if (thread->isValidSyncEvent(*it)) {
Eric Laurent29864602012-05-08 18:57:51 -07001303 if (lStatus == NO_ERROR) {
Andy Hung068e08e2023-05-15 19:02:55 -07001304 (void) track->setSyncEvent(*it);
Eric Laurent29864602012-05-08 18:57:51 -07001305 } else {
Andy Hung068e08e2023-05-15 19:02:55 -07001306 (*it)->cancel();
Eric Laurent29864602012-05-08 18:57:51 -07001307 }
Andy Hung068e08e2023-05-15 19:02:55 -07001308 it = mPendingSyncEvents.erase(it);
1309 continue;
Eric Laurenta011e352012-03-29 15:51:43 -07001310 }
1311 }
Andy Hung068e08e2023-05-15 19:02:55 -07001312 ++it;
Eric Laurenta011e352012-03-29 15:51:43 -07001313 }
Andy Hung6eff0ff2021-07-30 19:01:48 -07001314 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1315 setAudioHwSyncForSession_l(thread, sessionId);
1316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 }
Glenn Kastene198c362013-08-13 09:13:36 -07001318
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001319 if (lStatus != NO_ERROR) {
1320 // remove local strong reference to Client before deleting the Track so that the
Andy Hung954b9712023-08-28 18:36:53 -07001321 // Client destructor is called by the TrackBase destructor with clientMutex() held
1322 // Don't hold clientMutex() when releasing the reference on the track as the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001323 // destructor will acquire it.
1324 {
Andy Hung954b9712023-08-28 18:36:53 -07001325 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001326 client.clear();
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001329 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330 }
1331
Eric Laurent6c796322019-04-09 14:13:17 -07001332 // effectThreadId is not NONE if an effect chain corresponding to the track session
1333 // was found on another thread and must be moved on this thread
1334 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1335 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1336 }
1337
Andy Hungd29af632023-06-23 19:27:19 -07001338 output.audioTrack = IAfTrack::createIAudioTrackAdapter(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001339 _output = VALUE_OR_FATAL(output.toAidl());
1340
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001342 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001343 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001344 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001345 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001346}
1347
Glenn Kasten2c073da2016-02-26 09:14:08 -08001348uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001349{
Andy Hung954b9712023-08-28 18:36:53 -07001350 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001351 IAfThreadBase* const thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001352 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001353 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 return 0;
1355 }
1356 return thread->sampleRate();
1357}
1358
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001359audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360{
Andy Hung954b9712023-08-28 18:36:53 -07001361 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001362 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001364 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001365 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366 }
1367 return thread->format();
1368}
1369
Glenn Kasten2c073da2016-02-26 09:14:08 -08001370size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371{
Andy Hung954b9712023-08-28 18:36:53 -07001372 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001373 IAfThreadBase* const thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001375 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001376 return 0;
1377 }
Glenn Kasten58912562012-04-03 10:45:00 -07001378 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1379 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 return thread->frameCount();
1381}
1382
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001383size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1384{
Andy Hung954b9712023-08-28 18:36:53 -07001385 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001386 IAfThreadBase* const thread = checkThread_l(ioHandle);
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001387 if (thread == NULL) {
1388 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1389 return 0;
1390 }
1391 return thread->frameCountHAL();
1392}
1393
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001394uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395{
Andy Hung954b9712023-08-28 18:36:53 -07001396 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001397 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001399 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400 return 0;
1401 }
1402 return thread->latency();
1403}
1404
1405status_t AudioFlinger::setMasterVolume(float value)
1406{
Eric Laurenta1884f92011-08-23 08:25:03 -07001407 status_t ret = initCheck();
1408 if (ret != NO_ERROR) {
1409 return ret;
1410 }
1411
Mathias Agopian65ab4712010-07-14 17:59:35 -07001412 // check calling permissions
1413 if (!settingsAllowed()) {
1414 return PERMISSION_DENIED;
1415 }
1416
Andy Hung954b9712023-08-28 18:36:53 -07001417 audio_utils::lock_guard _l(mutex());
John Grossmanee578c02012-07-23 17:05:46 -07001418 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001419
John Grossmanee578c02012-07-23 17:05:46 -07001420 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001421 {
Andy Hung954b9712023-08-28 18:36:53 -07001422 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001423 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1424 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001425
Eric Laurent00abf0d2020-04-22 19:28:22 -07001426 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1427 if (dev->canSetMasterVolume()) {
1428 dev->hwDevice()->setMasterVolume(value);
1429 }
1430 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001431 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 }
John Grossmanee578c02012-07-23 17:05:46 -07001433 // Now set the master volume in each playback thread. Playback threads
1434 // assigned to HALs which do not have master volume support will apply
1435 // master volume during the mix operation. Threads with HALs which do
1436 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001437 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1438 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1439 continue;
1440 }
John Grossmanee578c02012-07-23 17:05:46 -07001441 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443
1444 return NO_ERROR;
1445}
1446
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001447status_t AudioFlinger::setMasterBalance(float balance)
1448{
1449 status_t ret = initCheck();
1450 if (ret != NO_ERROR) {
1451 return ret;
1452 }
1453
1454 // check calling permissions
1455 if (!settingsAllowed()) {
1456 return PERMISSION_DENIED;
1457 }
1458
1459 // check range
1460 if (isnan(balance) || fabs(balance) > 1.f) {
1461 return BAD_VALUE;
1462 }
1463
Andy Hung954b9712023-08-28 18:36:53 -07001464 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001465
1466 // short cut.
1467 if (mMasterBalance == balance) return NO_ERROR;
1468
1469 mMasterBalance = balance;
1470
1471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1472 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1473 continue;
1474 }
1475 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1476 }
1477
1478 return NO_ERROR;
1479}
1480
Glenn Kastenf78aee72012-01-04 11:00:47 -08001481status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482{
Eric Laurenta1884f92011-08-23 08:25:03 -07001483 status_t ret = initCheck();
1484 if (ret != NO_ERROR) {
1485 return ret;
1486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487
1488 // check calling permissions
1489 if (!settingsAllowed()) {
1490 return PERMISSION_DENIED;
1491 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001492 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001493 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 return BAD_VALUE;
1495 }
1496
1497 { // scope for the lock
Andy Hung954b9712023-08-28 18:36:53 -07001498 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001499 if (mPrimaryHardwareDev == nullptr) {
1500 return INVALID_OPERATION;
1501 }
Andy Hunge3748872023-08-30 19:05:16 -07001502 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001504 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 mHardwareStatus = AUDIO_HW_IDLE;
1506 }
1507
1508 if (NO_ERROR == ret) {
Andy Hung954b9712023-08-28 18:36:53 -07001509 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 mMode = mode;
Andy Hung920f6572022-10-06 12:09:49 -07001511 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001512 mPlaybackThreads.valueAt(i)->setMode(mode);
Andy Hung920f6572022-10-06 12:09:49 -07001513 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 }
1515
Joey Poomarin52989982020-03-05 17:40:49 +08001516 mediametrics::LogItem(mMetricsId)
1517 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1518 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1519 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 return ret;
1521}
1522
1523status_t AudioFlinger::setMicMute(bool state)
1524{
Eric Laurenta1884f92011-08-23 08:25:03 -07001525 status_t ret = initCheck();
1526 if (ret != NO_ERROR) {
1527 return ret;
1528 }
1529
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 // check calling permissions
1531 if (!settingsAllowed()) {
1532 return PERMISSION_DENIED;
1533 }
1534
Andy Hung954b9712023-08-28 18:36:53 -07001535 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001536 if (mPrimaryHardwareDev == nullptr) {
1537 return INVALID_OPERATION;
1538 }
Andy Hunge3748872023-08-30 19:05:16 -07001539 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001540 if (primaryDev == nullptr) {
1541 ALOGW("%s: no primary HAL device", __func__);
1542 return INVALID_OPERATION;
1543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001545 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001546 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001547 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001548 if (dev != primaryDev) {
1549 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001550 }
1551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001553 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 return ret;
1555}
1556
1557bool AudioFlinger::getMicMute() const
1558{
Eric Laurenta1884f92011-08-23 08:25:03 -07001559 status_t ret = initCheck();
1560 if (ret != NO_ERROR) {
1561 return false;
1562 }
Andy Hung954b9712023-08-28 18:36:53 -07001563 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001564 if (mPrimaryHardwareDev == nullptr) {
1565 return false;
1566 }
Andy Hunge3748872023-08-30 19:05:16 -07001567 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001568 if (primaryDev == nullptr) {
1569 ALOGW("%s: no primary HAL device", __func__);
1570 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001571 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001572 bool state;
1573 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1574 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001576 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1577 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578}
1579
Eric Laurent5ada82e2019-08-29 17:53:54 -07001580void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001581{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001582 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001583
Andy Hung954b9712023-08-28 18:36:53 -07001584 audio_utils::lock_guard lock(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001585 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001586 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001587 }
1588 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001589 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001590 }
1591}
1592
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593status_t AudioFlinger::setMasterMute(bool muted)
1594{
John Grossmand8f178d2012-07-20 14:51:35 -07001595 status_t ret = initCheck();
1596 if (ret != NO_ERROR) {
1597 return ret;
1598 }
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 // check calling permissions
1601 if (!settingsAllowed()) {
1602 return PERMISSION_DENIED;
1603 }
1604
Andy Hung954b9712023-08-28 18:36:53 -07001605 audio_utils::lock_guard _l(mutex());
John Grossmanee578c02012-07-23 17:05:46 -07001606 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001607
John Grossmanee578c02012-07-23 17:05:46 -07001608 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001609 {
Andy Hung954b9712023-08-28 18:36:53 -07001610 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1612 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001613
Eric Laurent00abf0d2020-04-22 19:28:22 -07001614 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1615 if (dev->canSetMasterMute()) {
1616 dev->hwDevice()->setMasterMute(muted);
1617 }
1618 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001619 }
John Grossmand8f178d2012-07-20 14:51:35 -07001620 }
1621
John Grossmanee578c02012-07-23 17:05:46 -07001622 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001623 // assigned to HALs which do not have master mute support will apply master mute
1624 // during the mix operation. Threads with HALs which do support master mute
1625 // will simply ignore the setting.
Andy Hung84074c62023-07-06 19:21:50 -07001626 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001627 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1628 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630
1631 return NO_ERROR;
1632}
1633
1634float AudioFlinger::masterVolume() const
1635{
Andy Hung954b9712023-08-28 18:36:53 -07001636 audio_utils::lock_guard _l(mutex());
Glenn Kasten98067102011-12-13 11:47:54 -08001637 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638}
1639
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001640status_t AudioFlinger::getMasterBalance(float *balance) const
1641{
Andy Hung954b9712023-08-28 18:36:53 -07001642 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001643 *balance = getMasterBalance_l();
1644 return NO_ERROR; // if called through binder, may return a transactional error
1645}
1646
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647bool AudioFlinger::masterMute() const
1648{
Andy Hung954b9712023-08-28 18:36:53 -07001649 audio_utils::lock_guard _l(mutex());
Glenn Kasten98067102011-12-13 11:47:54 -08001650 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651}
1652
John Grossman4ff14ba2012-02-08 16:37:41 -08001653float AudioFlinger::masterVolume_l() const
1654{
John Grossman4ff14ba2012-02-08 16:37:41 -08001655 return mMasterVolume;
1656}
1657
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001658float AudioFlinger::getMasterBalance_l() const
1659{
1660 return mMasterBalance;
1661}
1662
John Grossmand8f178d2012-07-20 14:51:35 -07001663bool AudioFlinger::masterMute_l() const
1664{
John Grossmanee578c02012-07-23 17:05:46 -07001665 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001666}
1667
Andy Hungc2cf7ec2023-08-30 18:19:00 -07001668/* static */
1669status_t AudioFlinger::checkStreamType(audio_stream_type_t stream)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001670{
1671 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001672 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001673 return BAD_VALUE;
1674 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001675 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1676 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1677 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001678 return PERMISSION_DENIED;
1679 }
1680
1681 return NO_ERROR;
1682}
1683
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001684status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
Vlad Popa1e865e62024-08-15 19:11:42 -07001685 bool muted, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686{
1687 // check calling permissions
1688 if (!settingsAllowed()) {
1689 return PERMISSION_DENIED;
1690 }
1691
Eric Laurent223fd5c2014-11-11 13:43:36 -08001692 status_t status = checkStreamType(stream);
1693 if (status != NO_ERROR) {
1694 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 }
Eric Laurent98e38192018-02-15 18:31:53 -08001696 if (output == AUDIO_IO_HANDLE_NONE) {
1697 return BAD_VALUE;
1698 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001699 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1700 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701
Andy Hung954b9712023-08-28 18:36:53 -07001702 audio_utils::lock_guard lock(mutex());
Andy Hung84074c62023-07-06 19:21:50 -07001703 sp<VolumeInterface> volumeInterface = getVolumeInterface_l(output);
Eric Laurent98e38192018-02-15 18:31:53 -08001704 if (volumeInterface == NULL) {
1705 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 }
Vlad Popa1e865e62024-08-15 19:11:42 -07001707 volumeInterface->setStreamVolume(stream, value, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708
1709 return NO_ERROR;
1710}
1711
Andy Hung6b137d12024-08-27 22:35:17 +00001712status_t AudioFlinger::setPortsVolume(
Vlad Popa1e865e62024-08-15 19:11:42 -07001713 const std::vector<audio_port_handle_t> &ports, float volume, bool muted,
1714 audio_io_handle_t output) {
Andy Hung6b137d12024-08-27 22:35:17 +00001715 for (const auto& port : ports) {
1716 if (port == AUDIO_PORT_HANDLE_NONE) {
1717 return BAD_VALUE;
1718 }
1719 }
1720 if (isnan(volume) || volume > 1.0f || volume < 0.0f) {
1721 return BAD_VALUE;
1722 }
1723 if (output == AUDIO_IO_HANDLE_NONE) {
1724 return BAD_VALUE;
1725 }
1726 audio_utils::lock_guard lock(mutex());
1727 IAfPlaybackThread *thread = checkPlaybackThread_l(output);
1728 if (thread != nullptr) {
Vlad Popa1e865e62024-08-15 19:11:42 -07001729 return thread->setPortsVolume(ports, volume, muted);
Andy Hung6b137d12024-08-27 22:35:17 +00001730 }
1731 const sp<IAfMmapThread> mmapThread = checkMmapThread_l(output);
1732 if (mmapThread != nullptr && mmapThread->isOutput()) {
1733 IAfMmapPlaybackThread *mmapPlaybackThread = mmapThread->asIAfMmapPlaybackThread().get();
Vlad Popa1e865e62024-08-15 19:11:42 -07001734 return mmapPlaybackThread->setPortsVolume(ports, volume, muted);
Andy Hung6b137d12024-08-27 22:35:17 +00001735 }
1736 return BAD_VALUE;
1737}
1738
Eric Laurent076e7c72022-05-03 18:12:28 +02001739status_t AudioFlinger::setRequestedLatencyMode(
Eric Laurent68a40a82022-05-03 18:15:04 +02001740 audio_io_handle_t output, audio_latency_mode_t mode) {
Eric Laurent076e7c72022-05-03 18:12:28 +02001741 if (output == AUDIO_IO_HANDLE_NONE) {
1742 return BAD_VALUE;
1743 }
Andy Hung954b9712023-08-28 18:36:53 -07001744 audio_utils::lock_guard lock(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001745 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Eric Laurent68a40a82022-05-03 18:15:04 +02001746 if (thread == nullptr) {
1747 return BAD_VALUE;
1748 }
1749 return thread->setRequestedLatencyMode(mode);
Eric Laurent076e7c72022-05-03 18:12:28 +02001750}
1751
1752status_t AudioFlinger::getSupportedLatencyModes(audio_io_handle_t output,
Andy Hungcdd80ef2023-07-17 11:37:26 -07001753 std::vector<audio_latency_mode_t>* modes) const {
Eric Laurent076e7c72022-05-03 18:12:28 +02001754 if (output == AUDIO_IO_HANDLE_NONE) {
1755 return BAD_VALUE;
1756 }
Andy Hung954b9712023-08-28 18:36:53 -07001757 audio_utils::lock_guard lock(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001758 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Eric Laurent68a40a82022-05-03 18:15:04 +02001759 if (thread == nullptr) {
1760 return BAD_VALUE;
1761 }
1762 return thread->getSupportedLatencyModes(modes);
Eric Laurent076e7c72022-05-03 18:12:28 +02001763}
1764
Eric Laurent50d72582022-12-20 20:20:23 +01001765status_t AudioFlinger::setBluetoothVariableLatencyEnabled(bool enabled) {
Andy Hung954b9712023-08-28 18:36:53 -07001766 audio_utils::lock_guard _l(mutex());
Eric Laurent52057642022-12-16 11:45:07 +01001767 status_t status = INVALID_OPERATION;
1768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1769 // Success if at least one PlaybackThread supports Bluetooth latency modes
Eric Laurent50d72582022-12-20 20:20:23 +01001770 if (mPlaybackThreads.valueAt(i)->setBluetoothVariableLatencyEnabled(enabled) == NO_ERROR) {
Eric Laurent52057642022-12-16 11:45:07 +01001771 status = NO_ERROR;
1772 }
1773 }
1774 if (status == NO_ERROR) {
1775 mBluetoothLatencyModesEnabled.store(enabled);
1776 }
1777 return status;
1778}
1779
Andy Hungcdd80ef2023-07-17 11:37:26 -07001780status_t AudioFlinger::isBluetoothVariableLatencyEnabled(bool* enabled) const {
Eric Laurent50d72582022-12-20 20:20:23 +01001781 if (enabled == nullptr) {
1782 return BAD_VALUE;
1783 }
1784 *enabled = mBluetoothLatencyModesEnabled.load();
1785 return NO_ERROR;
1786}
1787
Andy Hungcdd80ef2023-07-17 11:37:26 -07001788status_t AudioFlinger::supportsBluetoothVariableLatency(bool* support) const {
Eric Laurent52057642022-12-16 11:45:07 +01001789 if (support == nullptr) {
1790 return BAD_VALUE;
1791 }
Andy Hungc2cf7ec2023-08-30 18:19:00 -07001792 audio_utils::lock_guard _l(hardwareMutex());
Eric Laurent52057642022-12-16 11:45:07 +01001793 *support = false;
1794 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurent50d72582022-12-20 20:20:23 +01001795 if (mAudioHwDevs.valueAt(i)->supportsBluetoothVariableLatency()) {
Eric Laurent52057642022-12-16 11:45:07 +01001796 *support = true;
1797 break;
1798 }
1799 }
1800 return NO_ERROR;
1801}
1802
Vlad Popae3fd1c22022-11-07 21:03:18 +01001803status_t AudioFlinger::getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
Andy Hungcdd80ef2023-07-17 11:37:26 -07001804 sp<media::ISoundDose>* soundDose) const {
Vlad Popae3fd1c22022-11-07 21:03:18 +01001805 if (soundDose == nullptr) {
1806 return BAD_VALUE;
1807 }
1808
1809 *soundDose = mMelReporter->getSoundDoseInterface(callback);
Vlad Popa63f047e2022-11-05 14:09:19 +01001810 return NO_ERROR;
1811}
1812
Glenn Kastenfff6d712012-01-12 16:38:12 -08001813status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814{
1815 // check calling permissions
1816 if (!settingsAllowed()) {
1817 return PERMISSION_DENIED;
1818 }
1819
Eric Laurent223fd5c2014-11-11 13:43:36 -08001820 status_t status = checkStreamType(stream);
1821 if (status != NO_ERROR) {
1822 return status;
1823 }
1824 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1825
1826 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001827 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 return BAD_VALUE;
1829 }
1830
Andy Hung954b9712023-08-28 18:36:53 -07001831 audio_utils::lock_guard lock(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 mStreamTypes[stream].mute = muted;
Andy Hung84074c62023-07-06 19:21:50 -07001833 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001834 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1835 volumeInterfaces[i]->setStreamMute(stream, muted);
1836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837
1838 return NO_ERROR;
1839}
1840
Andy Hungd9ef4b12020-11-11 15:13:18 -08001841void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001842{
1843 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1844 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1845 }
1846}
1847
jiabinc52b1ff2019-10-31 17:20:42 -07001848void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1849{
1850 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1851 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1852 }
1853}
1854
Andy Hung954b9712023-08-28 18:36:53 -07001855// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mutex() held
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001856void AudioFlinger::forwardParametersToDownstreamPatches_l(
1857 audio_io_handle_t upStream, const String8& keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07001858 const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread)
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001859{
Andy Hungb6692eb2023-07-13 16:52:46 -07001860 std::vector<SoftwarePatch> swPatches;
1861 if (mPatchPanel->getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001862 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1863 __func__, swPatches.size(), upStream);
1864 for (const auto& swPatch : swPatches) {
Andy Hung87c693c2023-07-06 20:56:16 -07001865 const sp<IAfPlaybackThread> downStream =
1866 checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001867 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1868 downStream->setParameters(keyValuePairs);
1869 }
1870 }
1871}
1872
Eric Laurent74c38dc2020-12-23 18:19:44 +01001873// Update downstream patches for all playback threads attached to an MSD module
1874void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
Andy Hung920f6572022-10-06 12:09:49 -07001875 const std::set<audio_io_handle_t>& streams)
Eric Laurent74c38dc2020-12-23 18:19:44 +01001876{
1877 for (const audio_io_handle_t stream : streams) {
Andy Hung87c693c2023-07-06 20:56:16 -07001878 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(stream);
Eric Laurent74c38dc2020-12-23 18:19:44 +01001879 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1880 continue;
1881 }
1882 playbackThread->setDownStreamPatch(patch);
1883 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1884 }
1885}
1886
Eric Laurentf1047e82018-04-16 19:18:20 -07001887// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1888// Some keys are used for audio routing and audio path configuration and should be reserved for use
1889// by audio policy and audio flinger for functional, privacy and security reasons.
1890void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1891{
1892 static const String8 kReservedParameters[] = {
1893 String8(AudioParameter::keyRouting),
1894 String8(AudioParameter::keySamplingRate),
1895 String8(AudioParameter::keyFormat),
1896 String8(AudioParameter::keyChannels),
1897 String8(AudioParameter::keyFrameCount),
1898 String8(AudioParameter::keyInputSource),
1899 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001900 String8(AudioParameter::keyDeviceConnect),
1901 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001902 String8(AudioParameter::keyStreamSupportedFormats),
1903 String8(AudioParameter::keyStreamSupportedChannels),
1904 String8(AudioParameter::keyStreamSupportedSamplingRates),
Andy Hungdda7aed2023-03-27 15:53:06 -07001905 String8(AudioParameter::keyClosing),
1906 String8(AudioParameter::keyExiting),
Eric Laurentf1047e82018-04-16 19:18:20 -07001907 };
1908
Andy Hung4ef19fa2018-05-15 19:35:29 -07001909 if (isAudioServerUid(callingUid)) {
1910 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001911 }
1912
1913 AudioParameter param = AudioParameter(keyValuePairs);
1914 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001915 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001916 for (auto& key : kReservedParameters) {
1917 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001918 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001919 param.remove(key);
1920 }
1921 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001922 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1923 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001924 keyValuePairs = param.toString();
1925}
1926
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001927void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1928 size_t rejectedKVPSize, const String8& rejectedKVPs,
1929 uid_t callingUid) {
1930 auto prefix = String8::format("UID %5d", callingUid);
1931 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1932 if (rejectedKVPSize != 0) {
1933 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1934 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1935 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1936 } else {
1937 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1938 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1939 }
1940}
1941
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001942status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943{
Eric Laurentf1047e82018-04-16 19:18:20 -07001944 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001945 ioHandle, keyValuePairs.c_str(),
Eric Laurentf1047e82018-04-16 19:18:20 -07001946 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001947
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 // check calling permissions
1949 if (!settingsAllowed()) {
1950 return PERMISSION_DENIED;
1951 }
1952
Eric Laurentf1047e82018-04-16 19:18:20 -07001953 String8 filteredKeyValuePairs = keyValuePairs;
1954 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1955
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001956 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.c_str());
Eric Laurentf1047e82018-04-16 19:18:20 -07001957
Glenn Kasten142f5192014-03-25 17:44:59 -07001958 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1959 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Andy Hung954b9712023-08-28 18:36:53 -07001960 audio_utils::lock_guard _l(mutex());
Eric Laurentd21bcd22016-09-08 18:25:54 -07001961 // result will remain NO_INIT if no audio device is present
1962 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001963 {
Andy Hung954b9712023-08-28 18:36:53 -07001964 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -07001965 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001967 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001968 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001969 // return success if at least one audio device accepts the parameters as not all
1970 // HALs are requested to support all parameters. If no audio device supports the
1971 // requested parameters, the last error is reported.
1972 if (final_result != NO_ERROR) {
1973 final_result = result;
1974 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001975 }
1976 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001977 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001978 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001979 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001980 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001981 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1982 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001983 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001984 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001985 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001986 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001987 }
1988 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001989 String8 screenState;
1990 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001991 bool isOff = (screenState == AudioParameter::valueOff);
Andy Hung1d2d2aea2023-07-19 16:22:58 -07001992 if (isOff != (mScreenState & 1)) {
1993 mScreenState = ((mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001994 }
1995 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001996 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 }
1998
1999 // hold a strong ref on thread in case closeOutput() or closeInput() is called
2000 // and the thread is exited once the lock is released
Andy Hung87c693c2023-07-06 20:56:16 -07002001 sp<IAfThreadBase> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 {
Andy Hung954b9712023-08-28 18:36:53 -07002003 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07002005 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002007 if (thread == 0) {
2008 thread = checkMmapThread_l(ioHandle);
2009 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08002010 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002011 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07002012 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002013 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07002014 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
2015 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08002016 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 }
2019 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08002020 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002021 status_t result = thread->setParameters(filteredKeyValuePairs);
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002022 audio_utils::lock_guard _l(mutex());
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002023 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
2024 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026 return BAD_VALUE;
2027}
2028
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002029String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030{
Glenn Kasten827e5f12012-11-02 10:00:06 -07002031 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002032 ioHandle, keys.c_str(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033
Andy Hung954b9712023-08-28 18:36:53 -07002034 audio_utils::lock_guard _l(mutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -07002035
Glenn Kasten142f5192014-03-25 17:44:59 -07002036 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002037 String8 out_s8;
2038
Andy Hung954b9712023-08-28 18:36:53 -07002039 audio_utils::lock_guard lock(hardwareMutex());
Dima Zavin799a70e2011-04-18 16:57:27 -07002040 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002041 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002042 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002043 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07002044 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002045 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002046 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07002047 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002048 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 }
2050
Andy Hung87c693c2023-07-06 20:56:16 -07002051 IAfThreadBase* thread = checkPlaybackThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002052 if (thread == NULL) {
Andy Hung87c693c2023-07-06 20:56:16 -07002053 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002054 if (thread == NULL) {
Andy Hung87c693c2023-07-06 20:56:16 -07002055 thread = checkMmapThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08002056 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07002057 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08002058 }
2059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08002061 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062}
2063
Glenn Kastendd8104c2012-07-02 12:42:44 -07002064size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
2065 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066{
Eric Laurenta1884f92011-08-23 08:25:03 -07002067 status_t ret = initCheck();
2068 if (ret != NO_ERROR) {
2069 return 0;
2070 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08002071 if ((sampleRate == 0) ||
Dean Wheatley8d72b4b2023-11-16 06:43:58 +11002072 !audio_is_valid_format(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08002073 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07002074 return 0;
2075 }
Eric Laurenta1884f92011-08-23 08:25:03 -07002076
Andy Hung954b9712023-08-28 18:36:53 -07002077 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002078 if (mPrimaryHardwareDev == nullptr) {
2079 return 0;
2080 }
Oleg Lyovin7434b722024-03-05 18:08:01 +03002081 if (mInputBufferSizeOrderedDevs.empty()) {
2082 return 0;
2083 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002084 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002085
Judy Hsiaoabab5222019-11-09 18:14:58 +08002086 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
Andy Hung920f6572022-10-06 12:09:49 -07002087 if (channelMask != AUDIO_CHANNEL_IN_MONO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002088 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
Andy Hung920f6572022-10-06 12:09:49 -07002089 }
2090 if (channelMask != AUDIO_CHANNEL_IN_STEREO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002091 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
Andy Hung920f6572022-10-06 12:09:49 -07002092 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002093
2094 std::vector<audio_format_t> formats = {format};
Andy Hung920f6572022-10-06 12:09:49 -07002095 if (format != AUDIO_FORMAT_PCM_16_BIT) {
Dean Wheatley8d72b4b2023-11-16 06:43:58 +11002096 // For compressed format, buffer size may be queried using PCM. Allow this for compatibility
2097 // in cases the primary hw dev does not support the format.
2098 // TODO: replace with a table of formats and nominal buffer sizes (based on nominal bitrate
2099 // and codec frame size).
Judy Hsiaoabab5222019-11-09 18:14:58 +08002100 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
Andy Hung920f6572022-10-06 12:09:49 -07002101 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002102
2103 std::vector<uint32_t> sampleRates = {sampleRate};
2104 static const uint32_t SR_44100 = 44100;
2105 static const uint32_t SR_48000 = 48000;
Andy Hung920f6572022-10-06 12:09:49 -07002106 if (sampleRate != SR_48000) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002107 sampleRates.push_back(SR_48000);
Andy Hung920f6572022-10-06 12:09:49 -07002108 }
2109 if (sampleRate != SR_44100) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002110 sampleRates.push_back(SR_44100);
Andy Hung920f6572022-10-06 12:09:49 -07002111 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002112
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002113 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002114
Oleg Lyovin7434b722024-03-05 18:08:01 +03002115 auto getInputBufferSize = [](const sp<DeviceHalInterface>& dev, audio_config_t config,
2116 size_t* bytes) -> status_t {
2117 if (!dev) {
2118 return BAD_VALUE;
2119 }
2120 status_t result = dev->getInputBufferSize(&config, bytes);
2121 if (result == BAD_VALUE) {
2122 // Retry with the config suggested by the HAL.
2123 result = dev->getInputBufferSize(&config, bytes);
2124 }
2125 if (result != OK || *bytes == 0) {
2126 return BAD_VALUE;
2127 }
2128 return result;
2129 };
2130
Robin Lee9899ff72019-12-24 22:02:08 +01002131 // Change parameters of the configuration each iteration until we find a
Mikhail Naganovd5b643f2024-02-15 11:51:26 -08002132 // configuration that the device will support, or HAL suggests what it supports.
Robin Lee9899ff72019-12-24 22:02:08 +01002133 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002134 for (auto testChannelMask : channelMasks) {
2135 config.channel_mask = testChannelMask;
2136 for (auto testFormat : formats) {
2137 config.format = testFormat;
2138 for (auto testSampleRate : sampleRates) {
2139 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01002140
Judy Hsiaoabab5222019-11-09 18:14:58 +08002141 size_t bytes = 0;
Oleg Lyovin7434b722024-03-05 18:08:01 +03002142 ret = BAD_VALUE;
2143 for (const AudioHwDevice* dev : mInputBufferSizeOrderedDevs) {
2144 ret = getInputBufferSize(dev->hwDevice(), config, &bytes);
2145 if (ret == OK) {
2146 break;
2147 }
Mikhail Naganovd5b643f2024-02-15 11:51:26 -08002148 }
Oleg Lyovin7434b722024-03-05 18:08:01 +03002149 if (ret == BAD_VALUE) continue;
2150
Judy Hsiaoabab5222019-11-09 18:14:58 +08002151 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
2152 config.format != format) {
2153 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
2154 uint32_t srcChannelCount =
2155 audio_channel_count_from_in_mask(config.channel_mask);
2156 size_t srcFrames =
2157 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
2158 size_t dstFrames = destinationFramesPossible(
2159 srcFrames, config.sample_rate, sampleRate);
2160 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
2161 }
2162 return bytes;
2163 }
2164 }
Andy Hung6770c6f2015-04-07 13:43:36 -07002165 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002166
2167 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
2168 "format %#x, channelMask %#x",sampleRate, format, channelMask);
2169 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170}
2171
Glenn Kasten5f972c02014-01-13 09:59:31 -08002172uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173{
Andy Hung954b9712023-08-28 18:36:53 -07002174 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175
Andy Hung87c693c2023-07-06 20:56:16 -07002176 IAfRecordThread* const recordThread = checkRecordThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 if (recordThread != NULL) {
2178 return recordThread->getInputFramesLost();
2179 }
2180 return 0;
2181}
2182
2183status_t AudioFlinger::setVoiceVolume(float value)
2184{
Eric Laurenta1884f92011-08-23 08:25:03 -07002185 status_t ret = initCheck();
2186 if (ret != NO_ERROR) {
2187 return ret;
2188 }
2189
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 // check calling permissions
2191 if (!settingsAllowed()) {
2192 return PERMISSION_DENIED;
2193 }
2194
Andy Hung954b9712023-08-28 18:36:53 -07002195 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002196 if (mPrimaryHardwareDev == nullptr) {
2197 return INVALID_OPERATION;
2198 }
Andy Hunge3748872023-08-30 19:05:16 -07002199 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002200 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002201 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202 mHardwareStatus = AUDIO_HW_IDLE;
2203
Joey Poomarin52989982020-03-05 17:40:49 +08002204 mediametrics::LogItem(mMetricsId)
2205 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
2206 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
2207 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002208 return ret;
2209}
2210
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002211status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002212 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213{
Andy Hung954b9712023-08-28 18:36:53 -07002214 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215
Andy Hung87c693c2023-07-06 20:56:16 -07002216 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 if (playbackThread != NULL) {
2218 return playbackThread->getRenderPosition(halFrames, dspFrames);
2219 }
2220
2221 return BAD_VALUE;
2222}
2223
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002224void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225{
Eric Laurent44622db2014-08-01 19:00:33 -07002226 if (client == 0) {
2227 return;
2228 }
Andy Hung05b0ffe2024-08-30 17:18:37 -07002229 const pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08002230 const uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung05b0ffe2024-08-30 17:18:37 -07002231
2232 audio_utils::lock_guard _l(mutex());
Eric Laurent021cf962014-05-13 10:18:14 -07002233 {
Andy Hung954b9712023-08-28 18:36:53 -07002234 audio_utils::lock_guard _cl(clientMutex());
Andy Hung05b0ffe2024-08-30 17:18:37 -07002235 if (mNotificationClients.count(pid) == 0) {
2236 auto notificationClient = sp<NotificationClient>::make(
2237 this, client, pid, uid);
Andy Hungbcd19ea2024-08-22 16:32:21 +00002238 ALOGV("registerClient() client %p, pid %d, uid %u",
2239 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240
Andy Hung05b0ffe2024-08-30 17:18:37 -07002241 mNotificationClients[pid] = notificationClient;
Marco Nelissen06b46062014-11-14 07:58:25 -08002242 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07002243 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07002244 }
2245 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246
Andy Hung954b9712023-08-28 18:36:53 -07002247 // clientMutex() should not be held here because ThreadBase::sendIoConfigEvent()
2248 // will lock the ThreadBase::mutex() and the locking order is
2249 // ThreadBase::mutex() then AudioFlinger::clientMutex().
2250 // The config change is always sent from playback or record threads to avoid deadlock
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002251 // with AudioSystem::gLock
2252 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002253 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002254 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002257 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 }
2259}
2260
2261void AudioFlinger::removeNotificationClient(pid_t pid)
2262{
Andy Hung6ac17eb2023-06-20 18:56:17 -07002263 std::vector<sp<IAfEffectModule>> removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07002264 {
Andy Hung954b9712023-08-28 18:36:53 -07002265 audio_utils::lock_guard _l(mutex());
Eric Laurent6c796322019-04-09 14:13:17 -07002266 {
Andy Hung954b9712023-08-28 18:36:53 -07002267 audio_utils::lock_guard _cl(clientMutex());
Andy Hung05b0ffe2024-08-30 17:18:37 -07002268 mNotificationClients.erase(pid);
Eric Laurent6c796322019-04-09 14:13:17 -07002269 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002270
Eric Laurent6c796322019-04-09 14:13:17 -07002271 ALOGV("%d died, releasing its sessions", pid);
2272 size_t num = mAudioSessionRefs.size();
2273 bool removed = false;
2274 for (size_t i = 0; i < num; ) {
2275 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2276 ALOGV(" pid %d @ %zu", ref->mPid, i);
2277 if (ref->mPid == pid) {
2278 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
2279 mAudioSessionRefs.removeAt(i);
2280 delete ref;
2281 removed = true;
2282 num--;
2283 } else {
2284 i++;
2285 }
2286 }
2287 if (removed) {
2288 removedEffects = purgeStaleEffects_l();
François Gaffie1b4753e2023-02-06 10:36:33 +01002289 std::vector< sp<IAfEffectModule> > removedOrphanEffects = purgeOrphanEffectChains_l();
2290 removedEffects.insert(removedEffects.end(), removedOrphanEffects.begin(),
2291 removedOrphanEffects.end());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002292 }
2293 }
Eric Laurent6c796322019-04-09 14:13:17 -07002294 for (auto& effect : removedEffects) {
2295 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297}
2298
Andy Hungab65b182023-09-06 19:41:47 -07002299// Hold either AudioFlinger::mutex or ThreadBase::mutex
2300void AudioFlinger::ioConfigChanged_l(audio_io_config_event_t event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002301 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002302 pid_t pid) {
Andy Hungb75b6242021-07-29 16:46:14 +00002303 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
2304 legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002305 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
2306 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002307
Andy Hung954b9712023-08-28 18:36:53 -07002308 audio_utils::lock_guard _l(clientMutex());
Andy Hung05b0ffe2024-08-30 17:18:37 -07002309 if (pid != 0) {
2310 if (auto it = mNotificationClients.find(pid); it != mNotificationClients.end()) {
2311 it->second->audioFlingerClient()->ioConfigChanged(eventAidl, descAidl);
2312 }
2313 } else {
2314 for (const auto& [ client_pid, client] : mNotificationClients) {
2315 client->audioFlingerClient()->ioConfigChanged(eventAidl, descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317 }
2318}
2319
Eric Laurent076e7c72022-05-03 18:12:28 +02002320void AudioFlinger::onSupportedLatencyModesChanged(
2321 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) {
2322 int32_t outputAidl = VALUE_OR_FATAL(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovf53e1822022-12-18 02:48:14 +00002323 std::vector<media::audio::common::AudioLatencyMode> modesAidl = VALUE_OR_FATAL(
2324 convertContainer<std::vector<media::audio::common::AudioLatencyMode>>(
2325 modes, legacy2aidl_audio_latency_mode_t_AudioLatencyMode));
Eric Laurent076e7c72022-05-03 18:12:28 +02002326
Andy Hung954b9712023-08-28 18:36:53 -07002327 audio_utils::lock_guard _l(clientMutex());
Eric Laurent076e7c72022-05-03 18:12:28 +02002328 size_t size = mNotificationClients.size();
Andy Hung05b0ffe2024-08-30 17:18:37 -07002329 for (const auto& [_, client] : mNotificationClients) {
2330 client->audioFlingerClient()->onSupportedLatencyModesChanged(outputAidl, modesAidl);
Eric Laurent076e7c72022-05-03 18:12:28 +02002331 }
2332}
2333
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07002334void AudioFlinger::onHardError(std::set<audio_port_handle_t>& trackPortIds) {
2335 ALOGI("releasing tracks due to a hard error occurred on an I/O thread");
2336 for (const auto portId : trackPortIds) {
2337 AudioSystem::releaseOutput(portId);
2338 }
2339}
2340
Atneya Nair5997a652024-06-14 17:24:45 -07002341const IPermissionProvider& AudioFlinger::getPermissionProvider() {
2342 // This is inited as part of service construction, prior to binder registration,
2343 // so it should always be non-null.
2344 return mAudioPolicyServiceLocal.load()->getPermissionProvider();
2345}
2346
Andy Hung954b9712023-08-28 18:36:53 -07002347// removeClient_l() must be called with AudioFlinger::clientMutex() held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348void AudioFlinger::removeClient_l(pid_t pid)
2349{
Glenn Kasten827e5f12012-11-02 10:00:06 -07002350 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002351 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 mClients.removeItem(pid);
2353}
2354
Andy Hung954b9712023-08-28 18:36:53 -07002355// getEffectThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07002356sp<IAfThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002357 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07002358{
Andy Hung87c693c2023-07-06 20:56:16 -07002359 sp<IAfThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07002360
2361 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002362 thread = mPlaybackThreads.valueAt(i);
2363 if (thread->getEffect(sessionId, effectId) != 0) {
2364 return thread;
Eric Laurent717e1282012-06-29 16:36:52 -07002365 }
2366 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002367 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002368 thread = mRecordThreads.valueAt(i);
2369 if (thread->getEffect(sessionId, effectId) != 0) {
2370 return thread;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002371 }
2372 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002373 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002374 thread = mMmapThreads.valueAt(i);
2375 if (thread->getEffect(sessionId, effectId) != 0) {
2376 return thread;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002377 }
2378 }
Shunkai Yao0bc64562024-02-14 03:01:33 +00002379 return nullptr;
Eric Laurent717e1282012-06-29 16:36:52 -07002380}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382// ----------------------------------------------------------------------------
2383
2384AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002385 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002386 pid_t pid,
Andy Hungbcd19ea2024-08-22 16:32:21 +00002387 uid_t uid)
2388 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Andy Hung88a7afe2024-08-12 20:00:46 -07002389 , mClientToken(media::psh_utils::AudioPowerManager::enabled()
2390 ? media::psh_utils::createAudioClientToken(pid, uid)
2391 : nullptr)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392{
2393}
2394
2395AudioFlinger::NotificationClient::~NotificationClient()
2396{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397}
2398
Glenn Kasten0f11b512014-01-31 16:18:54 -08002399void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400{
Andy Hung05b0ffe2024-08-30 17:18:37 -07002401 const auto keep = sp<NotificationClient>::fromExisting(this);
Glenn Kastena1117922012-01-26 10:53:32 -08002402 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403}
2404
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002405// ----------------------------------------------------------------------------
2406AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2407 : mPendingRequests(false) {}
2408
2409
2410void AudioFlinger::MediaLogNotifier::requestMerge() {
Andy Hung954b9712023-08-28 18:36:53 -07002411 audio_utils::lock_guard _l(mMutex);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002412 mPendingRequests = true;
Andy Hung954b9712023-08-28 18:36:53 -07002413 mCondition.notify_one();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002414}
2415
2416bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002417 // Should already have been checked, but just in case
2418 if (sMediaLogService == 0) {
2419 return false;
2420 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002421 // Wait until there are pending requests
2422 {
Andy Hung954b9712023-08-28 18:36:53 -07002423 audio_utils::unique_lock _l(mMutex);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002424 mPendingRequests = false; // to ignore past requests
2425 while (!mPendingRequests) {
Andy Hung954b9712023-08-28 18:36:53 -07002426 mCondition.wait(_l);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002427 // TODO may also need an exitPending check
2428 }
2429 mPendingRequests = false;
2430 }
2431 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002432 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002433 usleep(kPostTriggerSleepPeriod);
2434 return true;
2435}
2436
2437void AudioFlinger::requestLogMerge() {
2438 mMediaLogNotifier->requestMerge();
2439}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440
2441// ----------------------------------------------------------------------------
2442
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002443status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2444 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002446 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002447 CreateRecordOutput output;
2448
Andy Hung8d31fd22023-06-26 19:20:57 -07002449 sp<IAfRecordTrack> recordTrack;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002452 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002453 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
Eric Laurentf14db3c2017-12-08 14:20:36 -08002455 output.cblk.clear();
2456 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002457 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002458
Atneya Nair5997a652024-06-14 17:24:45 -07002459 AttributionSourceState adjAttributionSource;
2460 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2461 if (!com::android::media::audio::audioserver_permissions()) {
2462 adjAttributionSource = input.clientInfo.attributionSource;
2463 bool updatePid = (adjAttributionSource.pid == -1);
2464 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2465 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2466 adjAttributionSource.uid));
2467 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
2468 ALOGW_IF(currentUid != callingUid,
2469 "%s uid %d tried to pass itself off as %d",
2470 __FUNCTION__, callingUid, currentUid);
2471 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
2472 legacy2aidl_uid_t_int32_t(callingUid));
2473 updatePid = true;
2474 }
2475 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2476 adjAttributionSource.pid));
2477 if (updatePid) {
2478 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
2479 "%s uid %d pid %d tried to pass itself off as pid %d",
2480 __func__, callingUid, callingPid, currentPid);
2481 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
2482 legacy2aidl_pid_t_int32_t(callingPid));
2483 }
2484 adjAttributionSource = afutils::checkAttributionSourcePackage(
2485 adjAttributionSource);
2486 } else {
2487 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
2488 validateAttributionFromContextOrTrustedCaller(
2489 input.clientInfo.attributionSource,
2490 getPermissionProvider()
2491 ));
2492 // TODO pass wrapped object around
2493 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002494 }
Atneya Nair5997a652024-06-14 17:24:45 -07002495
Dean Wheatleya404ff42023-10-20 13:25:02 +11002496 // further format checks are performed by createRecordTrack_l()
2497 if (!audio_is_valid_format(input.config.format)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002498 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002499 lStatus = BAD_VALUE;
2500 goto Exit;
2501 }
2502
Glenn Kasten53b5d092014-02-05 10:00:23 -08002503 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002504 if (!audio_is_input_channel(input.config.channel_mask)) {
2505 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002506 lStatus = BAD_VALUE;
2507 goto Exit;
2508 }
2509
Eric Laurentf14db3c2017-12-08 14:20:36 -08002510 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2511 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2512 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2513 lStatus = BAD_VALUE;
2514 goto Exit;
2515 }
2516
2517 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002518 output.selectedDeviceId = input.selectedDeviceId;
2519 output.flags = input.flags;
2520
Atneya Nairb01390f2024-10-09 23:33:27 +00002521 client = registerClient(adjAttributionSource.pid, adjAttributionSource.uid);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002522
2523 // Not a conventional loop, but a retry loop for at most two iterations total.
2524 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2525 // Exits loop via break on no error of got exit on error
2526 // The sp<> references will be dropped when re-entering scope.
2527 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2528 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002529 // release previously opened input if retrying.
2530 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2531 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002532 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002533 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002534 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002535 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002536 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002537 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002538 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002539 sessionId,
2540 // FIXME compare to AudioTrack
Svet Ganov33761132021-05-13 22:51:08 +00002541 adjAttributionSource,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002542 &input.config,
2543 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002544 if (lStatus != NO_ERROR) {
2545 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2546 goto Exit;
2547 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002548
Glenn Kasten05997e22014-03-13 15:08:33 -07002549 {
Andy Hung954b9712023-08-28 18:36:53 -07002550 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002551 IAfRecordThread* const thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002553 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2554 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 goto Exit;
2556 }
2557
Eric Laurentf14db3c2017-12-08 14:20:36 -08002558 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559
Eric Laurentf14db3c2017-12-08 14:20:36 -08002560 output.sampleRate = input.config.sample_rate;
2561 output.frameCount = input.frameCount;
2562 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002563
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002564 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002565 input.config.format, input.config.channel_mask,
2566 &output.frameCount, sessionId,
2567 &output.notificationFrameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002568 callingPid, adjAttributionSource, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002569 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002570 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002571 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002572
Eric Laurentf14db3c2017-12-08 14:20:36 -08002573 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2574 // audio policy manager without FAST constraint
2575 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002576 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002577 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002578
2579 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002580 goto Exit;
2581 }
2582
jiabinb00edc32021-08-16 16:27:54 +00002583 if (recordTrack->isFastTrack()) {
2584 output.serverConfig = {
2585 thread->sampleRate(),
2586 thread->channelMask(),
2587 thread->format()
2588 };
2589 } else {
2590 output.serverConfig = {
2591 recordTrack->sampleRate(),
2592 recordTrack->channelMask(),
2593 recordTrack->format()
2594 };
2595 }
2596
Robert Wu310037a2022-09-06 21:48:18 +00002597 output.halConfig = {
2598 thread->sampleRate(),
2599 thread->channelMask(),
2600 thread->format()
2601 };
2602
Eric Laurentf14db3c2017-12-08 14:20:36 -08002603 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2604 // session and move it to this thread.
Andy Hung6ac17eb2023-06-20 18:56:17 -07002605 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002606 if (chain != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07002607 audio_utils::lock_guard _l2(thread->mutex());
Eric Laurentf14db3c2017-12-08 14:20:36 -08002608 thread->addEffectChain_l(chain);
2609 }
2610 break;
2611 }
2612 // End of retry loop.
2613 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 }
Glenn Kastene198c362013-08-13 09:13:36 -07002615
Eric Laurentf14db3c2017-12-08 14:20:36 -08002616 output.cblk = recordTrack->getCblk();
2617 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002618 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002619
Andy Hungd29af632023-06-23 19:27:19 -07002620 output.audioRecord = IAfRecordTrack::createIAudioRecordAdapter(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002621 _output = VALUE_OR_FATAL(output.toAidl());
2622
Eric Laurentf14db3c2017-12-08 14:20:36 -08002623Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002624 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002625 // remove local strong reference to Client before deleting the RecordTrack so that the
Andy Hung954b9712023-08-28 18:36:53 -07002626 // Client destructor is called by the TrackBase destructor with clientMutex() held
2627 // Don't hold clientMutex() when releasing the reference on the track as the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002628 // destructor will acquire it.
2629 {
Andy Hung954b9712023-08-28 18:36:53 -07002630 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002631 client.clear();
2632 }
Eric Laurent896c9672017-12-08 14:08:45 -08002633 recordTrack.clear();
2634 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002635 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637 }
2638
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002639 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640}
2641
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002642
2643
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644// ----------------------------------------------------------------------------
2645
Mikhail Naganovffd97712023-05-03 17:45:36 -07002646status_t AudioFlinger::getAudioPolicyConfig(media::AudioPolicyConfig *config)
2647{
2648 if (config == nullptr) {
2649 return BAD_VALUE;
2650 }
Andy Hung954b9712023-08-28 18:36:53 -07002651 audio_utils::lock_guard _l(mutex());
2652 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovffd97712023-05-03 17:45:36 -07002653 RETURN_STATUS_IF_ERROR(
2654 mDevicesFactoryHal->getSurroundSoundConfig(&config->surroundSoundConfig));
2655 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getEngineConfig(&config->engineConfig));
2656 std::vector<std::string> hwModuleNames;
2657 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getDeviceNames(&hwModuleNames));
2658 std::set<AudioMode> allSupportedModes;
2659 for (const auto& name : hwModuleNames) {
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002660 AudioHwDevice* module = loadHwModule_ll(name.c_str());
Mikhail Naganovffd97712023-05-03 17:45:36 -07002661 if (module == nullptr) continue;
2662 media::AudioHwModule aidlModule;
2663 if (module->hwDevice()->getAudioPorts(&aidlModule.ports) == OK &&
2664 module->hwDevice()->getAudioRoutes(&aidlModule.routes) == OK) {
2665 aidlModule.handle = module->handle();
2666 aidlModule.name = module->moduleName();
2667 config->modules.push_back(std::move(aidlModule));
2668 }
2669 std::vector<AudioMode> supportedModes;
2670 if (module->hwDevice()->getSupportedModes(&supportedModes) == OK) {
2671 allSupportedModes.insert(supportedModes.begin(), supportedModes.end());
2672 }
2673 }
2674 if (!allSupportedModes.empty()) {
2675 config->supportedModes.insert(config->supportedModes.end(),
2676 allSupportedModes.begin(), allSupportedModes.end());
2677 } else {
2678 ALOGW("%s: The HAL does not provide telephony functionality", __func__);
2679 config->supportedModes = { media::audio::common::AudioMode::NORMAL,
2680 media::audio::common::AudioMode::RINGTONE,
2681 media::audio::common::AudioMode::IN_CALL,
2682 media::audio::common::AudioMode::IN_COMMUNICATION };
2683 }
2684 return OK;
2685}
2686
Eric Laurenta4c5a552012-03-29 10:12:40 -07002687audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2688{
Eric Laurent44622db2014-08-01 19:00:33 -07002689 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002690 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002691 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002692 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002693 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002694 }
Andy Hung954b9712023-08-28 18:36:53 -07002695 audio_utils::lock_guard _l(mutex());
2696 audio_utils::lock_guard lock(hardwareMutex());
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002697 AudioHwDevice* module = loadHwModule_ll(name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002698 return module != nullptr ? module->handle() : AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002699}
2700
Andy Hung954b9712023-08-28 18:36:53 -07002701// loadHwModule_l() must be called with AudioFlinger::mutex()
2702// and AudioFlinger::hardwareMutex() held
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002703AudioHwDevice* AudioFlinger::loadHwModule_ll(const char *name)
Eric Laurenta4c5a552012-03-29 10:12:40 -07002704{
2705 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2706 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2707 ALOGW("loadHwModule() module %s already loaded", name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002708 return mAudioHwDevs.valueAt(i);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002709 }
2710 }
2711
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002712 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002713
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002714 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002715 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002716 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002717 return nullptr;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002718 }
Vlad Popa03bd5bc2023-01-17 16:16:51 +01002719 if (!mMelReporter->activateHalSoundDoseComputation(name, dev)) {
Vlad Popa1d5f0d52022-12-18 12:21:26 +01002720 ALOGW("loadHwModule() sound dose reporting is not available");
2721 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002722
2723 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002724 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002725 mHardwareStatus = AUDIO_HW_IDLE;
2726 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002727 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002728 return nullptr;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002729 }
2730
John Grossmanee578c02012-07-23 17:05:46 -07002731 // Check and cache this HAL's level of support for master mute and master
2732 // volume. If this is the first HAL opened, and it supports the get
2733 // methods, use the initial values provided by the HAL as the current
2734 // master mute and volume settings.
2735
2736 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002737 if (0 == mAudioHwDevs.size()) {
2738 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2739 float mv;
2740 if (OK == dev->getMasterVolume(&mv)) {
2741 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002742 }
2743
Eric Laurent00abf0d2020-04-22 19:28:22 -07002744 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2745 bool mm;
2746 if (OK == dev->getMasterMute(&mm)) {
2747 mMasterMute = mm;
Andy Hung0e26ec62024-02-20 16:32:57 -08002748 ALOGI_IF(mMasterMute, "%s: applying mute from HAL %s", __func__, name);
John Grossmanee578c02012-07-23 17:05:46 -07002749 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002750 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002751
2752 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2753 if (OK == dev->setMasterVolume(mMasterVolume)) {
2754 flags = static_cast<AudioHwDevice::Flags>(flags |
2755 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2756 }
2757
2758 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2759 if (OK == dev->setMasterMute(mMasterMute)) {
2760 flags = static_cast<AudioHwDevice::Flags>(flags |
2761 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2762 }
2763
2764 mHardwareStatus = AUDIO_HW_IDLE;
2765
Mikhail Naganov97373b02018-07-23 13:27:24 -07002766 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002767 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2768 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2769 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002770
Eric Laurent52057642022-12-16 11:45:07 +01002771
2772 if (bool supports = false;
Eric Laurent50d72582022-12-20 20:20:23 +01002773 dev->supportsBluetoothVariableLatency(&supports) == NO_ERROR && supports) {
Eric Laurent52057642022-12-16 11:45:07 +01002774 flags = static_cast<AudioHwDevice::Flags>(flags |
2775 AudioHwDevice::AHWD_SUPPORTS_BT_LATENCY_MODES);
2776 }
2777
Glenn Kastena13cde92016-03-28 15:26:02 -07002778 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002779 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2780 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2781 mPrimaryHardwareDev = audioDevice;
2782 mHardwareStatus = AUDIO_HW_SET_MODE;
Andy Hunge3748872023-08-30 19:05:16 -07002783 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002784 mHardwareStatus = AUDIO_HW_IDLE;
2785 }
2786
Shunkai Yao2b8fed42022-12-09 01:12:02 +00002787 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +00002788 if (int32_t mixerBursts = dev->getAAudioMixerBurstCount();
jiabina4ff38f2022-02-11 19:42:25 +00002789 mixerBursts > 0 && mixerBursts > mAAudioBurstsPerBuffer) {
jiabine504e7b2021-09-18 00:27:08 +00002790 mAAudioBurstsPerBuffer = mixerBursts;
2791 }
2792 if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec();
jiabina4ff38f2022-02-11 19:42:25 +00002793 hwBurstMinMicros > 0
2794 && (hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0)) {
jiabine504e7b2021-09-18 00:27:08 +00002795 mAAudioHwBurstMinMicros = hwBurstMinMicros;
2796 }
2797 }
2798
Eric Laurent00abf0d2020-04-22 19:28:22 -07002799 mAudioHwDevs.add(handle, audioDevice);
Oleg Lyovin7434b722024-03-05 18:08:01 +03002800 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_STUB) != 0) {
2801 mInputBufferSizeOrderedDevs.insert(audioDevice);
2802 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002803
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002804 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002805
Mikhail Naganovffd97712023-05-03 17:45:36 -07002806 return audioDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002807}
2808
Oleg Lyovin7434b722024-03-05 18:08:01 +03002809// Sort AudioHwDevice to be traversed in the getInputBufferSize call in the following order:
2810// Primary, Usb, Bluetooth, A2DP, other modules, remote submix.
2811/* static */
2812bool AudioFlinger::inputBufferSizeDevsCmp(const AudioHwDevice* lhs, const AudioHwDevice* rhs) {
2813 static const std::map<std::string_view, int> kPriorities = {
2814 { AUDIO_HARDWARE_MODULE_ID_PRIMARY, 0 }, { AUDIO_HARDWARE_MODULE_ID_USB, 1 },
2815 { AUDIO_HARDWARE_MODULE_ID_BLUETOOTH, 2 }, { AUDIO_HARDWARE_MODULE_ID_A2DP, 3 },
2816 { AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, std::numeric_limits<int>::max() }
2817 };
2818
2819 const std::string_view lhsName = lhs->moduleName();
2820 const std::string_view rhsName = rhs->moduleName();
2821
2822 auto lhsPriority = std::numeric_limits<int>::max() - 1;
2823 if (const auto lhsIt = kPriorities.find(lhsName); lhsIt != kPriorities.end()) {
2824 lhsPriority = lhsIt->second;
2825 }
2826 auto rhsPriority = std::numeric_limits<int>::max() - 1;
2827 if (const auto rhsIt = kPriorities.find(rhsName); rhsIt != kPriorities.end()) {
2828 rhsPriority = rhsIt->second;
2829 }
2830
2831 if (lhsPriority != rhsPriority) {
2832 return lhsPriority < rhsPriority;
2833 }
2834 return lhsName < rhsName;
2835}
2836
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002837// ----------------------------------------------------------------------------
2838
Andy Hungcdd80ef2023-07-17 11:37:26 -07002839uint32_t AudioFlinger::getPrimaryOutputSamplingRate() const
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002840{
Andy Hung954b9712023-08-28 18:36:53 -07002841 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002842 IAfPlaybackThread* const thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002843 return thread != NULL ? thread->sampleRate() : 0;
2844}
2845
Andy Hungcdd80ef2023-07-17 11:37:26 -07002846size_t AudioFlinger::getPrimaryOutputFrameCount() const
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002847{
Andy Hung954b9712023-08-28 18:36:53 -07002848 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002849 IAfPlaybackThread* const thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002850 return thread != NULL ? thread->frameCountHAL() : 0;
2851}
2852
2853// ----------------------------------------------------------------------------
2854
Andy Hung6f248bb2018-01-23 14:04:37 -08002855status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002856{
2857 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002858 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002859 return PERMISSION_DENIED;
2860 }
Andy Hung954b9712023-08-28 18:36:53 -07002861 audio_utils::lock_guard _l(mutex());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002862 if (mIsDeviceTypeKnown) {
2863 return INVALID_OPERATION;
2864 }
2865 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002866 mTotalMemory = totalMemory;
2867 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2868 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2869 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2870 // though actual setting is determined through device configuration.
2871 constexpr int64_t GB = 1024 * 1024 * 1024;
2872 mClientSharedHeapSize =
2873 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2874 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2875 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2876 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2877 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002878 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002879
2880 // TODO: Cache the client shared heap size in a persistent property.
2881 // It's possible that a native process or Java service or app accesses audioserver
2882 // after it is registered by system server, but before AudioService updates
2883 // the memory info. This would occur immediately after boot or an audioserver
2884 // crash and restore. Before update from AudioService, the client would get the
2885 // minimum heap size.
2886
2887 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2888 (isLowRamDevice ? "true" : "false"),
2889 (long long)mTotalMemory,
2890 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002891 return NO_ERROR;
2892}
2893
Andy Hung6f248bb2018-01-23 14:04:37 -08002894size_t AudioFlinger::getClientSharedHeapSize() const
2895{
2896 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2897 if (heapSizeInBytes != 0) { // read-only property overrides all.
2898 return heapSizeInBytes;
2899 }
2900 return mClientSharedHeapSize;
2901}
2902
Mikhail Naganovdea53042018-04-26 13:10:21 -07002903status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2904{
2905 ALOGV(__func__);
2906
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002907 status_t status = AudioValidator::validateAudioPortConfig(*config);
2908 if (status != NO_ERROR) {
2909 return status;
2910 }
2911
Mikhail Naganovdea53042018-04-26 13:10:21 -07002912 audio_module_handle_t module;
2913 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2914 module = config->ext.device.hw_module;
2915 } else {
2916 module = config->ext.mix.hw_module;
2917 }
2918
Andy Hung954b9712023-08-28 18:36:53 -07002919 audio_utils::lock_guard _l(mutex());
2920 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovdea53042018-04-26 13:10:21 -07002921 ssize_t index = mAudioHwDevs.indexOfKey(module);
2922 if (index < 0) {
2923 ALOGW("%s() bad hw module %d", __func__, module);
2924 return BAD_VALUE;
2925 }
2926
2927 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2928 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2929}
2930
Eric Laurent93c3d412014-08-01 14:48:35 -07002931audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2932{
Andy Hung954b9712023-08-28 18:36:53 -07002933 audio_utils::lock_guard _l(mutex());
Eric Laurentfa90e842014-10-17 18:12:31 -07002934
2935 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2936 if (index >= 0) {
2937 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2938 mHwAvSyncIds.valueAt(index), sessionId);
2939 return mHwAvSyncIds.valueAt(index);
2940 }
2941
Eric Laurent00abf0d2020-04-22 19:28:22 -07002942 sp<DeviceHalInterface> dev;
2943 {
Andy Hung954b9712023-08-28 18:36:53 -07002944 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002945 if (mPrimaryHardwareDev == nullptr) {
2946 return AUDIO_HW_SYNC_INVALID;
2947 }
Andy Hunge3748872023-08-30 19:05:16 -07002948 dev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07002949 }
2950 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002951 return AUDIO_HW_SYNC_INVALID;
2952 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002953
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002954 error::Result<audio_hw_sync_t> result = dev->getHwAvSync();
2955 if (!result.ok()) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002956 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2957 return AUDIO_HW_SYNC_INVALID;
2958 }
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002959 audio_hw_sync_t value = VALUE_OR_FATAL(result);
Eric Laurentfa90e842014-10-17 18:12:31 -07002960
2961 // allow only one session for a given HW A/V sync ID.
2962 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002963 if (mHwAvSyncIds.valueAt(i) == value) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002964 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2965 value, mHwAvSyncIds.keyAt(i));
2966 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002967 break;
2968 }
2969 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002970
2971 mHwAvSyncIds.add(sessionId, value);
2972
2973 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07002974 const sp<IAfPlaybackThread> thread = mPlaybackThreads.valueAt(i);
Eric Laurentfa90e842014-10-17 18:12:31 -07002975 uint32_t sessions = thread->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07002976 if (sessions & IAfThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002977 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002978 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002979 String8 keyValuePairs = param.toString();
2980 thread->setParameters(keyValuePairs);
2981 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07002982 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002983 break;
2984 }
2985 }
2986
2987 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2988 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002989}
2990
Eric Laurent72e3f392015-05-20 14:43:50 -07002991status_t AudioFlinger::systemReady()
2992{
Andy Hung954b9712023-08-28 18:36:53 -07002993 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07002994 ALOGI("%s", __FUNCTION__);
2995 if (mSystemReady) {
2996 ALOGW("%s called twice", __FUNCTION__);
2997 return NO_ERROR;
2998 }
2999 mSystemReady = true;
3000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003001 IAfThreadBase* const thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent72e3f392015-05-20 14:43:50 -07003002 thread->systemReady();
3003 }
3004 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003005 IAfThreadBase* const thread = mRecordThreads.valueAt(i).get();
Eric Laurent72e3f392015-05-20 14:43:50 -07003006 thread->systemReady();
3007 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003008 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003009 IAfThreadBase* const thread = mMmapThreads.valueAt(i).get();
Eric Laurentd66d7a12021-07-13 13:35:32 +02003010 thread->systemReady();
3011 }
Vlad Popae8d99472022-06-30 16:02:48 +02003012
3013 // Java services are ready, so we can create a reference to AudioService
3014 getOrCreateAudioManager();
3015
Eric Laurent72e3f392015-05-20 14:43:50 -07003016 return NO_ERROR;
3017}
3018
Vlad Popae8d99472022-06-30 16:02:48 +02003019sp<IAudioManager> AudioFlinger::getOrCreateAudioManager()
3020{
3021 if (mAudioManager.load() == nullptr) {
3022 // use checkService() to avoid blocking
3023 sp<IBinder> binder =
3024 defaultServiceManager()->checkService(String16(kAudioServiceName));
3025 if (binder != nullptr) {
3026 mAudioManager = interface_cast<IAudioManager>(binder);
3027 } else {
3028 ALOGE("%s(): binding to audio service failed.", __func__);
3029 }
3030 }
3031 return mAudioManager.load();
3032}
3033
Andy Hungcdd80ef2023-07-17 11:37:26 -07003034status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const
jiabin46a76fa2018-01-05 10:18:21 -08003035{
Andy Hung954b9712023-08-28 18:36:53 -07003036 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07003037 status_t status = INVALID_OPERATION;
3038
3039 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Shunkai Yaoed624a72022-12-12 06:11:46 +00003040 std::vector<audio_microphone_characteristic_t> mics;
Eric Laurent00abf0d2020-04-22 19:28:22 -07003041 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
3042 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
3043 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
3044 mHardwareStatus = AUDIO_HW_IDLE;
3045 if (devStatus == NO_ERROR) {
Eric Laurent00abf0d2020-04-22 19:28:22 -07003046 // report success if at least one HW module supports the function.
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08003047 std::transform(mics.begin(), mics.end(), std::back_inserter(*microphones), [](auto& mic)
3048 {
3049 auto microphone =
3050 legacy2aidl_audio_microphone_characteristic_t_MicrophoneInfoFw(mic);
3051 return microphone.ok() ? microphone.value() : media::MicrophoneInfoFw{};
3052 });
Eric Laurent00abf0d2020-04-22 19:28:22 -07003053 status = NO_ERROR;
3054 }
3055 }
3056
jiabin9ff780e2018-03-19 18:19:52 -07003057 return status;
jiabin46a76fa2018-01-05 10:18:21 -08003058}
3059
Andy Hung954b9712023-08-28 18:36:53 -07003060// setAudioHwSyncForSession_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003061void AudioFlinger::setAudioHwSyncForSession_l(
3062 IAfPlaybackThread* const thread, audio_session_t sessionId)
Eric Laurentfa90e842014-10-17 18:12:31 -07003063{
3064 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
3065 if (index >= 0) {
3066 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
3067 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
3068 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07003069 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07003070 String8 keyValuePairs = param.toString();
3071 thread->setParameters(keyValuePairs);
3072 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07003073 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07003074 }
3075}
3076
3077
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003078// ----------------------------------------------------------------------------
3079
Eric Laurent83b88082014-06-20 18:31:16 -07003080
Andy Hung87c693c2023-07-06 20:56:16 -07003081sp<IAfThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07003082 audio_io_handle_t *output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003083 audio_config_t *halConfig,
Andy Hung920f6572022-10-06 12:09:49 -07003084 audio_config_base_t *mixerConfig,
jiabin43810402019-10-24 14:58:31 -07003085 audio_devices_t deviceType,
3086 const String8& address,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003087 audio_output_flags_t *flags,
Haofan Wangf6e304f2024-07-09 23:06:58 -07003088 const audio_attributes_t attributes)
Eric Laurent83b88082014-06-20 18:31:16 -07003089{
jiabin43810402019-10-24 14:58:31 -07003090 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07003091 if (outHwDev == NULL) {
Eric Laurente28c66d2022-01-21 13:40:41 +01003092 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07003093 }
3094
Eric Laurentcf2c0212014-07-25 16:20:43 -07003095 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08003096 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
3097 } else {
3098 // Audio Policy does not currently request a specific output handle.
3099 // If this is ever needed, see openInput_l() for example code.
3100 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
Eric Laurente28c66d2022-01-21 13:40:41 +01003101 return nullptr;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003102 }
Eric Laurent83b88082014-06-20 18:31:16 -07003103
3104 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Phil Burk062e67a2015-02-11 13:40:50 -08003105 AudioStreamOut *outputStream = NULL;
Haofan Wangf6e304f2024-07-09 23:06:58 -07003106
3107 playback_track_metadata_v7_t trackMetadata;
3108 trackMetadata.base.usage = attributes.usage;
3109
Phil Burk062e67a2015-02-11 13:40:50 -08003110 status_t status = outHwDev->openOutputStream(
3111 &outputStream,
3112 *output,
jiabin43810402019-10-24 14:58:31 -07003113 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08003114 flags,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003115 halConfig,
Haofan Wangf6e304f2024-07-09 23:06:58 -07003116 address.c_str(),
3117 {trackMetadata});
Eric Laurent83b88082014-06-20 18:31:16 -07003118
3119 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07003120
Phil Burk062e67a2015-02-11 13:40:50 -08003121 if (status == NO_ERROR) {
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003122 if (*flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003123 const sp<IAfMmapPlaybackThread> thread = IAfMmapPlaybackThread::create(
3124 this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003125 mMmapThreads.add(*output, thread);
3126 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
3127 *output, thread.get());
3128 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003129 } else {
Andy Hung87c693c2023-07-06 20:56:16 -07003130 sp<IAfPlaybackThread> thread;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003131 if (*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003132 thread = IAfPlaybackThread::createBitPerfectThread(
3133 this, outputStream, *output, mSystemReady);
jiabinc658e452022-10-21 20:52:21 +00003134 ALOGV("%s() created bit-perfect output: ID %d thread %p",
3135 __func__, *output, thread.get());
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003136 } else if (*flags & AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003137 thread = IAfPlaybackThread::createSpatializerThread(this, outputStream, *output,
Eric Laurentb3f315a2021-07-13 15:09:05 +02003138 mSystemReady, mixerConfig);
Eric Laurente28c66d2022-01-21 13:40:41 +01003139 ALOGV("openOutput_l() created spatializer output: ID %d thread %p",
Eric Laurentb3f315a2021-07-13 15:09:05 +02003140 *output, thread.get());
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003141 } else if (*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003142 thread = IAfPlaybackThread::createOffloadThread(this, outputStream, *output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07003143 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003144 ALOGV("openOutput_l() created offload output: ID %d thread %p",
3145 *output, thread.get());
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003146 } else if ((*flags & AUDIO_OUTPUT_FLAG_DIRECT)
Andy Hung81994d62023-07-20 21:44:14 -07003147 || !IAfThreadBase::isValidPcmSinkFormat(halConfig->format)
3148 || !IAfThreadBase::isValidPcmSinkChannelMask(halConfig->channel_mask)) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003149 thread = IAfPlaybackThread::createDirectOutputThread(this, outputStream, *output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07003150 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003151 ALOGV("openOutput_l() created direct output: ID %d thread %p",
3152 *output, thread.get());
3153 } else {
Andy Hungee58e4a2023-07-07 13:47:37 -07003154 thread = IAfPlaybackThread::createMixerThread(
3155 this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003156 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
3157 *output, thread.get());
3158 }
3159 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01003160 struct audio_patch patch;
Andy Hungb6692eb2023-07-13 16:52:46 -07003161 mPatchPanel->notifyStreamOpened(outHwDev, *output, &patch);
Eric Laurent74c38dc2020-12-23 18:19:44 +01003162 if (thread->isMsdDevice()) {
3163 thread->setDownStreamPatch(&patch);
3164 }
Eric Laurent50d72582022-12-20 20:20:23 +01003165 thread->setBluetoothVariableLatencyEnabled(mBluetoothLatencyModesEnabled.load());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003166 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003167 }
Eric Laurent83b88082014-06-20 18:31:16 -07003168 }
3169
Eric Laurente28c66d2022-01-21 13:40:41 +01003170 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07003171}
3172
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003173status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
3174 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003176 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
3177 aidl2legacy_int32_t_audio_module_handle_t(request.module));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003178 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003179 aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003180 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003181 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003182 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
3183 aidl2legacy_DeviceDescriptorBase(request.device));
3184 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08003185 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Haofan Wangf6e304f2024-07-09 23:06:58 -07003186 audio_attributes_t attributes = VALUE_OR_RETURN_STATUS(
3187 aidl2legacy_AudioAttributes_audio_attributes_t(request.attributes));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003188
3189 audio_io_handle_t output;
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003190
jiabin43810402019-10-24 14:58:31 -07003191 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003192 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08003193 this, module,
jiabin43810402019-10-24 14:58:31 -07003194 device->toString().c_str(),
Eric Laurentf1f22e72021-07-13 14:04:14 +02003195 halConfig.sample_rate,
3196 halConfig.format,
3197 halConfig.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07003198 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199
jiabin43810402019-10-24 14:58:31 -07003200 audio_devices_t deviceType = device->type();
3201 const String8 address = String8(device->address().c_str());
3202
3203 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003204 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003206
Andy Hung954b9712023-08-28 18:36:53 -07003207 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208
Andy Hung87c693c2023-07-06 20:56:16 -07003209 const sp<IAfThreadBase> thread = openOutput_l(module, &output, &halConfig,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11003210 &mixerConfig, deviceType, address, &flags, attributes);
Eric Laurent83b88082014-06-20 18:31:16 -07003211 if (thread != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07003212 uint32_t latencyMs = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003213 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
Andy Hung87c693c2023-07-06 20:56:16 -07003214 const auto playbackThread = thread->asIAfPlaybackThread();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003215 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216
Eric Laurent6acd1d42017-01-04 14:23:29 -08003217 // notify client processes of the new output creation
Andy Hungab65b182023-09-06 19:41:47 -07003218 playbackThread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003219
Eric Laurent00abf0d2020-04-22 19:28:22 -07003220 // the first primary output opened designates the primary hw device if no HW module
3221 // named "primary" was already loaded.
Andy Hung954b9712023-08-28 18:36:53 -07003222 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07003223 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08003224 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003225 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07003226
Eric Laurent6acd1d42017-01-04 14:23:29 -08003227 mHardwareStatus = AUDIO_HW_SET_MODE;
Andy Hunge3748872023-08-30 19:05:16 -07003228 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003229 mHardwareStatus = AUDIO_HW_IDLE;
3230 }
3231 } else {
Andy Hungab65b182023-09-06 19:41:47 -07003232 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003233 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003234 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003235 response->config = VALUE_OR_RETURN_STATUS(
3236 legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003237 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08003238 response->flags = VALUE_OR_RETURN_STATUS(
3239 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07003240 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 }
3242
Eric Laurentcf2c0212014-07-25 16:20:43 -07003243 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244}
3245
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003246audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
3247 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248{
Andy Hung954b9712023-08-28 18:36:53 -07003249 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003250 IAfPlaybackThread* const thread1 = checkMixerThread_l(output1);
3251 IAfPlaybackThread* const thread2 = checkMixerThread_l(output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252
3253 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003254 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
3255 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07003256 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 }
3258
Glenn Kasteneeecb982016-02-26 10:44:04 -08003259 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Andy Hungee58e4a2023-07-07 13:47:37 -07003260 const sp<IAfDuplicatingThread> thread = IAfDuplicatingThread::create(
3261 this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 thread->addOutputTrack(thread2);
3263 mPlaybackThreads.add(id, thread);
3264 // notify client processes of the new output creation
Andy Hungab65b182023-09-06 19:41:47 -07003265 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 return id;
3267}
3268
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003269status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270{
Glenn Kastend96c5722012-04-25 13:44:49 -07003271 return closeOutput_nonvirtual(output);
3272}
3273
3274status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
3275{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 // keep strong reference on the playback thread so that
3277 // it is not destroyed while exit() is executed
Andy Hung87c693c2023-07-06 20:56:16 -07003278 sp<IAfPlaybackThread> playbackThread;
Andy Hung7aa7d102023-07-07 15:58:48 -07003279 sp<IAfMmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 {
Andy Hung954b9712023-08-28 18:36:53 -07003281 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003282 playbackThread = checkPlaybackThread_l(output);
3283 if (playbackThread != NULL) {
3284 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285
Andy Hungdc099c22018-09-18 13:46:39 -07003286 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07003287
Andy Hung87c693c2023-07-06 20:56:16 -07003288 if (playbackThread->type() == IAfThreadBase::MIXER) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003289 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3290 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Andy Hung87c693c2023-07-06 20:56:16 -07003291 IAfDuplicatingThread* const dupThread =
3292 mPlaybackThreads.valueAt(i)->asIAfDuplicatingThread().get();
3293 dupThread->removeOutputTrack(playbackThread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 }
3296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297
3298
Eric Laurent6acd1d42017-01-04 14:23:29 -08003299 mPlaybackThreads.removeItem(output);
Shunkai Yao517fc2a2024-03-19 04:31:47 +00003300 // Save AUDIO_SESSION_OUTPUT_MIX effect to orphan chains
3301 // Output Mix Effect session is used to manage Music Effect by AudioPolicy Manager.
3302 // It exists across all playback threads.
3303 if (playbackThread->type() == IAfThreadBase::MIXER
3304 || playbackThread->type() == IAfThreadBase::OFFLOAD
3305 || playbackThread->type() == IAfThreadBase::SPATIALIZER) {
3306 sp<IAfEffectChain> mixChain;
3307 {
3308 audio_utils::scoped_lock sl(playbackThread->mutex());
3309 mixChain = playbackThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3310 if (mixChain != nullptr) {
3311 ALOGW("%s() output %d moving mix session to orphans", __func__, output);
3312 playbackThread->removeEffectChain_l(mixChain);
3313 }
3314 }
3315 if (mixChain != nullptr) {
3316 putOrphanEffectChain_l(mixChain);
3317 }
3318 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003319 // save all effects to the default thread
3320 if (mPlaybackThreads.size()) {
Andy Hung87c693c2023-07-06 20:56:16 -07003321 IAfPlaybackThread* const dstThread =
3322 checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
Eric Laurent6acd1d42017-01-04 14:23:29 -08003323 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003324 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Andy Hunge0f5ec52023-08-30 11:26:06 -07003325 // Use scoped_lock to avoid deadlock order issues with duplicating threads.
3326 audio_utils::scoped_lock sl(dstThread->mutex(), playbackThread->mutex());
Andy Hung6ac17eb2023-06-20 18:56:17 -07003327 Vector<sp<IAfEffectChain>> effectChains = playbackThread->getEffectChains_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003328 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003329 moveEffectChain_ll(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07003330 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 }
3333 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003334 } else {
Andy Hung7aa7d102023-07-07 15:58:48 -07003335 const sp<IAfMmapThread> mt = checkMmapThread_l(output);
3336 mmapThread = mt ? mt->asIAfMmapPlaybackThread().get() : nullptr;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003337 if (mmapThread == 0) {
3338 return BAD_VALUE;
3339 }
Andy Hungdc099c22018-09-18 13:46:39 -07003340 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003341 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08003342 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 }
Andy Hungab65b182023-09-06 19:41:47 -07003344 ioConfigChanged_l(AUDIO_OUTPUT_CLOSED, sp<AudioIoDescriptor>::make(output));
Andy Hungb6692eb2023-07-13 16:52:46 -07003345 mPatchPanel->notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08003347 // The thread entity (active unit of execution) is no longer running here,
Andy Hung87c693c2023-07-06 20:56:16 -07003348 // but the IAfThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349
Eric Laurent6acd1d42017-01-04 14:23:29 -08003350 if (playbackThread != 0) {
3351 playbackThread->exit();
3352 if (!playbackThread->isDuplicating()) {
3353 closeOutputFinish(playbackThread);
3354 }
3355 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08003356 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003357 mmapThread->exit();
3358 AudioStreamOut *out = mmapThread->clearOutput();
3359 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3360 // from now on thread->mOutput is NULL
3361 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 }
3363 return NO_ERROR;
3364}
3365
Andy Hungc2cf7ec2023-08-30 18:19:00 -07003366/* static */
Andy Hung87c693c2023-07-06 20:56:16 -07003367void AudioFlinger::closeOutputFinish(const sp<IAfPlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003368{
3369 AudioStreamOut *out = thread->clearOutput();
3370 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3371 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07003372 delete out;
3373}
3374
Andy Hung87c693c2023-07-06 20:56:16 -07003375void AudioFlinger::closeThreadInternal_l(const sp<IAfPlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003376{
Andy Hung87c693c2023-07-06 20:56:16 -07003377 mPlaybackThreads.removeItem(thread->id());
Eric Laurent83b88082014-06-20 18:31:16 -07003378 thread->exit();
3379 closeOutputFinish(thread);
3380}
3381
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003382status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383{
Andy Hung954b9712023-08-28 18:36:53 -07003384 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003385 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386
3387 if (thread == NULL) {
3388 return BAD_VALUE;
3389 }
3390
Steve Block3856b092011-10-20 11:56:00 +01003391 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 thread->suspend();
3393
3394 return NO_ERROR;
3395}
3396
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003397status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398{
Andy Hung954b9712023-08-28 18:36:53 -07003399 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003400 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401
3402 if (thread == NULL) {
3403 return BAD_VALUE;
3404 }
3405
Steve Block3856b092011-10-20 11:56:00 +01003406 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407
3408 thread->restore();
3409
3410 return NO_ERROR;
3411}
3412
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003413status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
3414 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415{
Andy Hung954b9712023-08-28 18:36:53 -07003416 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07003417
Mikhail Naganov21a32ec2021-07-08 14:40:12 -07003418 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
3419 aidl2legacy_AudioDeviceTypeAddress(request.device));
3420 if (device.mType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003421 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07003422 }
3423
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003424 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
3425 aidl2legacy_int32_t_audio_io_handle_t(request.input));
3426 audio_config_t config = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003427 aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003428
Andy Hung87c693c2023-07-06 20:56:16 -07003429 const sp<IAfThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003430 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
3431 &input,
3432 &config,
3433 device.mType,
3434 device.address().c_str(),
Mikhail Naganovddceecc2021-09-03 13:58:56 -07003435 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08003436 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003437 AUDIO_DEVICE_NONE,
3438 String8{});
3439
3440 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003441 response->config = VALUE_OR_RETURN_STATUS(
3442 legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003443 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07003444
3445 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07003446 // notify client processes of the new input creation
Andy Hungab65b182023-09-06 19:41:47 -07003447 thread->ioConfigChanged_l(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003448 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003450 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07003451}
Dima Zavin799a70e2011-04-18 16:57:27 -07003452
Andy Hung87c693c2023-07-06 20:56:16 -07003453sp<IAfThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003454 audio_io_handle_t *input,
3455 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08003456 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003457 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003458 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003459 audio_input_flags_t flags,
3460 audio_devices_t outputDevice,
3461 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07003462{
Glenn Kastene7d66712015-03-05 13:46:52 -08003463 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003464 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003465 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07003466 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003467 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003468
Glenn Kasteneeecb982016-02-26 10:44:04 -08003469 // Audio Policy can request a specific handle for hardware hotword.
3470 // The goal here is not to re-open an already opened input.
3471 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07003472 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08003473 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3474 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
3475 ALOGE("openInput_l() requested input handle %d is invalid", *input);
3476 return 0;
3477 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
3478 // This should not happen in a transient state with current design.
3479 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
3480 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003481 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07003482
Dean Wheatley6c009512023-10-23 09:34:14 +11003483 AudioStreamIn *inputStream = nullptr;
3484 status_t status = inHwDev->openInputStream(
3485 &inputStream,
3486 *input,
Mikhail Naganovf558e022016-11-14 17:45:17 -08003487 devices,
Glenn Kastenec40d282014-07-15 15:31:26 -07003488 flags,
Dean Wheatley6c009512023-10-23 09:34:14 +11003489 config,
3490 address,
3491 source,
3492 outputDevice,
3493 outputDeviceAddress.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494
Dean Wheatley6c009512023-10-23 09:34:14 +11003495 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003496 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003497 const sp<IAfMmapCaptureThread> thread =
Andy Hungee58e4a2023-07-07 13:47:37 -07003498 IAfMmapCaptureThread::create(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003499 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08003500 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
3501 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003502 return thread;
3503 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003504 // Start record thread
Andy Hung87c693c2023-07-06 20:56:16 -07003505 // IAfRecordThread requires both input and output device indication
3506 // to forward to audio pre processing modules
3507 const sp<IAfRecordThread> thread =
3508 IAfRecordThread::create(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003509 mRecordThreads.add(*input, thread);
3510 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
3511 return thread;
3512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 }
3514
Eric Laurentcf2c0212014-07-25 16:20:43 -07003515 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 return 0;
3517}
3518
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003519status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520{
Glenn Kastend96c5722012-04-25 13:44:49 -07003521 return closeInput_nonvirtual(input);
3522}
3523
3524status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
3525{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526 // keep strong reference on the record thread so that
3527 // it is not destroyed while exit() is executed
Andy Hung87c693c2023-07-06 20:56:16 -07003528 sp<IAfRecordThread> recordThread;
Andy Hung7aa7d102023-07-07 15:58:48 -07003529 sp<IAfMmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 {
Andy Hung954b9712023-08-28 18:36:53 -07003531 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003532 recordThread = checkRecordThread_l(input);
3533 if (recordThread != 0) {
3534 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535
Andy Hungdc099c22018-09-18 13:46:39 -07003536 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07003537
Eric Laurent6acd1d42017-01-04 14:23:29 -08003538 // If we still have effect chains, it means that a client still holds a handle
3539 // on at least one effect. We must either move the chain to an existing thread with the
3540 // same session ID or put it aside in case a new record thread is opened for a
3541 // new capture on the same session
Andy Hung6ac17eb2023-06-20 18:56:17 -07003542 sp<IAfEffectChain> chain;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003543 {
Andy Hungc5007f82023-08-29 14:26:09 -07003544 audio_utils::lock_guard _sl(recordThread->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003545 const Vector<sp<IAfEffectChain>> effectChains = recordThread->getEffectChains_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003546 // Note: maximum one chain per record thread
3547 if (effectChains.size() != 0) {
3548 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003549 }
3550 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003551 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003552 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003553 // This should only happen in case of overlap between one thread tear down and the
3554 // creation of its replacement
3555 size_t i;
3556 for (i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003557 const sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003558 if (t == recordThread) {
3559 continue;
3560 }
3561 if (t->hasAudioSession(chain->sessionId()) != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07003562 audio_utils::lock_guard _l2(t->mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003563 ALOGV("closeInput() found thread %d for effect session %d",
3564 t->id(), chain->sessionId());
3565 t->addEffectChain_l(chain);
3566 break;
3567 }
3568 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003569 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003570 if (i == mRecordThreads.size()) {
3571 putOrphanEffectChain_l(chain);
3572 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003573 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003574 mRecordThreads.removeItem(input);
3575 } else {
Andy Hung7aa7d102023-07-07 15:58:48 -07003576 const sp<IAfMmapThread> mt = checkMmapThread_l(input);
3577 mmapThread = mt ? mt->asIAfMmapCaptureThread().get() : nullptr;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003578 if (mmapThread == 0) {
3579 return BAD_VALUE;
3580 }
Andy Hungdc099c22018-09-18 13:46:39 -07003581 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003582 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003583 }
Andy Hungab65b182023-09-06 19:41:47 -07003584 ioConfigChanged_l(AUDIO_INPUT_CLOSED, sp<AudioIoDescriptor>::make(input));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 }
Andy Hung954b9712023-08-28 18:36:53 -07003586 // FIXME: calling thread->exit() without mutex() held should not be needed anymore now that
Eric Laurent83b88082014-06-20 18:31:16 -07003587 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003588 if (recordThread != 0) {
3589 closeInputFinish(recordThread);
3590 } else if (mmapThread != 0) {
3591 mmapThread->exit();
3592 AudioStreamIn *in = mmapThread->clearInput();
3593 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3594 // from now on thread->mInput is NULL
3595 delete in;
3596 }
Eric Laurent83b88082014-06-20 18:31:16 -07003597 return NO_ERROR;
3598}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003599
Andy Hung87c693c2023-07-06 20:56:16 -07003600void AudioFlinger::closeInputFinish(const sp<IAfRecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003601{
3602 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003603 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003604 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003605 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003606 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003607}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608
Andy Hung87c693c2023-07-06 20:56:16 -07003609void AudioFlinger::closeThreadInternal_l(const sp<IAfRecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003610{
Andy Hung87c693c2023-07-06 20:56:16 -07003611 mRecordThreads.removeItem(thread->id());
Eric Laurent83b88082014-06-20 18:31:16 -07003612 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613}
3614
jiabinc44b3462022-12-08 12:52:31 -08003615status_t AudioFlinger::invalidateTracks(const std::vector<audio_port_handle_t> &portIds) {
Andy Hung954b9712023-08-28 18:36:53 -07003616 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003617 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618
jiabinc44b3462022-12-08 12:52:31 -08003619 std::set<audio_port_handle_t> portIdSet(portIds.begin(), portIds.end());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003621 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
jiabinc44b3462022-12-08 12:52:31 -08003622 thread->invalidateTracks(portIdSet);
3623 if (portIdSet.empty()) {
3624 return NO_ERROR;
3625 }
Eric Laurentde070132010-07-13 04:45:46 -07003626 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003627 for (size_t i = 0; i < mMmapThreads.size(); i++) {
jiabinc44b3462022-12-08 12:52:31 -08003628 mMmapThreads[i]->invalidateTracks(portIdSet);
3629 if (portIdSet.empty()) {
3630 return NO_ERROR;
3631 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 return NO_ERROR;
3634}
3635
3636
Glenn Kasteneeecb982016-02-26 10:44:04 -08003637audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638{
Glenn Kasten9d003132016-04-06 14:38:09 -07003639 // This is a binder API, so a malicious client could pass in a bad parameter.
3640 // Check for that before calling the internal API nextUniqueId().
3641 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3642 ALOGE("newAudioUniqueId invalid use %d", use);
3643 return AUDIO_UNIQUE_ID_ALLOCATE;
3644 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003645 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646}
3647
Andy Hung8b0bfd92019-12-23 13:11:11 -08003648void AudioFlinger::acquireAudioSessionId(
3649 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003650{
Andy Hung954b9712023-08-28 18:36:53 -07003651 audio_utils::lock_guard _l(mutex());
Glenn Kastenbb001922012-02-03 11:10:26 -08003652 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003653 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003654 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003655 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3656 caller = pid; // check must match releaseAudioSessionId()
3657 }
3658 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3659 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003660 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003661
Eric Laurent021cf962014-05-13 10:18:14 -07003662 {
Andy Hung954b9712023-08-28 18:36:53 -07003663 audio_utils::lock_guard _cl(clientMutex());
Eric Laurent021cf962014-05-13 10:18:14 -07003664 // Ignore requests received from processes not known as notification client. The request
3665 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3666 // called from a different pid leaving a stale session reference. Also we don't know how
3667 // to clear this reference if the client process dies.
Andy Hung05b0ffe2024-08-30 17:18:37 -07003668 if (mNotificationClients.count(caller) == 0) {
Eric Laurent021cf962014-05-13 10:18:14 -07003669 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3670 return;
3671 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003672 }
3673
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003674 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003675 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003676 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003677 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3678 ref->mCnt++;
3679 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003680 return;
3681 }
3682 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003683 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003684 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003685}
3686
Glenn Kastend848eb42016-03-08 13:42:11 -08003687void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003688{
Andy Hung6ac17eb2023-06-20 18:56:17 -07003689 std::vector<sp<IAfEffectModule>> removedEffects;
Eric Laurent6c796322019-04-09 14:13:17 -07003690 {
Andy Hung954b9712023-08-28 18:36:53 -07003691 audio_utils::lock_guard _l(mutex());
Eric Laurent6c796322019-04-09 14:13:17 -07003692 pid_t caller = IPCThreadState::self()->getCallingPid();
3693 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3694 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003695 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3696 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003697 }
Eric Laurent6c796322019-04-09 14:13:17 -07003698 size_t num = mAudioSessionRefs.size();
3699 for (size_t i = 0; i < num; i++) {
3700 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3701 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3702 ref->mCnt--;
3703 ALOGV(" decremented refcount to %d", ref->mCnt);
3704 if (ref->mCnt == 0) {
3705 mAudioSessionRefs.removeAt(i);
3706 delete ref;
Andy Hung6ac17eb2023-06-20 18:56:17 -07003707 std::vector<sp<IAfEffectModule>> effects = purgeStaleEffects_l();
Eric Laurent6c796322019-04-09 14:13:17 -07003708 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3709 }
3710 goto Exit;
3711 }
3712 }
3713 // If the caller is audioserver it is likely that the session being released was acquired
3714 // on behalf of a process not in notification clients and we ignore the warning.
3715 ALOGW_IF(!isAudioServerUid(callerUid),
3716 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003717 }
Eric Laurent6c796322019-04-09 14:13:17 -07003718
3719Exit:
3720 for (auto& effect : removedEffects) {
3721 effect->updatePolicyState();
3722 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003723}
3724
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003725bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3726{
3727 size_t num = mAudioSessionRefs.size();
3728 for (size_t i = 0; i < num; i++) {
3729 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3730 if (ref->mSessionid == audioSession) {
3731 return true;
3732 }
3733 }
3734 return false;
3735}
3736
Andy Hung6ac17eb2023-06-20 18:56:17 -07003737std::vector<sp<IAfEffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003738
Steve Block3856b092011-10-20 11:56:00 +01003739 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003740
Andy Hung87c693c2023-07-06 20:56:16 -07003741 Vector<sp<IAfEffectChain>> chains;
Andy Hung6ac17eb2023-06-20 18:56:17 -07003742 std::vector< sp<IAfEffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003743
3744 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003745 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003746 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003747 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3748 for (size_t j = 0; j < threadChains.size(); j++) {
3749 sp<IAfEffectChain> ec = threadChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003750 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003751 chains.push(ec);
3752 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003753 }
3754 }
Eric Laurent6c796322019-04-09 14:13:17 -07003755
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003756 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003757 sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003758 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003759 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3760 for (size_t j = 0; j < threadChains.size(); j++) {
3761 sp<IAfEffectChain> ec = threadChains[j];
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003762 chains.push(ec);
3763 }
3764 }
3765
Eric Laurent6c796322019-04-09 14:13:17 -07003766 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003767 const sp<IAfMmapThread> t = mMmapThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003768 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003769 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3770 for (size_t j = 0; j < threadChains.size(); j++) {
3771 sp<IAfEffectChain> ec = threadChains[j];
Eric Laurent6c796322019-04-09 14:13:17 -07003772 chains.push(ec);
3773 }
3774 }
3775
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003776 for (size_t i = 0; i < chains.size(); i++) {
Andy Hung920f6572022-10-06 12:09:49 -07003777 // clang-tidy suggests const ref
Andy Hung6ac17eb2023-06-20 18:56:17 -07003778 sp<IAfEffectChain> ec = chains[i]; // NOLINT(performance-unnecessary-copy-initialization)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003779 int sessionid = ec->sessionId();
Andy Hung99b1ba62023-07-14 11:00:08 -07003780 const auto t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003781 if (t == 0) {
3782 continue;
3783 }
3784 size_t numsessionrefs = mAudioSessionRefs.size();
3785 bool found = false;
3786 for (size_t k = 0; k < numsessionrefs; k++) {
3787 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003788 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003789 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003790 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003791 found = true;
3792 break;
3793 }
3794 }
3795 if (!found) {
Andy Hungc5007f82023-08-29 14:26:09 -07003796 audio_utils::lock_guard _l(t->mutex());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003797 // remove all effects from the chain
Andy Hung6ac17eb2023-06-20 18:56:17 -07003798 while (ec->numberOfEffects()) {
3799 sp<IAfEffectModule> effect = ec->getEffectModule(0);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003800 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003801 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003802 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003803 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003804 }
Eric Laurent6c796322019-04-09 14:13:17 -07003805 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003806 }
3807 }
3808 }
Eric Laurent6c796322019-04-09 14:13:17 -07003809 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003810}
3811
François Gaffie1b4753e2023-02-06 10:36:33 +01003812std::vector< sp<IAfEffectModule> > AudioFlinger::purgeOrphanEffectChains_l()
3813{
3814 ALOGV("purging stale effects from orphan chains");
3815 std::vector< sp<IAfEffectModule> > removedEffects;
3816 for (size_t index = 0; index < mOrphanEffectChains.size(); index++) {
3817 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
3818 audio_session_t session = mOrphanEffectChains.keyAt(index);
3819 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_DEVICE
3820 || session == AUDIO_SESSION_OUTPUT_STAGE) {
3821 continue;
3822 }
3823 size_t numSessionRefs = mAudioSessionRefs.size();
3824 bool found = false;
3825 for (size_t k = 0; k < numSessionRefs; k++) {
3826 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3827 if (ref->mSessionid == session) {
3828 ALOGV(" session %d still exists for %d with %d refs", session, ref->mPid,
3829 ref->mCnt);
3830 found = true;
3831 break;
3832 }
3833 }
3834 if (!found) {
3835 for (size_t i = 0; i < chain->numberOfEffects(); i++) {
3836 sp<IAfEffectModule> effect = chain->getEffectModule(i);
3837 removedEffects.push_back(effect);
3838 }
3839 }
3840 }
3841 for (auto& effect : removedEffects) {
3842 effect->unPin();
3843 updateOrphanEffectChains_l(effect);
3844 }
3845 return removedEffects;
3846}
3847
Andy Hung954b9712023-08-28 18:36:53 -07003848// dumpToThreadLog_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003849void AudioFlinger::dumpToThreadLog_l(const sp<IAfThreadBase> &thread)
Andy Hungdc099c22018-09-18 13:46:39 -07003850{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303851 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
Atneya Nair50ffdd12023-12-05 20:42:35 -08003852 constexpr auto PREFIX = "- ";
3853 if (com::android::media::audioserver::fdtostring_timeout_fix()) {
3854 using ::android::audio_utils::FdToString;
3855
3856 auto writer = OR_RETURN(FdToString::createWriter(PREFIX));
3857 thread->dump(writer.borrowFdUnsafe(), {} /* args */);
3858 mThreadLog.logs(-1 /* time */, FdToString::closeWriterAndGetString(std::move(writer)));
3859 } else {
3860 audio_utils::FdToStringOldImpl fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
3861 const int fd = fdToString.borrowFdUnsafe();
3862 if (fd >= 0) {
3863 thread->dump(fd, {} /* args */);
3864 mThreadLog.logs(-1 /* time */, fdToString.closeAndGetString());
3865 }
Andy Hungdc099c22018-09-18 13:46:39 -07003866 }
3867}
3868
Andy Hung954b9712023-08-28 18:36:53 -07003869// checkThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003870IAfThreadBase* AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
Glenn Kasteneeecb982016-02-26 10:44:04 -08003871{
Andy Hung87c693c2023-07-06 20:56:16 -07003872 IAfThreadBase* thread = checkMmapThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003873 if (thread == 0) {
3874 switch (audio_unique_id_get_use(ioHandle)) {
3875 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3876 thread = checkPlaybackThread_l(ioHandle);
3877 break;
3878 case AUDIO_UNIQUE_ID_USE_INPUT:
3879 thread = checkRecordThread_l(ioHandle);
3880 break;
3881 default:
3882 break;
3883 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003884 }
3885 return thread;
3886}
3887
Andy Hung954b9712023-08-28 18:36:53 -07003888// checkOutputThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003889sp<IAfThreadBase> AudioFlinger::checkOutputThread_l(audio_io_handle_t ioHandle) const
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003890{
3891 if (audio_unique_id_get_use(ioHandle) != AUDIO_UNIQUE_ID_USE_OUTPUT) {
3892 return nullptr;
3893 }
3894
Andy Hung87c693c2023-07-06 20:56:16 -07003895 sp<IAfThreadBase> thread = mPlaybackThreads.valueFor(ioHandle);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003896 if (thread == nullptr) {
3897 thread = mMmapThreads.valueFor(ioHandle);
3898 }
3899 return thread;
3900}
3901
Andy Hung954b9712023-08-28 18:36:53 -07003902// checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003903IAfPlaybackThread* AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904{
Glenn Kastena1117922012-01-26 10:53:32 -08003905 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906}
3907
Andy Hung954b9712023-08-28 18:36:53 -07003908// checkMixerThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003909IAfPlaybackThread* AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910{
Andy Hung87c693c2023-07-06 20:56:16 -07003911 IAfPlaybackThread * const thread = checkPlaybackThread_l(output);
3912 return thread != nullptr && thread->type() != IAfThreadBase::DIRECT ? thread : nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913}
3914
Andy Hung954b9712023-08-28 18:36:53 -07003915// checkRecordThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003916IAfRecordThread* AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917{
Glenn Kastena1117922012-01-26 10:53:32 -08003918 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919}
3920
Andy Hung954b9712023-08-28 18:36:53 -07003921// checkMmapThread_l() must be called with AudioFlinger::mutex() held
Andy Hung7aa7d102023-07-07 15:58:48 -07003922IAfMmapThread* AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003923{
3924 return mMmapThreads.valueFor(io).get();
3925}
3926
3927
Andy Hung954b9712023-08-28 18:36:53 -07003928// checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
Andy Hung6b137d12024-08-27 22:35:17 +00003929sp<VolumeInterface> AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const {
Andy Hung84074c62023-07-06 19:21:50 -07003930 sp<VolumeInterface> volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003931 if (volumeInterface == nullptr) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003932 IAfMmapThread* const mmapThread = mMmapThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003933 if (mmapThread != nullptr) {
3934 if (mmapThread->isOutput()) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003935 IAfMmapPlaybackThread* const mmapPlaybackThread =
3936 mmapThread->asIAfMmapPlaybackThread().get();
Eric Laurent7459b902017-04-19 18:10:41 -07003937 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003938 }
3939 }
3940 }
3941 return volumeInterface;
3942}
3943
Andy Hung84074c62023-07-06 19:21:50 -07003944std::vector<sp<VolumeInterface>> AudioFlinger::getAllVolumeInterfaces_l() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003945{
Andy Hung84074c62023-07-06 19:21:50 -07003946 std::vector<sp<VolumeInterface>> volumeInterfaces;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003947 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung84074c62023-07-06 19:21:50 -07003948 volumeInterfaces.push_back(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003949 }
3950 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3951 if (mMmapThreads.valueAt(i)->isOutput()) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003952 IAfMmapPlaybackThread* const mmapPlaybackThread =
3953 mMmapThreads.valueAt(i)->asIAfMmapPlaybackThread().get();
Andy Hung84074c62023-07-06 19:21:50 -07003954 volumeInterfaces.push_back(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003955 }
3956 }
3957 return volumeInterfaces;
3958}
3959
Glenn Kasteneeecb982016-02-26 10:44:04 -08003960audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961{
Glenn Kasten9d003132016-04-06 14:38:09 -07003962 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003963 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003964 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3965 for (int retry = 0; retry < maxRetries; retry++) {
3966 // The cast allows wraparound from max positive to min negative instead of abort
3967 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3968 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3969 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3970 // allow wrap by skipping 0 and -1 for session ids
3971 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3972 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3973 return (audio_unique_id_t) (base | use);
3974 }
3975 }
3976 // We have no way of recovering from wraparound
3977 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3978 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979}
3980
Andy Hung87c693c2023-07-06 20:56:16 -07003981IAfPlaybackThread* AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003982{
François Gaffie328a0a52024-06-25 11:48:09 +02003983 // The atomic ptr mPrimaryHardwareDev requires both the
3984 // AudioFlinger and the Hardware mutex for modification.
3985 // As we hold the AudioFlinger mutex, we access it
3986 // safely without the Hardware mutex, to avoid mutex order
3987 // inversion with Thread methods and the ThreadBase mutex.
Eric Laurent00abf0d2020-04-22 19:28:22 -07003988 if (mPrimaryHardwareDev == nullptr) {
3989 return nullptr;
3990 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003992 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003993 if(thread->isDuplicating()) {
3994 continue;
3995 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003996 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003997 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003998 return thread;
3999 }
4000 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07004001 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004002}
4003
jiabinc52b1ff2019-10-31 17:20:42 -07004004DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004005{
Andy Hung87c693c2023-07-06 20:56:16 -07004006 IAfPlaybackThread* const thread = primaryPlaybackThread_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004007
4008 if (thread == NULL) {
Andy Hung920f6572022-10-06 12:09:49 -07004009 return {};
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004010 }
4011
Andy Hungab65b182023-09-06 19:41:47 -07004012 audio_utils::lock_guard l(thread->mutex());
4013 return thread->outDeviceTypes_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004014}
4015
Andy Hung87c693c2023-07-06 20:56:16 -07004016IAfPlaybackThread* AudioFlinger::fastPlaybackThread_l() const
Glenn Kastena7335632016-06-09 17:09:53 -07004017{
4018 size_t minFrameCount = 0;
Andy Hung87c693c2023-07-06 20:56:16 -07004019 IAfPlaybackThread* minThread = nullptr;
Glenn Kastena7335632016-06-09 17:09:53 -07004020 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07004021 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena7335632016-06-09 17:09:53 -07004022 if (!thread->isDuplicating()) {
4023 size_t frameCount = thread->frameCountHAL();
4024 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
4025 (frameCount == minFrameCount && thread->hasFastMixer() &&
4026 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
4027 minFrameCount = frameCount;
4028 minThread = thread;
4029 }
4030 }
4031 }
4032 return minThread;
4033}
4034
Andy Hung87c693c2023-07-06 20:56:16 -07004035IAfThreadBase* AudioFlinger::hapticPlaybackThread_l() const {
jiabineb3bda02020-06-30 14:07:03 -07004036 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
Andy Hung87c693c2023-07-06 20:56:16 -07004037 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
jiabineb3bda02020-06-30 14:07:03 -07004038 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
4039 return thread;
4040 }
4041 }
4042 return nullptr;
4043}
4044
jiabinf042b9b2021-05-07 23:46:28 +00004045void AudioFlinger::updateSecondaryOutputsForTrack_l(
Andy Hungd29af632023-06-23 19:27:19 -07004046 IAfTrack* track,
Andy Hung87c693c2023-07-06 20:56:16 -07004047 IAfPlaybackThread* thread,
jiabinf042b9b2021-05-07 23:46:28 +00004048 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
4049 TeePatches teePatches;
4050 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
Andy Hung87c693c2023-07-06 20:56:16 -07004051 IAfPlaybackThread* const secondaryThread = checkPlaybackThread_l(secondaryOutput);
jiabinf042b9b2021-05-07 23:46:28 +00004052 if (secondaryThread == nullptr) {
4053 ALOGE("no playback thread found for secondary output %d", thread->id());
4054 continue;
4055 }
4056
4057 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
4058 / thread->sampleRate();
4059 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
4060 / secondaryThread->sampleRate();
4061 // If the secondary output has just been opened, the first secondaryThread write
4062 // will not block as it will fill the empty startup buffer of the HAL,
4063 // so a second sink buffer needs to be ready for the immediate next blocking write.
4064 // Additionally, have a margin of one main thread buffer as the scheduling jitter
4065 // can reorder the writes (eg if thread A&B have the same write intervale,
4066 // the scheduler could schedule AB...BA)
4067 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
4068 // Total secondary output buffer must be at least as the read frames plus
4069 // the margin of a few buffers on both sides in case the
4070 // threads scheduling has some jitter.
4071 // That value should not impact latency as the secondary track is started before
4072 // its buffer is full, see frameCountToBeReady.
4073 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
4074 // The frameCount should also not be smaller than the secondary thread min frame
4075 // count
4076 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
Andy Hungc5007f82023-08-29 14:26:09 -07004077 [&] { audio_utils::lock_guard _l(secondaryThread->mutex());
jiabinf042b9b2021-05-07 23:46:28 +00004078 return secondaryThread->latency_l(); }(),
Andy Hung87c693c2023-07-06 20:56:16 -07004079 secondaryThread->frameCount(), // normal frame count
4080 secondaryThread->sampleRate(),
jiabinf042b9b2021-05-07 23:46:28 +00004081 track->sampleRate(),
4082 track->getSpeed());
4083 frameCount = std::max(frameCount, minFrameCount);
4084
4085 using namespace std::chrono_literals;
4086 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
jiabin73e303c2022-09-15 17:49:50 +00004087 if (inChannelMask == AUDIO_CHANNEL_INVALID) {
4088 // The downstream PatchTrack has the proper output channel mask,
4089 // so if there is no input channel mask equivalent, we can just
4090 // use an index mask here to create the PatchRecord.
4091 inChannelMask = audio_channel_mask_out_to_in_index_mask(track->channelMask());
4092 }
Andy Hung8d31fd22023-06-26 19:20:57 -07004093 sp<IAfPatchRecord> patchRecord = IAfPatchRecord::create(nullptr /* thread */,
jiabinf042b9b2021-05-07 23:46:28 +00004094 track->sampleRate(),
4095 inChannelMask,
4096 track->format(),
4097 frameCount,
4098 nullptr /* buffer */,
4099 (size_t)0 /* bufferSize */,
4100 AUDIO_INPUT_FLAG_DIRECT,
4101 0ns /* timeout */);
4102 status_t status = patchRecord->initCheck();
4103 if (status != NO_ERROR) {
4104 ALOGE("Secondary output patchRecord init failed: %d", status);
4105 continue;
4106 }
4107
4108 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
4109 // for fast usage: thread has fast mixer, sample rate matches, etc.;
4110 // for now, we exclude fast tracks by removing the Fast flag.
Andy Hungb3fc6882024-08-19 19:03:55 -07004111 constexpr audio_output_flags_t kIncompatiblePatchTrackFlags =
4112 static_cast<audio_output_flags_t>(AUDIO_OUTPUT_FLAG_FAST
4113 | AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
4114
jiabinf042b9b2021-05-07 23:46:28 +00004115 const audio_output_flags_t outputFlags =
Andy Hungb3fc6882024-08-19 19:03:55 -07004116 (audio_output_flags_t)(track->getOutputFlags() & ~kIncompatiblePatchTrackFlags);
Andy Hung8d31fd22023-06-26 19:20:57 -07004117 sp<IAfPatchTrack> patchTrack = IAfPatchTrack::create(secondaryThread,
jiabinf042b9b2021-05-07 23:46:28 +00004118 track->streamType(),
4119 track->sampleRate(),
4120 track->channelMask(),
4121 track->format(),
4122 frameCount,
4123 patchRecord->buffer(),
4124 patchRecord->bufferSize(),
4125 outputFlags,
4126 0ns /* timeout */,
guonaichao3acc9b12024-06-07 09:27:21 +08004127 frameCountToBeReady,
Andy Hung6b137d12024-08-27 22:35:17 +00004128 track->getSpeed(),
Vlad Popa1e865e62024-08-15 19:11:42 -07004129 1.f /* volume */,
Vlad Popac9c36e62024-10-16 16:40:29 -07004130 false /* muted */);
jiabinf042b9b2021-05-07 23:46:28 +00004131 status = patchTrack->initCheck();
4132 if (status != NO_ERROR) {
4133 ALOGE("Secondary output patchTrack init failed: %d", status);
4134 continue;
4135 }
4136 teePatches.push_back({patchRecord, patchTrack});
4137 secondaryThread->addPatchTrack(patchTrack);
4138 // In case the downstream patchTrack on the secondaryThread temporarily outlives
4139 // our created track, ensure the corresponding patchRecord is still alive.
4140 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
4141 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
4142 }
Andy Hung16ed0da2023-07-14 11:45:38 -07004143 track->setTeePatchesToUpdate_l(std::move(teePatches));
jiabinf042b9b2021-05-07 23:46:28 +00004144}
4145
Andy Hung068e08e2023-05-15 19:02:55 -07004146sp<audioflinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08004147 audio_session_t triggerSession,
4148 audio_session_t listenerSession,
Andy Hunga9acac52023-05-22 18:13:40 -07004149 const audioflinger::SyncEventCallback& callBack,
Andy Hungd29af632023-06-23 19:27:19 -07004150 const wp<IAfTrackBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07004151{
Andy Hung954b9712023-08-28 18:36:53 -07004152 audio_utils::lock_guard _l(mutex());
Eric Laurenta011e352012-03-29 15:51:43 -07004153
Andy Hung068e08e2023-05-15 19:02:55 -07004154 auto event = sp<audioflinger::SyncEvent>::make(
4155 type, triggerSession, listenerSession, callBack, cookie);
Eric Laurenta011e352012-03-29 15:51:43 -07004156 status_t playStatus = NAME_NOT_FOUND;
4157 status_t recStatus = NAME_NOT_FOUND;
4158 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4159 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
4160 if (playStatus == NO_ERROR) {
4161 return event;
4162 }
4163 }
4164 for (size_t i = 0; i < mRecordThreads.size(); i++) {
4165 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
4166 if (recStatus == NO_ERROR) {
4167 return event;
4168 }
4169 }
4170 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
Andy Hung068e08e2023-05-15 19:02:55 -07004171 mPendingSyncEvents.emplace_back(event);
Eric Laurenta011e352012-03-29 15:51:43 -07004172 } else {
4173 ALOGV("createSyncEvent() invalid event %d", event->type());
4174 event.clear();
4175 }
4176 return event;
4177}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004178
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179// ----------------------------------------------------------------------------
4180// Effect management
4181// ----------------------------------------------------------------------------
4182
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004183sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
4184 return mEffectsFactoryHal;
4185}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186
Glenn Kastenf587ba52012-01-26 16:25:10 -08004187status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188{
Andy Hung954b9712023-08-28 18:36:53 -07004189 audio_utils::lock_guard _l(mutex());
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004190 if (mEffectsFactoryHal.get()) {
4191 return mEffectsFactoryHal->queryNumberEffects(numEffects);
4192 } else {
4193 return -ENODEV;
4194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195}
4196
Glenn Kastenf587ba52012-01-26 16:25:10 -08004197status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198{
Andy Hung954b9712023-08-28 18:36:53 -07004199 audio_utils::lock_guard _l(mutex());
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004200 if (mEffectsFactoryHal.get()) {
4201 return mEffectsFactoryHal->getDescriptor(index, descriptor);
4202 } else {
4203 return -ENODEV;
4204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205}
4206
Glenn Kasten5e92a782012-01-30 07:40:52 -08004207status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004208 const effect_uuid_t *pTypeUuid,
4209 uint32_t preferredTypeFlag,
4210 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004212 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
4213 return BAD_VALUE;
4214 }
4215
Andy Hung954b9712023-08-28 18:36:53 -07004216 audio_utils::lock_guard _l(mutex());
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004217
4218 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004219 return -ENODEV;
4220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004222 status_t status = NO_ERROR;
4223 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
4224 // If uuid is specified, request effect descriptor from that.
4225 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
4226 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
4227 // If uuid is not specified, look for an available implementation
4228 // of the required type instead.
4229
4230 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
4231 effect_descriptor_t desc;
4232 desc.flags = 0; // prevent compiler warning
4233
4234 uint32_t numEffects = 0;
4235 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
4236 if (status < 0) {
4237 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
4238 return status;
4239 }
4240
4241 bool found = false;
4242 for (uint32_t i = 0; i < numEffects; i++) {
4243 status = mEffectsFactoryHal->getDescriptor(i, &desc);
4244 if (status < 0) {
4245 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
4246 continue;
4247 }
4248 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
4249 // If matching type found save effect descriptor.
4250 found = true;
4251 *descriptor = desc;
4252
4253 // If there's no preferred flag or this descriptor matches the preferred
4254 // flag, success! If this descriptor doesn't match the preferred
4255 // flag, continue enumeration in case a better matching version of this
4256 // effect type is available. Note that this means if no effect with a
4257 // correct flag is found, the descriptor returned will correspond to the
4258 // last effect that at least had a matching type uuid (if any).
4259 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
4260 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
4261 break;
4262 }
4263 }
4264 }
4265
4266 if (!found) {
4267 status = NAME_NOT_FOUND;
4268 ALOGW("getEffectDescriptor(): Effect not found by type.");
4269 }
4270 } else {
4271 status = BAD_VALUE;
4272 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
4273 }
4274 return status;
4275}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004277status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
4278 media::CreateEffectResponse* response) {
4279 const sp<IEffectClient>& effectClient = request.client;
4280 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004281 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004282 aidl2legacy_AudioDeviceTypeAddress(request.device));
Svet Ganov33761132021-05-13 22:51:08 +00004283 AttributionSourceState adjAttributionSource = request.attributionSource;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004284 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004285 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004286 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
4287 aidl2legacy_int32_t_audio_io_handle_t(request.output));
4288 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004289 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
4290 const bool probe = request.probe;
4291
Andy Hung6ac17eb2023-06-20 18:56:17 -07004292 sp<IAfEffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004293 effect_descriptor_t descOut;
4294 int enabledOut = 0;
4295 int idOut = -1;
4296
4297 status_t lStatus = NO_ERROR;
Atneya Nair5997a652024-06-14 17:24:45 -07004298 uid_t callingUid = IPCThreadState::self()->getCallingUid();
4299 pid_t currentPid;
4300 if (!com::android::media::audio::audioserver_permissions()) {
4301 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
4302 currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
4303 if (currentPid == -1 || !isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
4304 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
4305 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
4306 "%s uid %d pid %d tried to pass itself off as pid %d",
4307 __func__, callingUid, callingPid, currentPid);
4308 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
4309 legacy2aidl_pid_t_int32_t(callingPid));
4310 currentPid = callingPid;
4311 }
4312 adjAttributionSource = afutils::checkAttributionSourcePackage(adjAttributionSource);
4313 } else {
4314 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
4315 validateAttributionFromContextOrTrustedCaller(request.attributionSource,
4316 getPermissionProvider()
4317 ));
4318 // TODO pass wrapped object around
4319 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
4320 currentPid = adjAttributionSource.pid;
Pechetty Sravani55532052024-06-14 03:30:13 +00004321 }
Atneya Nair5997a652024-06-14 17:24:45 -07004322
Eric Laurentb6436272016-12-07 19:24:50 -08004323
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004324 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Svet Ganov33761132021-05-13 22:51:08 +00004325 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
4326 mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004328 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004329 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004330 lStatus = NO_INIT;
4331 goto Exit;
4332 }
4333
Andy Hung6096dcd2019-03-13 13:20:30 -07004334 // check audio settings permission for global effects
4335 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4336 if (!settingsAllowed()) {
4337 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
4338 lStatus = PERMISSION_DENIED;
4339 goto Exit;
4340 }
4341 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004342 if (io == AUDIO_IO_HANDLE_NONE) {
4343 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
4344 lStatus = BAD_VALUE;
4345 goto Exit;
4346 }
Andy Hungc2cf7ec2023-08-30 18:19:00 -07004347 IAfPlaybackThread* thread;
4348 {
4349 audio_utils::lock_guard l(mutex());
4350 thread = checkPlaybackThread_l(io);
4351 }
Eric Laurenta74058e2022-05-26 15:08:00 +00004352 if (thread == nullptr) {
4353 ALOGE("%s: invalid output %d specified for AUDIO_SESSION_OUTPUT_STAGE", __func__, io);
4354 lStatus = BAD_VALUE;
4355 goto Exit;
4356 }
4357 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)
4358 && !isAudioServerUid(callingUid)) {
4359 ALOGE("%s: effect on AUDIO_SESSION_OUTPUT_STAGE not granted for uid %d",
4360 __func__, callingUid);
4361 lStatus = PERMISSION_DENIED;
4362 goto Exit;
4363 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004364 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Svet Ganov33761132021-05-13 22:51:08 +00004365 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004366 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
4367 lStatus = PERMISSION_DENIED;
4368 goto Exit;
4369 }
Eric Laurent94876032019-11-13 12:45:28 -08004370 if (io != AUDIO_IO_HANDLE_NONE) {
4371 ALOGE("%s: io handle should not be specified for device effect", __func__);
4372 lStatus = BAD_VALUE;
4373 goto Exit;
4374 }
Andy Hung6096dcd2019-03-13 13:20:30 -07004375 } else {
4376 // general sessionId.
4377
4378 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
4379 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
4380 lStatus = BAD_VALUE;
4381 goto Exit;
4382 }
4383
4384 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
4385 // to prevent creating an effect when one doesn't actually have track with that session?
4386 }
4387
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004389 // Get the full effect descriptor from the uuid/type.
4390 // If the session is the output mix, prefer an auxiliary effect,
4391 // otherwise no preference.
4392 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
4393 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004394 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004395 if (lStatus < 0) {
4396 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
4397 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 }
4399
4400 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004401 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004402 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403 lStatus = INVALID_OPERATION;
4404 goto Exit;
4405 }
4406
Eric Laurent59255e42011-07-27 19:49:51 -07004407 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004408 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08004409 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Svet Ganov33761132021-05-13 22:51:08 +00004410 !recordingAllowed(adjAttributionSource)) {
Eric Laurent59255e42011-07-27 19:49:51 -07004411 lStatus = PERMISSION_DENIED;
4412 goto Exit;
4413 }
4414
Andy Hung6ac17eb2023-06-20 18:56:17 -07004415 const bool hapticPlaybackRequired = IAfEffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07004416 if (hapticPlaybackRequired
4417 && (sessionId == AUDIO_SESSION_DEVICE
4418 || sessionId == AUDIO_SESSION_OUTPUT_MIX
4419 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
4420 // haptic-generating effect is only valid when the session id is a general session id
4421 lStatus = INVALID_OPERATION;
4422 goto Exit;
4423 }
4424
Eric Laurentf690c462021-09-17 14:47:03 +02004425 // Only audio policy service can create a spatializer effect
Eric Laurent4eb45d02023-12-20 12:07:17 +01004426 if (IAfEffectModule::isSpatializer(&descOut.type) &&
Eric Laurentf690c462021-09-17 14:47:03 +02004427 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
4428 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
4429 __func__, callingUid, currentPid);
4430 lStatus = PERMISSION_DENIED;
4431 goto Exit;
4432 }
4433
Glenn Kasten142f5192014-03-25 17:44:59 -07004434 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004435 // if the output returned by getOutputForEffect() is removed before we lock the
4436 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
4437 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004438 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07004439 ALOGV("createEffect got output %d", io);
4440 }
4441
Andy Hung954b9712023-08-28 18:36:53 -07004442 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443
Eric Laurentb82e6b72019-11-22 17:25:04 -08004444 if (sessionId == AUDIO_SESSION_DEVICE) {
Atneya Nairb01390f2024-10-09 23:33:27 +00004445 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004446 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Vlad Popa5161f8a2022-10-10 16:17:20 +02004447 handle = mDeviceEffectManager->createEffect_l(
Andy Hungb6692eb2023-07-13 16:52:46 -07004448 &descOut, device, client, effectClient, mPatchPanel->patches_l(),
Eric Laurentde8caf42021-08-11 17:19:25 +02004449 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08004450 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung954b9712023-08-28 18:36:53 -07004451 // remove local strong reference to Client with clientMutex() held
4452 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentb82e6b72019-11-22 17:25:04 -08004453 client.clear();
4454 } else {
4455 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004456 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08004457 }
4458 goto Register;
4459 }
4460
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461 // If output is not specified try to find a matching audio session ID in one of the
4462 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004463 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4464 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07004465 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
4466 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07004467 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004468 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07004469 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
4470 if (io == AUDIO_IO_HANDLE_NONE) {
4471 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08004473 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07004474 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08004475 }
Andy Hung444bb552019-03-14 17:06:39 -07004476
4477 // If you wish to create a Record preprocessing AudioEffect in Java,
4478 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
4479 // Otherwise it will fail when created on a Playback thread by legacy
4480 // handling below. Ditto with Mmap, the associated Mmap track must be created
4481 // before creating the AudioEffect or the io handle must be specified.
4482 //
4483 // Detect if the effect is created after an AudioRecord is destroyed.
Shunkai Yao29d10572024-03-19 04:31:47 +00004484 if (sessionId != AUDIO_SESSION_OUTPUT_MIX
4485 && ((descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)
4486 && getOrphanEffectChain_l(sessionId).get() != nullptr) {
Andy Hung444bb552019-03-14 17:06:39 -07004487 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004488 " for session %d no longer exists",
4489 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07004490 lStatus = PERMISSION_DENIED;
4491 goto Exit;
4492 }
4493
4494 // Legacy handling of creating an effect on an expired or made-up
4495 // session id. We think that it is a Playback effect.
4496 //
Shunkai Yao29d10572024-03-19 04:31:47 +00004497 // If no output thread contains the requested session ID, park the effect to
4498 // the orphan chains. The effect chain will be moved to the correct output
4499 // thread when a track with the same session ID is created.
4500 if (io == AUDIO_IO_HANDLE_NONE) {
4501 if (probe) {
4502 // In probe mode, as no compatible thread found, exit with error.
4503 lStatus = BAD_VALUE;
4504 goto Exit;
4505 }
4506 ALOGV("%s() got io %d for effect %s", __func__, io, descOut.name);
Atneya Nairb01390f2024-10-09 23:33:27 +00004507 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
Shunkai Yao29d10572024-03-19 04:31:47 +00004508 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
4509 handle = createOrphanEffect_l(client, effectClient, priority, sessionId,
4510 &descOut, &enabledOut, &lStatus, pinned,
4511 request.notifyFramesProcessed);
4512 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4513 // remove local strong reference to Client with clientMutex() held
4514 audio_utils::lock_guard _cl(clientMutex());
4515 client.clear();
4516 }
4517 goto Register;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004518 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004519 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Eric Laurentb3f315a2021-07-13 15:09:05 +02004520 } else if (checkPlaybackThread_l(io) != nullptr
4521 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung1631f062019-03-12 19:39:03 -07004522 // allow only one effect chain per sessionId on mPlaybackThreads.
4523 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4524 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07004525 if (io == checkIo) {
4526 if (hapticPlaybackRequired
4527 && mPlaybackThreads.valueAt(i)
4528 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4529 ALOGE("%s: haptic playback thread is required while the required playback "
4530 "thread(io=%d) doesn't support", __func__, (int)io);
4531 lStatus = BAD_VALUE;
4532 goto Exit;
4533 }
4534 continue;
4535 }
Andy Hung1631f062019-03-12 19:39:03 -07004536 const uint32_t sessionType =
4537 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07004538 if ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0) {
Andy Hung1631f062019-03-12 19:39:03 -07004539 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004540 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07004541 android_errorWriteLog(0x534e4554, "123237974");
4542 lStatus = BAD_VALUE;
4543 goto Exit;
4544 }
4545 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004546 }
Andy Hung87c693c2023-07-06 20:56:16 -07004547 IAfThreadBase* thread = checkRecordThread_l(io);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004548 if (thread == NULL) {
4549 thread = checkPlaybackThread_l(io);
4550 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08004551 thread = checkMmapThread_l(io);
4552 if (thread == NULL) {
4553 ALOGE("createEffect() unknown output thread");
4554 lStatus = BAD_VALUE;
4555 goto Exit;
4556 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004557 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004558 }
4559 if (thread->type() == IAfThreadBase::RECORD || sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentaaa44472014-09-12 17:41:50 -07004560 // Check if one effect chain was awaiting for an effect to be created on this
4561 // session and used it instead of creating a new one.
Andy Hung6ac17eb2023-06-20 18:56:17 -07004562 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07004563 if (chain != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07004564 audio_utils::lock_guard _l2(thread->mutex());
Eric Laurentaaa44472014-09-12 17:41:50 -07004565 thread->addEffectChain_l(chain);
4566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004568
Atneya Nairb01390f2024-10-09 23:33:27 +00004569 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004571 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004572 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07004573 IAfThreadBase* oriThread = nullptr;
jiabineb3bda02020-06-30 14:07:03 -07004574 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
Andy Hung87c693c2023-07-06 20:56:16 -07004575 IAfThreadBase* const hapticThread = hapticPlaybackThread_l();
jiabineb3bda02020-06-30 14:07:03 -07004576 if (hapticThread == nullptr) {
4577 ALOGE("%s haptic thread not found while it is required", __func__);
4578 lStatus = INVALID_OPERATION;
4579 goto Exit;
4580 }
4581 if (hapticThread != thread) {
4582 // Force to use haptic thread for haptic-generating effect.
4583 oriThread = thread;
4584 thread = hapticThread;
4585 }
4586 }
Eric Laurentde070132010-07-13 04:45:46 -07004587 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurentde8caf42021-08-11 17:19:25 +02004588 &descOut, &enabledOut, &lStatus, pinned, probe,
4589 request.notifyFramesProcessed);
haobo101735295ff7b0d2017-03-17 17:44:03 +08004590 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung954b9712023-08-28 18:36:53 -07004591 // remove local strong reference to Client with clientMutex() held
4592 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004593 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08004594 } else {
4595 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004596 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07004597 // Invalidate audio session when haptic playback is created.
4598 if (hapticPlaybackRequired && oriThread != nullptr) {
4599 // invalidateTracksForAudioSession will trigger locking the thread.
4600 oriThread->invalidateTracksForAudioSession(sessionId);
4601 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004602 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 }
4604
Eric Laurentb82e6b72019-11-22 17:25:04 -08004605Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004606 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent4f1d4e92022-02-01 14:37:16 +01004607 if (lStatus == ALREADY_EXISTS) {
4608 response->alreadyExists = true;
4609 lStatus = NO_ERROR;
4610 } else {
4611 response->alreadyExists = false;
4612 }
Eric Laurent6c796322019-04-09 14:13:17 -07004613 // Check CPU and memory usage
Andy Hung6ac17eb2023-06-20 18:56:17 -07004614 sp<IAfEffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004615 if (effect != nullptr) {
4616 status_t rStatus = effect->updatePolicyState();
4617 if (rStatus != NO_ERROR) {
4618 lStatus = rStatus;
4619 }
4620 }
4621 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08004622 handle.clear();
4623 }
4624
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004625 response->id = idOut;
4626 response->enabled = enabledOut != 0;
Shunkai Yao8ade2572023-07-28 00:55:00 +00004627 response->effect = handle.get() ? handle->asIEffect() : nullptr;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004628 response->desc = VALUE_OR_RETURN_STATUS(
4629 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004630
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004632 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633}
4634
Shunkai Yao29d10572024-03-19 04:31:47 +00004635sp<IAfEffectHandle> AudioFlinger::createOrphanEffect_l(
4636 const sp<Client>& client,
4637 const sp<IEffectClient>& effectClient,
4638 int32_t priority,
4639 audio_session_t sessionId,
4640 effect_descriptor_t *desc,
4641 int *enabled,
4642 status_t *status,
4643 bool pinned,
4644 bool notifyFramesProcessed)
4645{
4646 ALOGV("%s effectClient %p, priority %d, sessionId %d, factory %p",
4647 __func__, effectClient.get(), priority, sessionId, mEffectsFactoryHal.get());
4648
4649 // Check if an orphan effect chain exists for this session or create new chain for this session
4650 sp<IAfEffectModule> effect;
4651 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
4652 bool chainCreated = false;
4653 if (chain == nullptr) {
4654 chain = IAfEffectChain::create(/* ThreadBase= */ nullptr, sessionId, this);
4655 chainCreated = true;
4656 } else {
4657 effect = chain->getEffectFromDesc(desc);
4658 }
4659 bool effectCreated = false;
4660 if (effect == nullptr) {
4661 audio_unique_id_t effectId = nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
4662 // create a new effect module if none present in the chain
4663 status_t llStatus =
4664 chain->createEffect(effect, desc, effectId, sessionId, pinned);
4665 if (llStatus != NO_ERROR) {
4666 *status = llStatus;
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004667 // if the effect chain was not created here, put it back
4668 if (!chainCreated) {
4669 putOrphanEffectChain_l(chain);
4670 }
Shunkai Yao29d10572024-03-19 04:31:47 +00004671 return nullptr;
4672 }
4673 effect->setMode(getMode());
4674
4675 if (effect->isHapticGenerator()) {
4676 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
4677 // for the HapticGenerator.
4678 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08004679 getDefaultVibratorInfo_l();
Shunkai Yao29d10572024-03-19 04:31:47 +00004680 if (defaultVibratorInfo) {
4681 // Only set the vibrator info when it is a valid one.
4682 audio_utils::lock_guard _cl(chain->mutex());
4683 effect->setVibratorInfo_l(*defaultVibratorInfo);
4684 }
4685 }
4686 effectCreated = true;
4687 }
4688 // create effect handle and connect it to effect module
4689 sp<IAfEffectHandle> handle =
4690 IAfEffectHandle::create(effect, client, effectClient, priority, notifyFramesProcessed);
4691 status_t lStatus = handle->initCheck();
4692 if (lStatus == OK) {
4693 lStatus = effect->addHandle(handle.get());
4694 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004695 // in case of lStatus error, EffectHandle will still return and caller should do the clear
Shunkai Yao29d10572024-03-19 04:31:47 +00004696 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4697 if (effectCreated) {
4698 chain->removeEffect(effect);
4699 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004700 // if the effect chain was not created here, put it back
4701 if (!chainCreated) {
4702 putOrphanEffectChain_l(chain);
4703 }
Shunkai Yao29d10572024-03-19 04:31:47 +00004704 } else {
4705 if (enabled != NULL) {
4706 *enabled = (int)effect->isEnabled();
4707 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004708 putOrphanEffectChain_l(chain);
Shunkai Yao29d10572024-03-19 04:31:47 +00004709 }
4710 *status = lStatus;
4711 return handle;
4712}
4713
François Gaffie1b4753e2023-02-06 10:36:33 +01004714status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcIo,
4715 audio_io_handle_t dstIo)
4716NO_THREAD_SAFETY_ANALYSIS
Eric Laurentde070132010-07-13 04:45:46 -07004717{
François Gaffie1b4753e2023-02-06 10:36:33 +01004718 ALOGV("%s() session %d, srcIo %d, dstIo %d", __func__, sessionId, srcIo, dstIo);
Andy Hung954b9712023-08-28 18:36:53 -07004719 audio_utils::lock_guard _l(mutex());
François Gaffie1b4753e2023-02-06 10:36:33 +01004720 if (srcIo == dstIo) {
4721 ALOGW("%s() same dst and src outputs %d", __func__, dstIo);
Eric Laurentde070132010-07-13 04:45:46 -07004722 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 }
Andy Hung87c693c2023-07-06 20:56:16 -07004724 IAfRecordThread* const srcRecordThread = checkRecordThread_l(srcIo);
4725 IAfRecordThread* const dstRecordThread = checkRecordThread_l(dstIo);
François Gaffie1b4753e2023-02-06 10:36:33 +01004726 if (srcRecordThread != nullptr || dstRecordThread != nullptr) {
4727 if (srcRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004728 srcRecordThread->mutex().lock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004729 }
4730 if (dstRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004731 dstRecordThread->mutex().lock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004732 }
Andy Hung972bec12023-08-31 16:13:39 -07004733 status_t ret = moveEffectChain_ll(sessionId, srcRecordThread, dstRecordThread);
François Gaffie1b4753e2023-02-06 10:36:33 +01004734 if (srcRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004735 srcRecordThread->mutex().unlock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004736 }
4737 if (dstRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004738 dstRecordThread->mutex().unlock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004739 }
4740 return ret;
4741 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004742
4743 IAfPlaybackThread* dstThread = checkPlaybackThread_l(dstIo);
François Gaffie1b4753e2023-02-06 10:36:33 +01004744 if (dstThread == nullptr) {
4745 ALOGW("%s() bad dstIo %d", __func__, dstIo);
Eric Laurentde070132010-07-13 04:45:46 -07004746 return BAD_VALUE;
4747 }
4748
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004749 IAfPlaybackThread* srcThread = checkPlaybackThread_l(srcIo);
4750 sp<IAfEffectChain> orphanChain = getOrphanEffectChain_l(sessionId);
4751 if (srcThread == nullptr && orphanChain == nullptr && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4752 ALOGW("%s() AUDIO_SESSION_OUTPUT_MIX not found in orphans, checking other mix", __func__);
4753 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4754 const sp<IAfPlaybackThread> pt = mPlaybackThreads.valueAt(i);
4755 const uint32_t sessionType = pt->hasAudioSession(AUDIO_SESSION_OUTPUT_MIX);
4756 if ((pt->type() == IAfThreadBase::MIXER || pt->type() == IAfThreadBase::OFFLOAD) &&
4757 ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0)) {
4758 srcThread = pt.get();
Andy Hungae975472024-06-13 16:50:38 -07004759 if (srcThread == dstThread) {
4760 ALOGD("%s() same dst and src threads, ignoring move", __func__);
4761 return NO_ERROR;
4762 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004763 ALOGW("%s() found srcOutput %d hosting AUDIO_SESSION_OUTPUT_MIX", __func__,
4764 pt->id());
4765 break;
4766 }
4767 }
4768 }
4769 if (srcThread == nullptr && orphanChain == nullptr) {
4770 ALOGW("moveEffects() bad srcIo %d", srcIo);
4771 return BAD_VALUE;
4772 }
4773 // dstThread pointer validity has already been checked
4774 if (orphanChain != nullptr) {
4775 audio_utils::scoped_lock _ll(dstThread->mutex());
4776 return moveEffectChain_ll(sessionId, nullptr, dstThread, orphanChain.get());
4777 }
4778 // srcThread pointer validity has already been checked
Andy Hunge0f5ec52023-08-30 11:26:06 -07004779 audio_utils::scoped_lock _ll(dstThread->mutex(), srcThread->mutex());
Andy Hung972bec12023-08-31 16:13:39 -07004780 return moveEffectChain_ll(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004781}
4782
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004783
4784void AudioFlinger::setEffectSuspended(int effectId,
4785 audio_session_t sessionId,
4786 bool suspended)
4787{
Andy Hung954b9712023-08-28 18:36:53 -07004788 audio_utils::lock_guard _l(mutex());
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004789
Andy Hung87c693c2023-07-06 20:56:16 -07004790 sp<IAfThreadBase> thread = getEffectThread_l(sessionId, effectId);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004791 if (thread == nullptr) {
Shunkai Yao8da94182024-02-14 02:49:47 +00004792 return;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004793 }
Andy Hungc5007f82023-08-29 14:26:09 -07004794 audio_utils::lock_guard _sl(thread->mutex());
Shunkai Yao8da94182024-02-14 02:49:47 +00004795 if (const auto& effect = thread->getEffect_l(sessionId, effectId)) {
4796 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4797 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004798}
4799
4800
Andy Hung972bec12023-08-31 16:13:39 -07004801// moveEffectChain_ll must be called with the AudioFlinger::mutex()
4802// and both srcThread and dstThread mutex()s held
4803status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004804 IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread,
4805 IAfEffectChain* srcChain)
Eric Laurentde070132010-07-13 04:45:46 -07004806{
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004807 ALOGV("%s: session %d from thread %p to thread %p %s",
4808 __func__, sessionId, srcThread, dstThread,
4809 (srcChain != nullptr ? "from specific chain" : ""));
4810 ALOG_ASSERT((srcThread != nullptr) != (srcChain != nullptr),
4811 "no source provided for source chain");
Eric Laurentde070132010-07-13 04:45:46 -07004812
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004813 sp<IAfEffectChain> chain =
4814 srcChain != nullptr ? srcChain : srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07004815 if (chain == 0) {
Andy Hung972bec12023-08-31 16:13:39 -07004816 ALOGW("%s: effect chain for session %d not on source thread %p",
4817 __func__, sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07004818 return INVALID_OPERATION;
4819 }
4820
Eric Laurent4c415062016-06-17 16:14:16 -07004821 // Check whether the destination thread and all effects in the chain are compatible
4822 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung972bec12023-08-31 16:13:39 -07004823 ALOGW("%s: effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07004824 " destination thread %p is not compatible with effects in the chain",
Andy Hung972bec12023-08-31 16:13:39 -07004825 __func__, dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07004826 return INVALID_OPERATION;
4827 }
4828
Eric Laurent39e94f82010-07-28 01:32:47 -07004829 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004830 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07004831 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07004832 // removed.
Andy Hung180f49a2022-01-27 10:25:02 -08004833 // TODO(b/216875016): consider holding the effect chain locks for the duration of the move.
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004834 if (srcThread != nullptr) {
4835 srcThread->removeEffectChain_l(chain);
4836 }
Eric Laurentde070132010-07-13 04:45:46 -07004837 // transfer all effects one by one so that new effect chain is created on new thread with
4838 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Andy Hung6ac17eb2023-06-20 18:56:17 -07004839 sp<IAfEffectChain> dstChain;
4840 Vector<sp<IAfEffectModule>> removed;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004841 status_t status = NO_ERROR;
Andy Hung03410c02022-01-27 08:24:31 -08004842 std::string errorString;
Andy Hung920f6572022-10-06 12:09:49 -07004843 // process effects one by one.
Andy Hung6ac17eb2023-06-20 18:56:17 -07004844 for (sp<IAfEffectModule> effect = chain->getEffectFromId_l(0); effect != nullptr;
Andy Hung920f6572022-10-06 12:09:49 -07004845 effect = chain->getEffectFromId_l(0)) {
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004846 if (srcThread != nullptr) {
4847 srcThread->removeEffect_l(effect);
4848 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00004849 chain->removeEffect(effect);
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004850 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004851 removed.add(effect);
Andy Hung972bec12023-08-31 16:13:39 -07004852 status = dstThread->addEffect_ll(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004853 if (status != NO_ERROR) {
Andy Hung03410c02022-01-27 08:24:31 -08004854 errorString = StringPrintf(
4855 "cannot add effect %p to destination thread", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004856 break;
4857 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004858 // if the move request is not received from audio policy manager, the effect must be
Andy Hung180f49a2022-01-27 10:25:02 -08004859 // re-registered with the new strategy and output.
4860
4861 // We obtain the dstChain once the effect is on the new thread.
4862 if (dstChain == nullptr) {
Andy Hungfda44002021-06-03 17:23:16 -07004863 dstChain = effect->getCallback()->chain().promote();
Andy Hung180f49a2022-01-27 10:25:02 -08004864 if (dstChain == nullptr) {
Andy Hung03410c02022-01-27 08:24:31 -08004865 errorString = StringPrintf("cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004866 status = NO_INIT;
4867 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004868 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004869 }
Eric Laurentde070132010-07-13 04:45:46 -07004870 }
4871
Andy Hung03410c02022-01-27 08:24:31 -08004872 size_t restored = 0;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004873 if (status != NO_ERROR) {
Andy Hung180f49a2022-01-27 10:25:02 -08004874 dstChain.clear(); // dstChain is now from the srcThread (could be recreated).
Andy Hung03410c02022-01-27 08:24:31 -08004875 for (const auto& effect : removed) {
Andy Hung5c4dd0d2022-01-27 10:21:59 -08004876 dstThread->removeEffect_l(effect); // Note: Depending on error location, the last
4877 // effect may not have been placed on dstThread.
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004878 if (srcThread != nullptr && srcThread->addEffect_ll(effect) == NO_ERROR) {
Andy Hung03410c02022-01-27 08:24:31 -08004879 ++restored;
Andy Hung180f49a2022-01-27 10:25:02 -08004880 if (dstChain == nullptr) {
4881 dstChain = effect->getCallback()->chain().promote();
4882 }
Andy Hung03410c02022-01-27 08:24:31 -08004883 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004884 }
4885 }
4886
Andy Hung180f49a2022-01-27 10:25:02 -08004887 // After all the effects have been moved to new thread (or put back) we restart the effects
4888 // because removeEffect_l() has stopped the effect if it is currently active.
4889 size_t started = 0;
4890 if (dstChain != nullptr && !removed.empty()) {
4891 // If we do not take the dstChain lock, it is possible that processing is ongoing
4892 // while we are starting the effect. This can cause glitches with volume,
4893 // see b/202360137.
Andy Hungf65f5a72023-08-29 12:19:17 -07004894 dstChain->mutex().lock();
Andy Hung180f49a2022-01-27 10:25:02 -08004895 for (const auto& effect : removed) {
Andy Hung6ac17eb2023-06-20 18:56:17 -07004896 if (effect->state() == IAfEffectModule::ACTIVE ||
4897 effect->state() == IAfEffectModule::STOPPING) {
Andy Hung180f49a2022-01-27 10:25:02 -08004898 ++started;
Shunkai Yaod125e402024-01-20 03:19:06 +00004899 effect->start_l();
Andy Hung180f49a2022-01-27 10:25:02 -08004900 }
4901 }
Andy Hungf65f5a72023-08-29 12:19:17 -07004902 dstChain->mutex().unlock();
Andy Hung180f49a2022-01-27 10:25:02 -08004903 }
4904
Andy Hung03410c02022-01-27 08:24:31 -08004905 if (status != NO_ERROR) {
4906 if (errorString.empty()) {
4907 errorString = StringPrintf("%s: failed status %d", __func__, status);
4908 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004909 ALOGW("%s: %s unsuccessful move of session %d from %s %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004910 "(%zu effects removed from srcThread, %zu effects restored to srcThread, "
4911 "%zu effects started)",
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004912 __func__, errorString.c_str(), sessionId,
4913 (srcThread != nullptr ? "srcThread" : "srcChain"),
4914 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
Andy Hung180f49a2022-01-27 10:25:02 -08004915 removed.size(), restored, started);
Andy Hung03410c02022-01-27 08:24:31 -08004916 } else {
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004917 ALOGD("%s: successful move of session %d from %s %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004918 "(%zu effects moved, %zu effects started)",
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004919 __func__, sessionId, (srcThread != nullptr ? "srcThread" : "srcChain"),
4920 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
4921 removed.size(), started);
Andy Hung03410c02022-01-27 08:24:31 -08004922 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004923 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924}
4925
François Gaffie1b4753e2023-02-06 10:36:33 +01004926
Andy Hung972bec12023-08-31 16:13:39 -07004927// moveEffectChain_ll must be called with both srcThread (if not null) and dstThread (if not null)
Andy Hung954b9712023-08-28 18:36:53 -07004928// mutex()s held
Andy Hung972bec12023-08-31 16:13:39 -07004929status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
Andy Hung87c693c2023-07-06 20:56:16 -07004930 IAfRecordThread* srcThread, IAfRecordThread* dstThread)
François Gaffie1b4753e2023-02-06 10:36:33 +01004931{
4932 sp<IAfEffectChain> chain = nullptr;
4933 if (srcThread != 0) {
Andy Hung87c693c2023-07-06 20:56:16 -07004934 const Vector<sp<IAfEffectChain>> effectChains = srcThread->getEffectChains_l();
François Gaffie1b4753e2023-02-06 10:36:33 +01004935 for (size_t i = 0; i < effectChains.size(); i ++) {
4936 if (effectChains[i]->sessionId() == sessionId) {
4937 chain = effectChains[i];
4938 break;
4939 }
4940 }
4941 ALOGV_IF(effectChains.size() == 0, "%s: no effect chain on io=%d", __func__,
4942 srcThread->id());
4943 if (chain == nullptr) {
4944 ALOGE("%s wrong session id %d", __func__, sessionId);
4945 return BAD_VALUE;
4946 }
4947 ALOGV("%s: removing effect chain for session=%d io=%d", __func__, sessionId,
4948 srcThread->id());
4949 srcThread->removeEffectChain_l(chain);
4950 } else {
4951 chain = getOrphanEffectChain_l(sessionId);
4952 if (chain == nullptr) {
4953 ALOGE("%s: no orphan effect chain found for session=%d", __func__, sessionId);
4954 return BAD_VALUE;
4955 }
4956 }
4957 if (dstThread != 0) {
4958 ALOGV("%s: adding effect chain for session=%d on io=%d", __func__, sessionId,
4959 dstThread->id());
4960 dstThread->addEffectChain_l(chain);
4961 return NO_ERROR;
4962 }
4963 ALOGV("%s: parking to orphan effect chain for session=%d", __func__, sessionId);
4964 putOrphanEffectChain_l(chain);
4965 return NO_ERROR;
4966}
4967
Eric Laurent6c796322019-04-09 14:13:17 -07004968status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
Andy Hung87c693c2023-07-06 20:56:16 -07004969 const sp<IAfPlaybackThread>& dstThread, sp<IAfPlaybackThread>* srcThread)
Eric Laurent6c796322019-04-09 14:13:17 -07004970{
4971 status_t status = NO_ERROR;
Andy Hung954b9712023-08-28 18:36:53 -07004972 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07004973 const sp<IAfThreadBase> threadBase = getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4974 const sp<IAfPlaybackThread> thread = threadBase ? threadBase->asIAfPlaybackThread() : nullptr;
Eric Laurent6c796322019-04-09 14:13:17 -07004975
4976 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
Andy Hunge0f5ec52023-08-30 11:26:06 -07004977 audio_utils::scoped_lock _ll(dstThread->mutex(), thread->mutex());
Andy Hung6ac17eb2023-06-20 18:56:17 -07004978 sp<IAfEffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4979 sp<IAfEffectChain> dstChain;
Eric Laurent6c796322019-04-09 14:13:17 -07004980 if (srcChain == 0) {
4981 return INVALID_OPERATION;
4982 }
4983
Andy Hung6ac17eb2023-06-20 18:56:17 -07004984 sp<IAfEffectModule> effect = srcChain->getEffectFromId_l(EffectId);
Eric Laurent6c796322019-04-09 14:13:17 -07004985 if (effect == 0) {
4986 return INVALID_OPERATION;
4987 }
4988 thread->removeEffect_l(effect);
Andy Hung972bec12023-08-31 16:13:39 -07004989 status = dstThread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004990 if (status != NO_ERROR) {
Andy Hung972bec12023-08-31 16:13:39 -07004991 thread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004992 status = INVALID_OPERATION;
4993 goto Exit;
4994 }
4995
Andy Hungfda44002021-06-03 17:23:16 -07004996 dstChain = effect->getCallback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004997 if (dstChain == 0) {
Andy Hung972bec12023-08-31 16:13:39 -07004998 thread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004999 status = INVALID_OPERATION;
5000 }
5001
5002Exit:
5003 // removeEffect_l() has stopped the effect if it was active so it must be restarted
Andy Hung6ac17eb2023-06-20 18:56:17 -07005004 if (effect->state() == IAfEffectModule::ACTIVE ||
5005 effect->state() == IAfEffectModule::STOPPING) {
Shunkai Yaod125e402024-01-20 03:19:06 +00005006 effect->start_l();
Eric Laurent6c796322019-04-09 14:13:17 -07005007 }
5008 }
5009
5010 if (status == NO_ERROR && srcThread != nullptr) {
5011 *srcThread = thread;
5012 }
5013 return status;
5014}
5015
Andy Hung583043b2023-07-17 17:05:00 -07005016bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() const
Eric Laurent813e2a72013-08-31 12:59:48 -07005017{
Eric Laurent813e2a72013-08-31 12:59:48 -07005018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hungab65b182023-09-06 19:41:47 -07005019 const auto thread = mPlaybackThreads.valueAt(i);
5020 audio_utils::lock_guard l(thread->mutex());
5021 const sp<IAfEffectChain> ec = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07005022 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07005023 return true;
5024 }
5025 }
5026 return false;
5027}
5028
Eric Laurent5baf2af2013-09-12 17:37:00 -07005029void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07005030{
Andy Hung954b9712023-08-28 18:36:53 -07005031 audio_utils::lock_guard _l(mutex());
Eric Laurent813e2a72013-08-31 12:59:48 -07005032
Eric Laurent813e2a72013-08-31 12:59:48 -07005033 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07005034 const sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
5035 if (t->type() == IAfThreadBase::OFFLOAD) {
Eric Laurent813e2a72013-08-31 12:59:48 -07005036 t->invalidateTracks(AUDIO_STREAM_MUSIC);
5037 }
5038 }
5039
5040}
5041
Andy Hung6ac17eb2023-06-20 18:56:17 -07005042status_t AudioFlinger::putOrphanEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurentaaa44472014-09-12 17:41:50 -07005043{
Eric Laurentd8365c52017-07-16 15:27:05 -07005044 // clear possible suspended state before parking the chain so that it starts in default state
5045 // when attached to a new record thread
5046 chain->setEffectSuspended_l(FX_IID_AEC, false);
5047 chain->setEffectSuspended_l(FX_IID_NS, false);
5048
Glenn Kastend848eb42016-03-08 13:42:11 -08005049 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07005050 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005051 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07005052 if (index >= 0) {
5053 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
5054 return ALREADY_EXISTS;
5055 }
5056 mOrphanEffectChains.add(session, chain);
5057 return NO_ERROR;
5058}
5059
Andy Hung6ac17eb2023-06-20 18:56:17 -07005060sp<IAfEffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
Eric Laurentaaa44472014-09-12 17:41:50 -07005061{
Andy Hung6ac17eb2023-06-20 18:56:17 -07005062 sp<IAfEffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07005063 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005064 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07005065 if (index >= 0) {
5066 chain = mOrphanEffectChains.valueAt(index);
5067 mOrphanEffectChains.removeItemsAt(index);
5068 }
5069 return chain;
5070}
5071
Andy Hung6ac17eb2023-06-20 18:56:17 -07005072bool AudioFlinger::updateOrphanEffectChains(const sp<IAfEffectModule>& effect)
Eric Laurentaaa44472014-09-12 17:41:50 -07005073{
Andy Hung954b9712023-08-28 18:36:53 -07005074 audio_utils::lock_guard _l(mutex());
François Gaffie1b4753e2023-02-06 10:36:33 +01005075 return updateOrphanEffectChains_l(effect);
5076}
5077
5078bool AudioFlinger::updateOrphanEffectChains_l(const sp<IAfEffectModule>& effect)
5079{
Glenn Kastend848eb42016-03-08 13:42:11 -08005080 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07005081 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005082 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07005083 if (index >= 0) {
Andy Hung6ac17eb2023-06-20 18:56:17 -07005084 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
Shunkai Yao29d10572024-03-19 04:31:47 +00005085 if (chain->removeEffect(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005086 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07005087 mOrphanEffectChains.removeItemsAt(index);
5088 }
5089 return true;
5090 }
5091 return false;
5092}
5093
Andy Hung00b9aea2023-07-18 18:43:08 -07005094// ----------------------------------------------------------------------------
5095// from PatchPanel
5096
5097/* List connected audio ports and their attributes */
5098status_t AudioFlinger::listAudioPorts(unsigned int* num_ports,
5099 struct audio_port* ports) const
5100{
Andy Hung954b9712023-08-28 18:36:53 -07005101 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005102 return mPatchPanel->listAudioPorts_l(num_ports, ports);
Andy Hung00b9aea2023-07-18 18:43:08 -07005103}
5104
5105/* Get supported attributes for a given audio port */
5106status_t AudioFlinger::getAudioPort(struct audio_port_v7* port) const {
5107 const status_t status = AudioValidator::validateAudioPort(*port);
5108 if (status != NO_ERROR) {
5109 return status;
5110 }
5111
Andy Hung954b9712023-08-28 18:36:53 -07005112 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005113 return mPatchPanel->getAudioPort_l(port);
Andy Hung00b9aea2023-07-18 18:43:08 -07005114}
5115
5116/* Connect a patch between several source and sink ports */
5117status_t AudioFlinger::createAudioPatch(
5118 const struct audio_patch* patch, audio_patch_handle_t* handle)
5119{
5120 const status_t status = AudioValidator::validateAudioPatch(*patch);
5121 if (status != NO_ERROR) {
5122 return status;
5123 }
5124
Andy Hung954b9712023-08-28 18:36:53 -07005125 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005126 return mPatchPanel->createAudioPatch_l(patch, handle);
Andy Hung00b9aea2023-07-18 18:43:08 -07005127}
5128
5129/* Disconnect a patch */
5130status_t AudioFlinger::releaseAudioPatch(audio_patch_handle_t handle)
5131{
Andy Hung954b9712023-08-28 18:36:53 -07005132 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005133 return mPatchPanel->releaseAudioPatch_l(handle);
Andy Hung00b9aea2023-07-18 18:43:08 -07005134}
5135
5136/* List connected audio ports and they attributes */
5137status_t AudioFlinger::listAudioPatches(
5138 unsigned int* num_patches, struct audio_patch* patches) const
5139{
Andy Hung954b9712023-08-28 18:36:53 -07005140 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005141 return mPatchPanel->listAudioPatches_l(num_patches, patches);
Andy Hung00b9aea2023-07-18 18:43:08 -07005142}
Eric Laurentaaa44472014-09-12 17:41:50 -07005143
jiabin12537fc2023-10-12 17:56:08 +00005144/**
5145 * Get the attributes of the mix port when connecting to the given device port.
5146 */
5147status_t AudioFlinger::getAudioMixPort(const struct audio_port_v7 *devicePort,
5148 struct audio_port_v7 *mixPort) const {
5149 if (status_t status = AudioValidator::validateAudioPort(*devicePort); status != NO_ERROR) {
5150 ALOGE("%s, invalid device port, status=%d", __func__, status);
5151 return status;
5152 }
5153 if (status_t status = AudioValidator::validateAudioPort(*mixPort); status != NO_ERROR) {
5154 ALOGE("%s, invalid mix port, status=%d", __func__, status);
5155 return status;
5156 }
5157
5158 audio_utils::lock_guard _l(mutex());
5159 return mPatchPanel->getAudioMixPort_l(devicePort, mixPort);
5160}
5161
jiabin220eea12024-05-17 17:55:20 +00005162status_t AudioFlinger::setTracksInternalMute(
5163 const std::vector<media::TrackInternalMuteInfo>& tracksInternalMute) {
5164 audio_utils::lock_guard _l(mutex());
5165 ALOGV("%s", __func__);
5166
5167 std::map<audio_port_handle_t, bool> tracksInternalMuteMap;
5168 for (const auto& trackInternalMute : tracksInternalMute) {
5169 audio_port_handle_t portId = VALUE_OR_RETURN_STATUS(
5170 aidl2legacy_int32_t_audio_port_handle_t(trackInternalMute.portId));
5171 tracksInternalMuteMap.emplace(portId, trackInternalMute.muted);
5172 }
5173 for (size_t i = 0; i < mPlaybackThreads.size() && !tracksInternalMuteMap.empty(); i++) {
5174 mPlaybackThreads.valueAt(i)->setTracksInternalMute(&tracksInternalMuteMap);
5175 }
5176 return NO_ERROR;
5177}
5178
Shraddha Basantwania6dadac2024-06-06 16:28:52 +00005179status_t AudioFlinger::resetReferencesForTest() {
5180 mDeviceEffectManager.clear();
5181 mPatchPanel.clear();
5182 mMelReporter->resetReferencesForTest();
5183 return NO_ERROR;
5184}
5185
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186// ----------------------------------------------------------------------------
5187
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005188status_t AudioFlinger::onTransactWrapper(TransactionCode code,
Jing Mike537412f2023-03-12 11:01:47 +08005189 [[maybe_unused]] const Parcel& data,
5190 [[maybe_unused]] uint32_t flags,
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005191 const std::function<status_t()>& delegate) {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005192 // make sure transactions reserved to AudioPolicyManager do not come from other processes
5193 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005194 case TransactionCode::SET_STREAM_VOLUME:
5195 case TransactionCode::SET_STREAM_MUTE:
5196 case TransactionCode::OPEN_OUTPUT:
5197 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
5198 case TransactionCode::CLOSE_OUTPUT:
5199 case TransactionCode::SUSPEND_OUTPUT:
5200 case TransactionCode::RESTORE_OUTPUT:
5201 case TransactionCode::OPEN_INPUT:
5202 case TransactionCode::CLOSE_INPUT:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005203 case TransactionCode::SET_VOICE_VOLUME:
5204 case TransactionCode::MOVE_EFFECTS:
5205 case TransactionCode::SET_EFFECT_SUSPENDED:
5206 case TransactionCode::LOAD_HW_MODULE:
5207 case TransactionCode::GET_AUDIO_PORT:
5208 case TransactionCode::CREATE_AUDIO_PATCH:
5209 case TransactionCode::RELEASE_AUDIO_PATCH:
5210 case TransactionCode::LIST_AUDIO_PATCHES:
5211 case TransactionCode::SET_AUDIO_PORT_CONFIG:
5212 case TransactionCode::SET_RECORD_SILENCED:
Eric Laurentd66d7a12021-07-13 13:35:32 +02005213 case TransactionCode::AUDIO_POLICY_READY:
Mikhail Naganov516d3982022-02-01 23:53:59 +00005214 case TransactionCode::SET_DEVICE_CONNECTED_STATE:
Eric Laurent076e7c72022-05-03 18:12:28 +02005215 case TransactionCode::SET_REQUESTED_LATENCY_MODE:
5216 case TransactionCode::GET_SUPPORTED_LATENCY_MODES:
jiabinc44b3462022-12-08 12:52:31 -08005217 case TransactionCode::INVALIDATE_TRACKS:
Mikhail Naganovffd97712023-05-03 17:45:36 -07005218 case TransactionCode::GET_AUDIO_POLICY_CONFIG:
jiabin12537fc2023-10-12 17:56:08 +00005219 case TransactionCode::GET_AUDIO_MIX_PORT:
jiabin220eea12024-05-17 17:55:20 +00005220 case TransactionCode::SET_TRACKS_INTERNAL_MUTE:
Shraddha Basantwania6dadac2024-06-06 16:28:52 +00005221 case TransactionCode::RESET_REFERENCES_FOR_TEST:
Andy Hung6b137d12024-08-27 22:35:17 +00005222 case TransactionCode::SET_PORTS_VOLUME:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005223 ALOGW("%s: transaction %d received from PID %d",
Andy Hungf7786a42024-02-08 21:19:47 -08005224 __func__, static_cast<int>(code), IPCThreadState::self()->getCallingPid());
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005225 // return status only for non void methods
5226 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005227 case TransactionCode::SET_RECORD_SILENCED:
5228 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005229 break;
5230 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005231 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005232 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005233 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005234 return OK;
5235 default:
5236 break;
5237 }
5238
5239 // make sure the following transactions come from system components
5240 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005241 case TransactionCode::SET_MASTER_VOLUME:
5242 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08005243 case TransactionCode::MASTER_MUTE:
Vlad Popae3fd1c22022-11-07 21:03:18 +01005244 case TransactionCode::GET_SOUND_DOSE_INTERFACE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005245 case TransactionCode::SET_MODE:
5246 case TransactionCode::SET_MIC_MUTE:
5247 case TransactionCode::SET_LOW_RAM_DEVICE:
5248 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00005249 case TransactionCode::SET_AUDIO_HAL_PIDS:
jiabinf042b9b2021-05-07 23:46:28 +00005250 case TransactionCode::SET_VIBRATOR_INFOS:
Eric Laurent52057642022-12-16 11:45:07 +01005251 case TransactionCode::UPDATE_SECONDARY_OUTPUTS:
Eric Laurent50d72582022-12-20 20:20:23 +01005252 case TransactionCode::SET_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5253 case TransactionCode::IS_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5254 case TransactionCode::SUPPORTS_BLUETOOTH_VARIABLE_LATENCY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005255 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
5256 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
Andy Hungf7786a42024-02-08 21:19:47 -08005257 __func__, static_cast<int>(code),
5258 IPCThreadState::self()->getCallingPid(),
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005259 IPCThreadState::self()->getCallingUid());
Vlad Popa63f047e2022-11-05 14:09:19 +01005260 // return status only for non-void methods
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005261 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005262 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005263 break;
5264 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005265 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005266 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005267 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005268 return OK;
5269 }
5270 } break;
5271 default:
5272 break;
5273 }
5274
5275 // List of relevant events that trigger log merging.
5276 // Log merging should activate during audio activity of any kind. This are considered the
5277 // most relevant events.
5278 // TODO should select more wisely the items from the list
5279 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005280 case TransactionCode::CREATE_TRACK:
5281 case TransactionCode::CREATE_RECORD:
5282 case TransactionCode::SET_MASTER_VOLUME:
5283 case TransactionCode::SET_MASTER_MUTE:
5284 case TransactionCode::SET_MIC_MUTE:
5285 case TransactionCode::SET_PARAMETERS:
5286 case TransactionCode::CREATE_EFFECT:
5287 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005288 requestLogMerge();
5289 break;
5290 }
5291 default:
5292 break;
5293 }
5294
Andy Hungc747c532022-03-07 21:41:14 -08005295 const std::string methodName = getIAudioFlingerStatistics().getMethodForCode(code);
5296 mediautils::TimeCheck check(
5297 std::string("IAudioFlinger::").append(methodName),
5298 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
5299 if (timeout) {
5300 mediametrics::LogItem(mMetricsId)
5301 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
5302 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
5303 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
5304 .record();
5305 } else {
5306 getIAudioFlingerStatistics().event(code, elapsedMs);
5307 }
Andy Hung7cd77742024-08-06 15:17:16 -07005308 }, mediautils::TimeCheck::getDefaultTimeoutDuration(),
5309 mediautils::TimeCheck::getDefaultSecondChanceDuration(),
Atneya Nairc5b34362024-08-27 17:31:38 -07005310 !property_get_bool("audio.timecheck.disabled", false) /* crashOnTimeout */);
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005311
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005312 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313}
5314
Glenn Kasten63238ef2015-03-02 15:50:29 -08005315} // namespace android