blob: 1b28aca90604fef4cafa18bff7952bf459395794 [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
20
jiabina392a552019-09-23 10:34:20 -070021// Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
22#define AUDIO_ARRAYS_STATIC_CHECK 1
23
Glenn Kasten153b9fe2013-07-15 11:23:36 -070024#include "Configuration.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include "AudioFlinger.h"
Andy Hung9a57fc32023-07-19 18:02:19 -070026
27//#define BUFLOG_NDEBUG 0
28#include <afutils/BufLog.h>
29#include <afutils/DumpTryLock.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 Nair07c665d2024-05-17 15:46:48 -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 Nair07c665d2024-05-17 15:46:48 -070048#include <media/IPermissionProvider.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070049#include <media/MediaMetricsItem.h>
Atneya Nair07c665d2024-05-17 15:46:48 -070050#include <media/NativePermissionController.h>
Andy Hung9a57fc32023-07-19 18:02:19 -070051#include <media/TypeConverter.h>
Atneya Nair07c665d2024-05-17 15:46:48 -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>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080069
Mathias Agopian65ab4712010-07-14 17:59:35 -070070// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
John Grossman1c345192012-03-27 14:00:17 -070072// Note: the following macro is used for extremely verbose logging message. In
73// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
74// 0; but one side effect of this is to turn all LOGV's as well. Some messages
75// are so verbose that we want to suppress them even when we have ALOG_ASSERT
76// turned on. Do not uncomment the #def below unless you really know what you
77// are doing and want to see all of the extremely verbose messages.
78//#define VERY_VERY_VERBOSE_LOGGING
79#ifdef VERY_VERY_VERBOSE_LOGGING
80#define ALOGVV ALOGV
81#else
82#define ALOGVV(a...) do { } while(0)
83#endif
Eric Laurentde070132010-07-13 04:45:46 -070084
Mathias Agopian65ab4712010-07-14 17:59:35 -070085namespace android {
86
Andy Hung03410c02022-01-27 08:24:31 -080087using ::android::base::StringPrintf;
Atneya Nair07c665d2024-05-17 15:46:48 -070088using aidl_utils::statusTFromBinderStatus;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -070089using media::IEffectClient;
jiabine99d0882021-09-17 05:21:25 +000090using media::audio::common::AudioMMapPolicyInfo;
91using media::audio::common::AudioMMapPolicyType;
Mikhail Naganovffd97712023-05-03 17:45:36 -070092using media::audio::common::AudioMode;
Svet Ganov33761132021-05-13 22:51:08 +000093using android::content::AttributionSourceState;
Shunkai Yao2b8fed42022-12-09 01:12:02 +000094using android::detail::AudioHalVersionInfo;
Atneya Nair07c665d2024-05-17 15:46:48 -070095using com::android::media::permission::INativePermissionController;
96using com::android::media::permission::IPermissionProvider;
97using com::android::media::permission::NativePermissionController;
98using com::android::media::permission::ValidatedAttributionSourceState;
Shunkai Yao2b8fed42022-12-09 01:12:02 +000099
100static const AudioHalVersionInfo kMaxAAudioPropertyDeviceHalVersion =
101 AudioHalVersionInfo(AudioHalVersionInfo::Type::HIDL, 7, 1);
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700102
Vlad Popae8d99472022-06-30 16:02:48 +0200103static constexpr char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
104static constexpr char kHardwareLockedString[] = "Hardware lock is taken\n";
105static constexpr char kClientLockedString[] = "Client lock is taken\n";
106static constexpr char kNoEffectsFactory[] = "Effects Factory is absent\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Vlad Popae8d99472022-06-30 16:02:48 +0200108static constexpr char kAudioServiceName[] = "audio";
Glenn Kasten58912562012-04-03 10:45:00 -0700109
Eric Laurent813e2a72013-08-31 12:59:48 -0700110// In order to avoid invalidating offloaded tracks each time a Visualizer is turned on and off
111// we define a minimum time during which a global effect is considered enabled.
112static const nsecs_t kMinGlobalEffectEnabletimeNs = seconds(7200);
113
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700114// Keep a strong reference to media.log service around forever.
115// The service is within our parent process so it can never die in a way that we could observe.
116// These two variables are const after initialization.
117static sp<IBinder> sMediaLogServiceAsBinder;
118static sp<IMediaLogService> sMediaLogService;
119
120static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
121
122static void sMediaLogInit()
123{
124 sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
125 if (sMediaLogServiceAsBinder != 0) {
126 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
127 }
128}
129
Atneya Nair07c665d2024-05-17 15:46:48 -0700130static error::BinderResult<ValidatedAttributionSourceState>
131validateAttributionFromContextOrTrustedCaller(AttributionSourceState attr,
132 const IPermissionProvider& provider) {
133 const auto callingUid = IPCThreadState::self()->getCallingUid();
134 // We trust the following UIDs to appropriate validated identities above us
135 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
136 // Legacy paths may not properly populate package name, so we attempt to handle.
137 if (!attr.packageName.has_value() || attr.packageName.value() == "") {
138 ALOGW("Trusted client %d provided attr with missing package name" , callingUid);
139 attr.packageName = VALUE_OR_RETURN(provider.getPackagesForUid(callingUid))[0];
140 }
141 return ValidatedAttributionSourceState::createFromTrustedSource(std::move(attr));
142 } else {
143 return ValidatedAttributionSourceState::createFromBinderContext(std::move(attr), provider);
144 }
145}
146
147#define VALUE_OR_RETURN_CONVERTED(exp) \
148 ({ \
149 auto _tmp = (exp); \
150 if (!_tmp.ok()) { \
151 ALOGE("Function: %s Line: %d Failed result (%s)", __FUNCTION__, __LINE__, \
152 errorToString(_tmp.error()).c_str()); \
153 return statusTFromBinderStatus(_tmp.error()); \
154 } \
155 std::move(_tmp.value()); \
156 })
157
158
159
Andy Hungc747c532022-03-07 21:41:14 -0800160// Creates association between Binder code to name for IAudioFlinger.
161#define IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST \
162BINDER_METHOD_ENTRY(createTrack) \
163BINDER_METHOD_ENTRY(createRecord) \
164BINDER_METHOD_ENTRY(sampleRate) \
165BINDER_METHOD_ENTRY(format) \
166BINDER_METHOD_ENTRY(frameCount) \
167BINDER_METHOD_ENTRY(latency) \
168BINDER_METHOD_ENTRY(setMasterVolume) \
169BINDER_METHOD_ENTRY(setMasterMute) \
170BINDER_METHOD_ENTRY(masterVolume) \
171BINDER_METHOD_ENTRY(masterMute) \
172BINDER_METHOD_ENTRY(setStreamVolume) \
173BINDER_METHOD_ENTRY(setStreamMute) \
174BINDER_METHOD_ENTRY(streamVolume) \
175BINDER_METHOD_ENTRY(streamMute) \
176BINDER_METHOD_ENTRY(setMode) \
177BINDER_METHOD_ENTRY(setMicMute) \
178BINDER_METHOD_ENTRY(getMicMute) \
179BINDER_METHOD_ENTRY(setRecordSilenced) \
180BINDER_METHOD_ENTRY(setParameters) \
181BINDER_METHOD_ENTRY(getParameters) \
182BINDER_METHOD_ENTRY(registerClient) \
183BINDER_METHOD_ENTRY(getInputBufferSize) \
184BINDER_METHOD_ENTRY(openOutput) \
185BINDER_METHOD_ENTRY(openDuplicateOutput) \
186BINDER_METHOD_ENTRY(closeOutput) \
187BINDER_METHOD_ENTRY(suspendOutput) \
188BINDER_METHOD_ENTRY(restoreOutput) \
189BINDER_METHOD_ENTRY(openInput) \
190BINDER_METHOD_ENTRY(closeInput) \
Andy Hungc747c532022-03-07 21:41:14 -0800191BINDER_METHOD_ENTRY(setVoiceVolume) \
192BINDER_METHOD_ENTRY(getRenderPosition) \
193BINDER_METHOD_ENTRY(getInputFramesLost) \
194BINDER_METHOD_ENTRY(newAudioUniqueId) \
195BINDER_METHOD_ENTRY(acquireAudioSessionId) \
196BINDER_METHOD_ENTRY(releaseAudioSessionId) \
197BINDER_METHOD_ENTRY(queryNumberEffects) \
198BINDER_METHOD_ENTRY(queryEffect) \
199BINDER_METHOD_ENTRY(getEffectDescriptor) \
200BINDER_METHOD_ENTRY(createEffect) \
201BINDER_METHOD_ENTRY(moveEffects) \
202BINDER_METHOD_ENTRY(loadHwModule) \
203BINDER_METHOD_ENTRY(getPrimaryOutputSamplingRate) \
204BINDER_METHOD_ENTRY(getPrimaryOutputFrameCount) \
205BINDER_METHOD_ENTRY(setLowRamDevice) \
206BINDER_METHOD_ENTRY(getAudioPort) \
207BINDER_METHOD_ENTRY(createAudioPatch) \
208BINDER_METHOD_ENTRY(releaseAudioPatch) \
209BINDER_METHOD_ENTRY(listAudioPatches) \
210BINDER_METHOD_ENTRY(setAudioPortConfig) \
211BINDER_METHOD_ENTRY(getAudioHwSyncForSession) \
212BINDER_METHOD_ENTRY(systemReady) \
213BINDER_METHOD_ENTRY(audioPolicyReady) \
214BINDER_METHOD_ENTRY(frameCountHAL) \
215BINDER_METHOD_ENTRY(getMicrophones) \
216BINDER_METHOD_ENTRY(setMasterBalance) \
217BINDER_METHOD_ENTRY(getMasterBalance) \
218BINDER_METHOD_ENTRY(setEffectSuspended) \
219BINDER_METHOD_ENTRY(setAudioHalPids) \
220BINDER_METHOD_ENTRY(setVibratorInfos) \
221BINDER_METHOD_ENTRY(updateSecondaryOutputs) \
222BINDER_METHOD_ENTRY(getMmapPolicyInfos) \
223BINDER_METHOD_ENTRY(getAAudioMixerBurstCount) \
224BINDER_METHOD_ENTRY(getAAudioHardwareBurstMinUsec) \
225BINDER_METHOD_ENTRY(setDeviceConnectedState) \
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700226BINDER_METHOD_ENTRY(setSimulateDeviceConnections) \
Eric Laurent076e7c72022-05-03 18:12:28 +0200227BINDER_METHOD_ENTRY(setRequestedLatencyMode) \
228BINDER_METHOD_ENTRY(getSupportedLatencyModes) \
Eric Laurent50d72582022-12-20 20:20:23 +0100229BINDER_METHOD_ENTRY(setBluetoothVariableLatencyEnabled) \
230BINDER_METHOD_ENTRY(isBluetoothVariableLatencyEnabled) \
231BINDER_METHOD_ENTRY(supportsBluetoothVariableLatency) \
Vlad Popae3fd1c22022-11-07 21:03:18 +0100232BINDER_METHOD_ENTRY(getSoundDoseInterface) \
Mikhail Naganovffd97712023-05-03 17:45:36 -0700233BINDER_METHOD_ENTRY(getAudioPolicyConfig) \
jiabin12537fc2023-10-12 17:56:08 +0000234BINDER_METHOD_ENTRY(getAudioMixPort) \
Andy Hungc747c532022-03-07 21:41:14 -0800235
236// singleton for Binder Method Statistics for IAudioFlinger
237static auto& getIAudioFlingerStatistics() {
238 using Code = android::AudioFlingerServerAdapter::Delegate::TransactionCode;
239
240#pragma push_macro("BINDER_METHOD_ENTRY")
241#undef BINDER_METHOD_ENTRY
242#define BINDER_METHOD_ENTRY(ENTRY) \
243 {(Code)media::BnAudioFlingerService::TRANSACTION_##ENTRY, #ENTRY},
244
245 static mediautils::MethodStatistics<Code> methodStatistics{
246 IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST
247 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
248 };
249#pragma pop_macro("BINDER_METHOD_ENTRY")
250
251 return methodStatistics;
252}
253
Atneya Nair50ffdd12023-12-05 20:42:35 -0800254namespace base {
255template <typename T>
256struct OkOrFail<std::optional<T>> {
257 using opt_t = std::optional<T>;
258 OkOrFail() = delete;
259 OkOrFail(const opt_t&) = delete;
260
261 static bool IsOk(const opt_t& opt) { return opt.has_value(); }
262 static T Unwrap(opt_t&& opt) { return std::move(opt.value()); }
263 static std::string ErrorMessage(const opt_t&) { return "Empty optional"; }
264 static void Fail(opt_t&&) {}
265};
266}
267
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000268class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
269 public:
270 void onNewDevicesAvailable() override {
271 // Start a detached thread to execute notification in parallel.
272 // This is done to prevent mutual blocking of audio_flinger and
273 // audio_policy services during system initialization.
274 std::thread notifier([]() {
275 AudioSystem::onNewAudioModulesAvailable();
276 });
277 notifier.detach();
278 }
279};
280
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281// ----------------------------------------------------------------------------
282
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -0800283void AudioFlinger::instantiate() {
284 sp<IServiceManager> sm(defaultServiceManager());
285 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
286 new AudioFlingerServerAdapter(new AudioFlinger()), false,
287 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
288}
289
Mathias Agopian65ab4712010-07-14 17:59:35 -0700290AudioFlinger::AudioFlinger()
Mathias Agopian65ab4712010-07-14 17:59:35 -0700291{
Eric Laurentf43be0c2021-03-25 10:45:53 +0100292 // Move the audio session unique ID generator start base as time passes to limit risk of
293 // generating the same ID again after an audioserver restart.
294 // This is important because clients will reuse previously allocated audio session IDs
295 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
296 // active clients.
297 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
298 // between allocation ranges and not reaching wrap around too soon.
299 timespec ts{};
300 clock_gettime(CLOCK_MONOTONIC, &ts);
301 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
Eric Laurentf37f1982021-06-01 13:23:27 +0200302 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
Glenn Kastend2e67e12016-04-11 08:26:37 -0700303 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
304 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
Eric Laurentf43be0c2021-03-25 10:45:53 +0100305 mNextUniqueIds[use] =
Eric Laurentf37f1982021-06-01 13:23:27 +0200306 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
307 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
Glenn Kastend2e67e12016-04-11 08:26:37 -0700308 }
309
Eric Laurent94ca1142020-10-07 10:45:20 -0700310#if 1
311 // FIXME See bug 165702394 and bug 168511485
312 const bool doLog = false;
313#else
Glenn Kastenae0cff12016-02-24 13:57:49 -0800314 const bool doLog = property_get_bool("ro.test_harness", false);
Eric Laurent94ca1142020-10-07 10:45:20 -0700315#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800316 if (doLog) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800317 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
318 MemoryHeapBase::READ_ONLY);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700319 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800320 }
Eric Laurent1c333e22014-05-20 10:48:17 -0700321
Wei Jia3f273d12015-11-24 09:06:49 -0800322 // reset battery stats.
323 // if the audio service has crashed, battery stats could be left
324 // in bad state, reset the state upon service start.
325 BatteryNotifier::getInstance().noteResetAudio();
326
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -0800327 mMediaLogNotifier->run("MediaLogNotifier");
Andy Hungb68f5eb2019-12-03 16:49:17 -0800328
329 // Notify that we have started (also called when audioserver service restarts)
330 mediametrics::LogItem(mMetricsId)
331 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
332 .record();
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700333}
334
335void AudioFlinger::onFirstRef()
336{
Andy Hung954b9712023-08-28 18:36:53 -0700337 audio_utils::lock_guard _l(mutex());
Eric Laurent93575202011-01-18 18:39:02 -0800338
Eric Laurenta4c5a552012-03-29 10:12:40 -0700339 mMode = AUDIO_MODE_NORMAL;
Eric Laurentfc235202016-12-20 18:48:17 -0800340
Andy Hung6626a012021-01-12 13:38:00 -0800341 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
Andy Hung692f0452023-07-17 13:45:55 -0700342 mDeviceEffectManager = sp<DeviceEffectManager>::make(
343 sp<IAfDeviceEffectManagerCallback>::fromExisting(this)),
Mikhail Naganov88b30d22020-03-09 19:43:13 +0000344 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
345 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
jiabine504e7b2021-09-18 00:27:08 +0000346
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000347 if (mDevicesFactoryHal->getHalVersion() <= kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +0000348 mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty();
349 mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty();
350 }
Andy Hungb60a2c82023-07-17 14:02:52 -0700351
Andy Hung2dc61c42023-07-17 14:36:08 -0700352 mPatchPanel = IAfPatchPanel::create(sp<IAfPatchPanelCallback>::fromExisting(this));
Vlad Popa1c67ad62024-01-19 17:53:42 -0800353 mMelReporter = sp<MelReporter>::make(sp<IAfMelReporterCallback>::fromExisting(this),
354 mPatchPanel);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355}
356
Eric Laurent42896a02019-09-27 15:40:33 -0700357status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
Andy Hung5c6d68a2022-03-09 21:54:59 -0800358 mediautils::TimeCheck::setAudioHalPids(pids);
Eric Laurent42896a02019-09-27 15:40:33 -0700359 return NO_ERROR;
360}
361
jiabin1319f5a2021-03-30 22:21:24 +0000362status_t AudioFlinger::setVibratorInfos(
363 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
Andy Hung954b9712023-08-28 18:36:53 -0700364 audio_utils::lock_guard _l(mutex());
jiabin1319f5a2021-03-30 22:21:24 +0000365 mAudioVibratorInfos = vibratorInfos;
366 return NO_ERROR;
367}
368
jiabinf042b9b2021-05-07 23:46:28 +0000369status_t AudioFlinger::updateSecondaryOutputs(
370 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
Andy Hung954b9712023-08-28 18:36:53 -0700371 audio_utils::lock_guard _l(mutex());
jiabinf042b9b2021-05-07 23:46:28 +0000372 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
373 size_t i = 0;
374 for (; i < mPlaybackThreads.size(); ++i) {
Andy Hung87c693c2023-07-06 20:56:16 -0700375 IAfPlaybackThread* thread = mPlaybackThreads.valueAt(i).get();
Andy Hungc5007f82023-08-29 14:26:09 -0700376 audio_utils::lock_guard _tl(thread->mutex());
Andy Hungd29af632023-06-23 19:27:19 -0700377 sp<IAfTrack> track = thread->getTrackById_l(trackId);
jiabinf042b9b2021-05-07 23:46:28 +0000378 if (track != nullptr) {
379 ALOGD("%s trackId: %u", __func__, trackId);
380 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
381 break;
382 }
383 }
384 ALOGW_IF(i >= mPlaybackThreads.size(),
385 "%s cannot find track with id %u", __func__, trackId);
386 }
387 return NO_ERROR;
388}
389
Jiabin Huangebe64102021-09-07 20:01:07 +0000390status_t AudioFlinger::getMmapPolicyInfos(
jiabine99d0882021-09-17 05:21:25 +0000391 AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
Andy Hung954b9712023-08-28 18:36:53 -0700392 audio_utils::lock_guard _l(mutex());
Jiabin Huangebe64102021-09-07 20:01:07 +0000393 if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) {
394 *policyInfos = it->second;
395 return NO_ERROR;
396 }
Shunkai Yao2b8fed42022-12-09 01:12:02 +0000397 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
Andy Hung954b9712023-08-28 18:36:53 -0700398 audio_utils::lock_guard lock(hardwareMutex());
Jiabin Huangebe64102021-09-07 20:01:07 +0000399 for (size_t i = 0; i < mAudioHwDevs.size(); ++i) {
400 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
jiabine99d0882021-09-17 05:21:25 +0000401 std::vector<AudioMMapPolicyInfo> infos;
Jiabin Huangebe64102021-09-07 20:01:07 +0000402 status_t status = dev->getMmapPolicyInfos(policyType, &infos);
403 if (status != NO_ERROR) {
404 ALOGE("Failed to query mmap policy info of %d, error %d",
405 mAudioHwDevs.keyAt(i), status);
406 continue;
407 }
408 policyInfos->insert(policyInfos->end(), infos.begin(), infos.end());
409 }
410 mPolicyInfos[policyType] = *policyInfos;
411 } else {
412 getMmapPolicyInfosFromSystemProperty(policyType, policyInfos);
413 mPolicyInfos[policyType] = *policyInfos;
414 }
415 return NO_ERROR;
416}
417
Andy Hungcdd80ef2023-07-17 11:37:26 -0700418int32_t AudioFlinger::getAAudioMixerBurstCount() const {
Andy Hung954b9712023-08-28 18:36:53 -0700419 audio_utils::lock_guard _l(mutex());
jiabine504e7b2021-09-18 00:27:08 +0000420 return mAAudioBurstsPerBuffer;
421}
422
Andy Hungcdd80ef2023-07-17 11:37:26 -0700423int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() const {
Andy Hung954b9712023-08-28 18:36:53 -0700424 audio_utils::lock_guard _l(mutex());
jiabine504e7b2021-09-18 00:27:08 +0000425 return mAAudioHwBurstMinMicros;
426}
427
jiabinc0048632023-04-27 22:04:31 +0000428status_t AudioFlinger::setDeviceConnectedState(const struct audio_port_v7 *port,
429 media::DeviceConnectedState state) {
Mikhail Naganov516d3982022-02-01 23:53:59 +0000430 status_t final_result = NO_INIT;
Andy Hung954b9712023-08-28 18:36:53 -0700431 audio_utils::lock_guard _l(mutex());
432 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganov516d3982022-02-01 23:53:59 +0000433 mHardwareStatus = AUDIO_HW_SET_CONNECTED_STATE;
434 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
435 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
jiabinc0048632023-04-27 22:04:31 +0000436 status_t result = state == media::DeviceConnectedState::PREPARE_TO_DISCONNECT
437 ? dev->prepareToDisconnectExternalDevice(port)
438 : dev->setConnectedState(port, state == media::DeviceConnectedState::CONNECTED);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000439 // Same logic as with setParameter: it's a success if at least one
440 // HAL module accepts the update.
441 if (final_result != NO_ERROR) {
442 final_result = result;
443 }
444 }
445 mHardwareStatus = AUDIO_HW_IDLE;
446 return final_result;
447}
448
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700449status_t AudioFlinger::setSimulateDeviceConnections(bool enabled) {
450 bool at_least_one_succeeded = false;
451 status_t last_error = INVALID_OPERATION;
Andy Hung954b9712023-08-28 18:36:53 -0700452 audio_utils::lock_guard _l(mutex());
453 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovb1ddbb02023-03-15 17:06:59 -0700454 mHardwareStatus = AUDIO_HW_SET_SIMULATE_CONNECTIONS;
455 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
456 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
457 status_t result = dev->setSimulateDeviceConnections(enabled);
458 if (result == OK) {
459 at_least_one_succeeded = true;
460 } else {
461 last_error = result;
462 }
463 }
464 mHardwareStatus = AUDIO_HW_IDLE;
465 return at_least_one_succeeded ? OK : last_error;
466}
467
jiabin1319f5a2021-03-30 22:21:24 +0000468// getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
Andy Hung583043b2023-07-17 17:05:00 -0700469std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() const {
jiabin1319f5a2021-03-30 22:21:24 +0000470 if (mAudioVibratorInfos.empty()) {
Lais Andradebc3f37a2021-07-02 00:13:19 +0100471 return {};
jiabin1319f5a2021-03-30 22:21:24 +0000472 }
Lais Andradebc3f37a2021-07-02 00:13:19 +0100473 return mAudioVibratorInfos.front();
jiabin1319f5a2021-03-30 22:21:24 +0000474}
475
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476AudioFlinger::~AudioFlinger()
477{
478 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700479 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700480 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 }
482 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700483 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700484 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 }
Andy Hungb4946b62019-03-14 11:19:28 -0700486 while (!mMmapThreads.isEmpty()) {
487 const audio_io_handle_t io = mMmapThreads.keyAt(0);
488 if (mMmapThreads.valueAt(0)->isOutput()) {
489 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
490 } else {
491 closeInput_nonvirtual(io); // removes entry from mMmapThreads
492 }
493 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700494
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800495 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Andy Hung954b9712023-08-28 18:36:53 -0700496 // no hardwareMutex() needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700497 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700499
500 // Tell media.log service about any old writers that still need to be unregistered
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700501 if (sMediaLogService != 0) {
502 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
503 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
504 mUnregisteredWriters.pop();
505 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700506 }
507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508}
509
Eric Laurentfc235202016-12-20 18:48:17 -0800510//static
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511__attribute__ ((visibility ("default")))
Eric Laurentfc235202016-12-20 18:48:17 -0800512status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
513 const audio_attributes_t *attr,
514 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700515 const AudioClient& client,
Eric Laurentfc235202016-12-20 18:48:17 -0800516 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800517 audio_session_t *sessionId,
Eric Laurentfc235202016-12-20 18:48:17 -0800518 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700519 sp<MmapStreamInterface>& interface,
520 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800521{
Andy Hung9a57fc32023-07-19 18:02:19 -0700522 // TODO(b/292281786): Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
Andy Hung6626a012021-01-12 13:38:00 -0800523 // This allows moving oboeservice (AAudio) to a separate process in the future.
524 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
Eric Laurentfc235202016-12-20 18:48:17 -0800525 status_t ret = NO_INIT;
526 if (af != 0) {
527 ret = af->openMmapStream(
Phil Burk4e1af9f2018-01-03 15:54:35 -0800528 direction, attr, config, client, deviceId,
529 sessionId, callback, interface, handle);
Eric Laurentfc235202016-12-20 18:48:17 -0800530 }
531 return ret;
532}
533
Eric Laurent6acd1d42017-01-04 14:23:29 -0800534status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
535 const audio_attributes_t *attr,
536 audio_config_base_t *config,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700537 const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800538 audio_port_handle_t *deviceId,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800539 audio_session_t *sessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800540 const sp<MmapStreamCallback>& callback,
Eric Laurentcb4dae22017-07-01 19:39:32 -0700541 sp<MmapStreamInterface>& interface,
542 audio_port_handle_t *handle)
Eric Laurentfc235202016-12-20 18:48:17 -0800543{
544 status_t ret = initCheck();
545 if (ret != NO_ERROR) {
546 return ret;
547 }
Phil Burk4e1af9f2018-01-03 15:54:35 -0800548 audio_session_t actualSessionId = *sessionId;
549 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
550 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
551 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800552 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
Eric Laurentcb4dae22017-07-01 19:39:32 -0700553 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -0800554 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent42984412019-05-09 17:57:03 -0700555 audio_attributes_t localAttr = *attr;
Eric Laurent9ff3e532022-11-10 16:04:44 +0100556
557 // TODO b/182392553: refactor or make clearer
Atneya Nair07c665d2024-05-17 15:46:48 -0700558 AttributionSourceState adjAttributionSource;
559 if (!com::android::media::audio::audioserver_permissions()) {
560 pid_t clientPid =
561 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(client.attributionSource.pid));
562 bool updatePid = (clientPid == (pid_t)-1);
563 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
Eric Laurent9ff3e532022-11-10 16:04:44 +0100564
Atneya Nair07c665d2024-05-17 15:46:48 -0700565 adjAttributionSource = client.attributionSource;
566 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
567 uid_t clientUid =
568 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(client.attributionSource.uid));
569 ALOGW_IF(clientUid != callingUid,
570 "%s uid %d tried to pass itself off as %d",
571 __FUNCTION__, callingUid, clientUid);
572 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
573 legacy2aidl_uid_t_int32_t(callingUid));
574 updatePid = true;
575 }
576 if (updatePid) {
577 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
578 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
579 "%s uid %d pid %d tried to pass itself off as pid %d",
580 __func__, callingUid, callingPid, clientPid);
581 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
582 legacy2aidl_pid_t_int32_t(callingPid));
583 }
584 adjAttributionSource = afutils::checkAttributionSourcePackage(
Eric Laurent9ff3e532022-11-10 16:04:44 +0100585 adjAttributionSource);
Atneya Nair07c665d2024-05-17 15:46:48 -0700586 } else {
587 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
588 validateAttributionFromContextOrTrustedCaller(client.attributionSource,
589 getPermissionProvider()
590 ));
591 // TODO pass wrapped object around
592 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
593 }
Eric Laurent9ff3e532022-11-10 16:04:44 +0100594
Eric Laurent6acd1d42017-01-04 14:23:29 -0800595 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
596 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
597 fullConfig.sample_rate = config->sample_rate;
598 fullConfig.channel_mask = config->channel_mask;
599 fullConfig.format = config->format;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800600 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +0200601 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +0000602 bool isBitPerfect;
Eric Laurent42984412019-05-09 17:57:03 -0700603 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800604 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100605 &streamType, adjAttributionSource,
Ricardo Correa57a37692020-03-23 17:27:25 -0700606 &fullConfig,
Glenn Kastend3bb6452016-12-05 18:14:37 -0800607 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
608 AUDIO_OUTPUT_FLAG_DIRECT),
jiabinc658e452022-10-21 20:52:21 +0000609 deviceId, &portId, &secondaryOutputs, &isSpatialized,
610 &isBitPerfect);
jiabinf1c73972022-04-14 16:28:52 -0700611 if (ret != NO_ERROR) {
612 config->sample_rate = fullConfig.sample_rate;
613 config->channel_mask = fullConfig.channel_mask;
614 config->format = fullConfig.format;
615 }
Kevin Rocard153f92d2018-12-18 18:33:28 -0800616 ALOGW_IF(!secondaryOutputs.empty(),
617 "%s does not support secondary outputs, ignoring them", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800618 } else {
Eric Laurent42984412019-05-09 17:57:03 -0700619 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -0700620 RECORD_RIID_INVALID,
Phil Burk4e1af9f2018-01-03 15:54:35 -0800621 actualSessionId,
Eric Laurent9ff3e532022-11-10 16:04:44 +0100622 adjAttributionSource,
Eric Laurent6acd1d42017-01-04 14:23:29 -0800623 config,
Eric Laurent2ac76942017-06-22 17:17:09 -0700624 AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800625 }
626 if (ret != NO_ERROR) {
627 return ret;
628 }
629
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700630 // use unique_lock as we may selectively unlock.
631 audio_utils::unique_lock l(mutex());
632
Eric Laurent6acd1d42017-01-04 14:23:29 -0800633 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
634 // audio policy manager and we can retrieve it
Andy Hung7aa7d102023-07-07 15:58:48 -0700635 const sp<IAfMmapThread> thread = mMmapThreads.valueFor(io);
Eric Laurent6acd1d42017-01-04 14:23:29 -0800636 if (thread != 0) {
Andy Hung7aa7d102023-07-07 15:58:48 -0700637 interface = IAfMmapThread::createMmapStreamInterfaceAdapter(thread);
Eric Laurent42984412019-05-09 17:57:03 -0700638 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceId, portId);
Eric Laurentcb4dae22017-07-01 19:39:32 -0700639 *handle = portId;
Phil Burk4e1af9f2018-01-03 15:54:35 -0800640 *sessionId = actualSessionId;
Eric Laurenta7a89e22020-01-08 18:39:20 -0800641 config->sample_rate = thread->sampleRate();
642 config->channel_mask = thread->channelMask();
643 config->format = thread->format();
Eric Laurent6acd1d42017-01-04 14:23:29 -0800644 } else {
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700645 l.unlock();
Eric Laurentad2e7b92017-09-14 20:06:42 -0700646 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
Eric Laurentd7fe0862018-07-14 16:48:01 -0700647 AudioSystem::releaseOutput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700648 } else {
Eric Laurentfee19762018-01-29 18:44:13 -0800649 AudioSystem::releaseInput(portId);
Eric Laurentad2e7b92017-09-14 20:06:42 -0700650 }
Eric Laurent6acd1d42017-01-04 14:23:29 -0800651 ret = NO_INIT;
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700652 // we don't reacquire the lock here as nothing left to do.
Eric Laurent6acd1d42017-01-04 14:23:29 -0800653 }
654
655 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
656
Eric Laurentfc235202016-12-20 18:48:17 -0800657 return ret;
658}
659
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700660status_t AudioFlinger::addEffectToHal(
661 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
Andy Hung954b9712023-08-28 18:36:53 -0700662 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700663 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800664 if (audioHwDevice == nullptr) {
665 return NO_INIT;
666 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700667 return audioHwDevice->hwDevice()->addDeviceEffect(device, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800668}
669
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700670status_t AudioFlinger::removeEffectFromHal(
671 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
Andy Hung954b9712023-08-28 18:36:53 -0700672 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700673 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800674 if (audioHwDevice == nullptr) {
675 return NO_INIT;
676 }
Mikhail Naganovd2c7f852023-06-14 18:00:13 -0700677 return audioHwDevice->hwDevice()->removeDeviceEffect(device, effect);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800678}
679
Eric Laurenta4c5a552012-03-29 10:12:40 -0700680static const char * const audio_interfaces[] = {
681 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
682 AUDIO_HARDWARE_MODULE_ID_A2DP,
683 AUDIO_HARDWARE_MODULE_ID_USB,
684};
Eric Laurenta4c5a552012-03-29 10:12:40 -0700685
Phil Burk062e67a2015-02-11 13:40:50 -0800686AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
John Grossmanee578c02012-07-23 17:05:46 -0700687 audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -0700688 audio_devices_t deviceType)
Dima Zavin799a70e2011-04-18 16:57:27 -0700689{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700690 // if module is 0, the request comes from an old policy manager and we should load
691 // well known modules
Andy Hung954b9712023-08-28 18:36:53 -0700692 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -0700693 if (module == 0) {
694 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
Mikhail Naganovbf493082017-04-17 17:37:12 -0700695 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700696 loadHwModule_ll(audio_interfaces[i]);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700697 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700698 // then try to find a module supporting the requested device.
699 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
700 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700701 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
702 uint32_t supportedDevices;
703 if (dev->getSupportedDevices(&supportedDevices) == OK &&
jiabin43810402019-10-24 14:58:31 -0700704 (supportedDevices & deviceType) == deviceType) {
Eric Laurentf1c04f92012-08-28 14:26:53 -0700705 return audioHwDevice;
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700706 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700707 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700708 } else {
709 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700710 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
711 if (audioHwDevice != NULL) {
712 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700713 }
714 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700715
Dima Zavin799a70e2011-04-18 16:57:27 -0700716 return NULL;
717}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700719void AudioFlinger::dumpClients_ll(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 String8 result;
722
Atneya Nair9ec58d52022-10-03 15:46:20 -0700723 result.append("Client Allocators:\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800725 sp<Client> client = mClients.valueAt(i).promote();
726 if (client != 0) {
Atneya Nair9ec58d52022-10-03 15:46:20 -0700727 result.appendFormat("Client: %d\n", client->pid());
Atneya3c61d882021-09-20 14:52:15 -0400728 result.append(client->allocator().dump().c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 }
Atneya3c61d882021-09-20 14:52:15 -0400730 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700731
Eric Laurentd1b28d42013-09-18 18:47:13 -0700732 result.append("Notification Clients:\n");
Andy Hung5bdc5352019-12-23 14:36:31 -0800733 result.append(" pid uid name\n");
Eric Laurentd1b28d42013-09-18 18:47:13 -0700734 for (size_t i = 0; i < mNotificationClients.size(); ++i) {
Andy Hung5bdc5352019-12-23 14:36:31 -0800735 const pid_t pid = mNotificationClients[i]->getPid();
736 const uid_t uid = mNotificationClients[i]->getUid();
737 const mediautils::UidInfo::Info info = mUidInfo.getInfo(uid);
738 result.appendFormat("%6d %6u %s\n", pid, uid, info.package.c_str());
Eric Laurentd1b28d42013-09-18 18:47:13 -0700739 }
740
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700741 result.append("Global session refs:\n");
Andy Hung8b0bfd92019-12-23 13:11:11 -0800742 result.append(" session cnt pid uid name\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700743 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
744 AudioSessionRef *r = mAudioSessionRefs[i];
Andy Hung8b0bfd92019-12-23 13:11:11 -0800745 const mediautils::UidInfo::Info info = mUidInfo.getInfo(r->mUid);
746 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
747 r->mUid, info.package.c_str());
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700748 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000749 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750}
751
752
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700753void AudioFlinger::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754{
755 const size_t SIZE = 256;
756 char buffer[SIZE];
757 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800758 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759
Andy Hung8fe87eb2023-07-20 21:31:38 -0700760 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000762 write(fd, result.c_str(), result.size());
jiabinc47acf22022-04-01 23:47:52 +0000763
764 dprintf(fd, "Vibrator infos(size=%zu):\n", mAudioVibratorInfos.size());
765 for (const auto& vibratorInfo : mAudioVibratorInfos) {
766 dprintf(fd, " - %s\n", vibratorInfo.toString().c_str());
767 }
Eric Laurent90cea102023-05-15 15:08:27 +0200768 dprintf(fd, "Bluetooth latency modes are %senabled\n",
769 mBluetoothLatencyModesEnabled ? "" : "not ");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770}
771
Glenn Kasten0f11b512014-01-31 16:18:54 -0800772void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773{
774 const size_t SIZE = 256;
775 char buffer[SIZE];
776 String8 result;
777 snprintf(buffer, SIZE, "Permission Denial: "
778 "can't dump AudioFlinger from pid=%d, uid=%d\n",
779 IPCThreadState::self()->getCallingPid(),
780 IPCThreadState::self()->getCallingUid());
781 result.append(buffer);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000782 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783}
784
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -0700786NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787{
Glenn Kasten44deb052012-02-05 18:09:08 -0800788 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789 dumpPermissionDenial(fd, args);
790 } else {
791 // get state of hardware lock
Andy Hung954b9712023-08-28 18:36:53 -0700792 const bool hardwareLocked = afutils::dumpTryLock(hardwareMutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 if (!hardwareLocked) {
794 String8 result(kHardwareLockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000795 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 } else {
Andy Hung954b9712023-08-28 18:36:53 -0700797 hardwareMutex().unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700798 }
799
Andy Hung954b9712023-08-28 18:36:53 -0700800 const bool locked = afutils::dumpTryLock(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801
802 // failed to lock - AudioFlinger is probably deadlocked
803 if (!locked) {
804 String8 result(kDeadlockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000805 write(fd, result.c_str(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 }
807
Andy Hung954b9712023-08-28 18:36:53 -0700808 const bool clientLocked = afutils::dumpTryLock(clientMutex());
Eric Laurent021cf962014-05-13 10:18:14 -0700809 if (!clientLocked) {
810 String8 result(kClientLockedString);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000811 write(fd, result.c_str(), result.size());
Eric Laurent021cf962014-05-13 10:18:14 -0700812 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700813
Mikhail Naganov1dc98672016-08-18 17:50:29 -0700814 if (mEffectsFactoryHal != 0) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700815 mEffectsFactoryHal->dumpEffects(fd);
816 } else {
817 String8 result(kNoEffectsFactory);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000818 write(fd, result.c_str(), result.size());
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -0700819 }
Marco Nelissend89eadd2014-10-07 13:28:44 -0700820
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700821 dumpClients_ll(fd, args);
Eric Laurent021cf962014-05-13 10:18:14 -0700822 if (clientLocked) {
Andy Hung954b9712023-08-28 18:36:53 -0700823 clientMutex().unlock();
Eric Laurent021cf962014-05-13 10:18:14 -0700824 }
825
Andy Hungc2cf7ec2023-08-30 18:19:00 -0700826 dumpInternals_l(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827
828 // dump playback threads
829 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
830 mPlaybackThreads.valueAt(i)->dump(fd, args);
831 }
832
833 // dump record threads
834 for (size_t i = 0; i < mRecordThreads.size(); i++) {
835 mRecordThreads.valueAt(i)->dump(fd, args);
836 }
837
Eric Laurent6acd1d42017-01-04 14:23:29 -0800838 // dump mmap threads
839 for (size_t i = 0; i < mMmapThreads.size(); i++) {
840 mMmapThreads.valueAt(i)->dump(fd, args);
841 }
842
Eric Laurentaaa44472014-09-12 17:41:50 -0700843 // dump orphan effect chains
844 if (mOrphanEffectChains.size() != 0) {
845 write(fd, " Orphan Effect Chains\n", strlen(" Orphan Effect Chains\n"));
846 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
847 mOrphanEffectChains.valueAt(i)->dump(fd, args);
848 }
849 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700850 // dump all hardware devs
851 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -0700852 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Andy Hung61589a42021-06-16 09:37:53 -0700853 dev->dump(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700855
Andy Hungb6692eb2023-07-13 16:52:46 -0700856 mPatchPanel->dump(fd);
Mikhail Naganov201369b2018-05-16 16:52:32 -0700857
Vlad Popa5161f8a2022-10-10 16:17:20 +0200858 mDeviceEffectManager->dump(fd);
Eric Laurentb82e6b72019-11-22 17:25:04 -0800859
Vlad Popab042ee62022-10-20 18:05:00 +0200860 std::string melOutput = mMelReporter->dump();
861 write(fd, melOutput.c_str(), melOutput.size());
862
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -0700863 // dump external setParameters
864 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
865 dprintf(fd, "\n%s setParameters:\n", name);
866 logger.dump(fd, " " /* prefix */);
867 };
868 dumpLogger(mRejectedSetParameterLog, "Rejected");
869 dumpLogger(mAppSetParameterLog, "App");
870 dumpLogger(mSystemSetParameterLog, "System");
871
Andy Hunga8115dc2018-08-24 15:51:59 -0700872 // dump historical threads in the last 10 seconds
873 const std::string threadLog = mThreadLog.dumpToString(
874 "Historical Thread Log ", 0 /* lines */,
875 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND);
876 write(fd, threadLog.c_str(), threadLog.size());
877
rago3bd1c872016-09-26 12:58:14 -0700878 BUFLOG_RESET;
879
Glenn Kastend65d73c2012-06-22 17:21:07 -0700880 if (locked) {
Andy Hung954b9712023-08-28 18:36:53 -0700881 mutex().unlock();
Glenn Kastend65d73c2012-06-22 17:21:07 -0700882 }
Glenn Kasten9e58b552013-01-18 15:09:48 -0800883
Andy Hung8946a282018-04-19 20:04:56 -0700884#ifdef TEE_SINK
885 // NBAIO_Tee dump is safe to call outside of AF lock.
886 NBAIO_Tee::dumpAll(fd, "_DUMP");
887#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -0800888 // append a copy of media.log here by forwarding fd to it, but don't attempt
889 // to lookup the service if it's not running, as it will block for a second
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700890 if (sMediaLogServiceAsBinder != 0) {
891 dprintf(fd, "\nmedia.log:\n");
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700892 sMediaLogServiceAsBinder->dump(fd, args);
Glenn Kasten9e58b552013-01-18 15:09:48 -0800893 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700894
895 // check for optional arguments
Andy Hung07b745e2016-05-23 16:21:07 -0700896 bool dumpMem = false;
Andy Hung35fec5f2016-04-13 14:21:48 -0700897 bool unreachableMemory = false;
898 for (const auto &arg : args) {
Andy Hung07b745e2016-05-23 16:21:07 -0700899 if (arg == String16("-m")) {
900 dumpMem = true;
901 } else if (arg == String16("--unreachable")) {
Andy Hung35fec5f2016-04-13 14:21:48 -0700902 unreachableMemory = true;
903 }
904 }
905
Andy Hung07b745e2016-05-23 16:21:07 -0700906 if (dumpMem) {
907 dprintf(fd, "\nDumping memory:\n");
908 std::string s = dumpMemoryAddresses(100 /* limit */);
909 write(fd, s.c_str(), s.size());
910 }
Andy Hung35fec5f2016-04-13 14:21:48 -0700911 if (unreachableMemory) {
912 dprintf(fd, "\nDumping unreachable memory:\n");
913 // TODO - should limit be an argument parameter?
Andy Hung07b745e2016-05-23 16:21:07 -0700914 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
Andy Hung35fec5f2016-04-13 14:21:48 -0700915 write(fd, s.c_str(), s.size());
916 }
Andy Hungc747c532022-03-07 21:41:14 -0800917 {
918 std::string timeCheckStats = getIAudioFlingerStatistics().dump();
Andy Hung224f82f2022-03-22 00:00:49 -0700919 dprintf(fd, "\nIAudioFlinger binder call profile:\n");
Andy Hungc747c532022-03-07 21:41:14 -0800920 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
921
922 extern mediautils::MethodStatistics<int>& getIEffectStatistics();
923 timeCheckStats = getIEffectStatistics().dump();
Andy Hung224f82f2022-03-22 00:00:49 -0700924 dprintf(fd, "\nIEffect binder call profile:\n");
Andy Hungc747c532022-03-07 21:41:14 -0800925 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
Andy Hung224f82f2022-03-22 00:00:49 -0700926
Shunkai Yaod4532c82023-12-17 20:01:45 +0000927 // Automatically fetch HIDL or AIDL statistics.
928 const std::string_view halType = (mDevicesFactoryHal->getHalVersion().getType() ==
929 AudioHalVersionInfo::Type::HIDL)
930 ? METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL
931 : METHOD_STATISTICS_MODULE_NAME_AUDIO_AIDL;
932 const std::shared_ptr<std::vector<std::string>> halClassNames =
933 mediautils::getStatisticsClassesForModule(halType);
934 if (halClassNames) {
935 for (const auto& className : *halClassNames) {
Andy Hung224f82f2022-03-22 00:00:49 -0700936 auto stats = mediautils::getStatisticsForClass(className);
937 if (stats) {
938 timeCheckStats = stats->dump();
939 dprintf(fd, "\n%s binder call profile:\n", className.c_str());
940 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
941 }
942 }
943 }
944
945 timeCheckStats = mediautils::TimeCheck::toString();
946 dprintf(fd, "\nTimeCheck:\n");
947 write(fd, timeCheckStats.c_str(), timeCheckStats.size());
948 dprintf(fd, "\n");
Andy Hungc747c532022-03-07 21:41:14 -0800949 }
Andy Hungfba891d2023-10-12 18:18:13 -0700950 // dump mutex stats
951 const auto mutexStats = audio_utils::mutex::all_stats_to_string();
952 write(fd, mutexStats.c_str(), mutexStats.size());
Andy Hungc6877d62023-10-17 18:43:12 -0700953
954 // dump held mutexes
955 const auto mutexThreadInfo = audio_utils::mutex::all_threads_to_string();
956 write(fd, mutexThreadInfo.c_str(), mutexThreadInfo.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957 }
958 return NO_ERROR;
959}
960
Andy Hung59867e42023-06-27 17:05:02 -0700961sp<Client> AudioFlinger::registerPid(pid_t pid)
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800962{
Andy Hung954b9712023-08-28 18:36:53 -0700963 audio_utils::lock_guard _cl(clientMutex());
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800964 // If pid is already in the mClients wp<> map, then use that entry
965 // (for which promote() is always != 0), otherwise create a new entry and Client.
966 sp<Client> client = mClients.valueFor(pid).promote();
967 if (client == 0) {
Andy Hung47c01172023-07-17 12:40:43 -0700968 client = sp<Client>::make(sp<IAfClientCallback>::fromExisting(this), pid);
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800969 mClients.add(pid, client);
970 }
971
972 return client;
973}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974
Glenn Kasten9e58b552013-01-18 15:09:48 -0800975sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
976{
Jiabin Huang60766082020-07-28 22:03:56 +0000977 // If there is no memory allocated for logs, return a no-op writer that does nothing.
978 // Similarly if we can't contact the media.log service, also return a no-op writer.
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700979 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
Glenn Kasten9e58b552013-01-18 15:09:48 -0800980 return new NBLog::Writer();
981 }
Glenn Kasten481fb672013-09-30 14:39:28 -0700982 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
983 // If allocation fails, consult the vector of previously unregistered writers
984 // and garbage-collect one or more them until an allocation succeeds
985 if (shared == 0) {
Andy Hung954b9712023-08-28 18:36:53 -0700986 audio_utils::lock_guard _l(unregisteredWritersMutex());
Glenn Kasten481fb672013-09-30 14:39:28 -0700987 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
988 {
989 // Pick the oldest stale writer to garbage-collect
990 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
991 mUnregisteredWriters.removeAt(0);
Glenn Kasten04b96fc2017-04-10 14:58:47 -0700992 sMediaLogService->unregisterWriter(iMemory);
Glenn Kasten481fb672013-09-30 14:39:28 -0700993 // Now the media.log remote reference to IMemory is gone. When our last local
994 // reference to IMemory also drops to zero at end of this block,
995 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
996 }
997 // Re-attempt the allocation
998 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
999 if (shared != 0) {
1000 goto success;
1001 }
1002 }
1003 // Even after garbage-collecting all old writers, there is still not enough memory,
Jiabin Huang60766082020-07-28 22:03:56 +00001004 // so return a no-op writer
Glenn Kasten481fb672013-09-30 14:39:28 -07001005 return new NBLog::Writer();
1006 }
1007success:
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07001008 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
Glenn Kasten535e1612016-12-05 12:19:36 -08001009 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
1010 // explicit destructor not needed since it is POD
Glenn Kasten04b96fc2017-04-10 14:58:47 -07001011 sMediaLogService->registerWriter(shared, size, name);
Glenn Kasten535e1612016-12-05 12:19:36 -08001012 return new NBLog::Writer(shared, size);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001013}
1014
1015void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
1016{
Glenn Kasten685ef092013-02-04 08:15:34 -08001017 if (writer == 0) {
1018 return;
1019 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08001020 sp<IMemory> iMemory(writer->getIMemory());
1021 if (iMemory == 0) {
1022 return;
1023 }
Glenn Kasten481fb672013-09-30 14:39:28 -07001024 // Rather than removing the writer immediately, append it to a queue of old writers to
1025 // be garbage-collected later. This allows us to continue to view old logs for a while.
Andy Hung954b9712023-08-28 18:36:53 -07001026 audio_utils::lock_guard _l(unregisteredWritersMutex());
Glenn Kasten481fb672013-09-30 14:39:28 -07001027 mUnregisteredWriters.push(writer);
Glenn Kasten9e58b552013-01-18 15:09:48 -08001028}
1029
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030// IAudioFlinger interface
1031
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001032status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
1033 media::CreateTrackResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034{
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001035 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08001036 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001037 CreateTrackOutput output;
1038
Andy Hungd29af632023-06-23 19:27:19 -07001039 sp<IAfTrack> track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041 status_t lStatus;
Eric Laurent21da6472017-11-09 16:29:26 -08001042 audio_stream_type_t streamType;
Eric Laurent77881cd2018-02-09 16:01:31 -08001043 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001044 std::vector<audio_io_handle_t> secondaryOutputs;
jiabinc658e452022-10-21 20:52:21 +00001045 bool isSpatialized = false;
1046 bool isBitPerfect = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
Eric Laurent6c796322019-04-09 14:13:17 -07001048 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
1049 std::vector<int> effectIds;
Eric Laurent42984412019-05-09 17:57:03 -07001050 audio_attributes_t localAttr = input.attr;
Eric Laurent6c796322019-04-09 14:13:17 -07001051
Atneya Nair07c665d2024-05-17 15:46:48 -07001052 AttributionSourceState adjAttributionSource;
1053 pid_t clientPid;
1054 pid_t callingPid;
1055 if (!com::android::media::audio::audioserver_permissions()) {
1056 adjAttributionSource = input.clientInfo.attributionSource;
1057 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1058 uid_t clientUid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(
1059 input.clientInfo.attributionSource.uid));
1060 clientPid =
1061 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
1062 input.clientInfo.attributionSource.pid));
1063 bool updatePid = (clientPid == (pid_t)-1);
1064
1065 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
1066 ALOGW_IF(clientUid != callingUid,
1067 "%s uid %d tried to pass itself off as %d",
1068 __FUNCTION__, callingUid, clientUid);
1069 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
1070 legacy2aidl_uid_t_int32_t(callingUid));
1071 clientUid = callingUid;
1072 updatePid = true;
1073 }
1074 callingPid = IPCThreadState::self()->getCallingPid();
1075 if (updatePid) {
1076 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
1077 "%s uid %d pid %d tried to pass itself off as pid %d",
1078 __func__, callingUid, callingPid, clientPid);
1079 clientPid = callingPid;
1080 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
1081 legacy2aidl_pid_t_int32_t(callingPid));
1082 }
1083 adjAttributionSource = afutils::checkAttributionSourcePackage(
1084 adjAttributionSource);
1085
1086 } else {
1087 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
1088 validateAttributionFromContextOrTrustedCaller(input.clientInfo.attributionSource,
1089 getPermissionProvider()
1090 ));
1091 // TODO pass wrapped object around
1092 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
1093 clientPid = adjAttributionSource.pid;
1094 callingPid = adjAttributionSource.pid;
Eric Laurent21da6472017-11-09 16:29:26 -08001095 }
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07001096
Eric Laurent21da6472017-11-09 16:29:26 -08001097 audio_session_t sessionId = input.sessionId;
1098 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1099 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
Eric Laurentf14db3c2017-12-08 14:20:36 -08001100 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1101 lStatus = BAD_VALUE;
1102 goto Exit;
Eric Laurent21da6472017-11-09 16:29:26 -08001103 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08001104
Eric Laurent21da6472017-11-09 16:29:26 -08001105 output.sessionId = sessionId;
1106 output.outputId = AUDIO_IO_HANDLE_NONE;
1107 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent42984412019-05-09 17:57:03 -07001108 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
Svet Ganov33761132021-05-13 22:51:08 +00001109 adjAttributionSource, &input.config, input.flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001110 &output.selectedDeviceId, &portId, &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +00001111 &isSpatialized, &isBitPerfect);
Eric Laurent21da6472017-11-09 16:29:26 -08001112
1113 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1114 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
1115 goto Exit;
1116 }
Glenn Kasten263709e2012-01-06 08:40:01 -08001117 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
1118 // but if someone uses binder directly they could bypass that and cause us to crash
1119 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +00001120 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 lStatus = BAD_VALUE;
1122 goto Exit;
1123 }
1124
Glenn Kasten53b5d092014-02-05 10:00:23 -08001125 // further channel mask checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001126 if (!audio_is_output_channel(input.config.channel_mask)) {
1127 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08001128 lStatus = BAD_VALUE;
1129 goto Exit;
1130 }
1131
Glenn Kastenc4b88a82014-04-30 16:54:30 -07001132 // further format checks are performed by createTrack_l() depending on the thread type
Eric Laurent21da6472017-11-09 16:29:26 -08001133 if (!audio_is_valid_format(input.config.format)) {
1134 ALOGE("createTrack() invalid format %#x", input.config.format);
Glenn Kasten663c2242013-09-24 11:52:37 -07001135 lStatus = BAD_VALUE;
1136 goto Exit;
1137 }
1138
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 {
Andy Hung954b9712023-08-28 18:36:53 -07001140 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001141 IAfPlaybackThread* thread = checkPlaybackThread_l(output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142 if (thread == NULL) {
Eric Laurent21da6472017-11-09 16:29:26 -08001143 ALOGE("no playback thread found for output handle %d", output.outputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001144 lStatus = BAD_VALUE;
1145 goto Exit;
1146 }
1147
Eric Laurent21da6472017-11-09 16:29:26 -08001148 client = registerPid(clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149
Andy Hung87c693c2023-07-06 20:56:16 -07001150 IAfPlaybackThread* effectThread = nullptr;
Shunkai Yao29d10572024-03-19 04:31:47 +00001151 sp<IAfEffectChain> effectChain = nullptr;
Eric Laurent21da6472017-11-09 16:29:26 -08001152 // check if an effect chain with the same session ID is present on another
1153 // output thread and move it here.
1154 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07001155 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
Eric Laurent21da6472017-11-09 16:29:26 -08001156 if (mPlaybackThreads.keyAt(i) != output.outputId) {
1157 uint32_t sessions = t->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07001158 if (sessions & IAfThreadBase::EFFECT_SESSION) {
Eric Laurent21da6472017-11-09 16:29:26 -08001159 effectThread = t.get();
1160 break;
Eric Laurentde070132010-07-13 04:45:46 -07001161 }
1162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 }
Shunkai Yao29d10572024-03-19 04:31:47 +00001164 // Check if an orphan effect chain exists for this session
1165 if (effectThread == nullptr) {
1166 effectChain = getOrphanEffectChain_l(sessionId);
1167 }
Eric Laurent21da6472017-11-09 16:29:26 -08001168 ALOGV("createTrack() sessionId: %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169
Eric Laurent21da6472017-11-09 16:29:26 -08001170 output.sampleRate = input.config.sample_rate;
1171 output.frameCount = input.frameCount;
1172 output.notificationFrameCount = input.notificationFrameCount;
1173 output.flags = input.flags;
Andy Hunga2159aa2021-07-20 13:01:52 -07001174 output.streamType = streamType;
Eric Laurent21da6472017-11-09 16:29:26 -08001175
Eric Laurent42984412019-05-09 17:57:03 -07001176 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001177 input.config.format, input.config.channel_mask,
Eric Laurent21da6472017-11-09 16:29:26 -08001178 &output.frameCount, &output.notificationFrameCount,
1179 input.notificationsPerBuffer, input.speed,
1180 input.sharedBuffer, sessionId, &output.flags,
Svet Ganov33761132021-05-13 22:51:08 +00001181 callingPid, adjAttributionSource, input.clientInfo.clientTid,
jiabinc658e452022-10-21 20:52:21 +00001182 &lStatus, portId, input.audioTrackCallback, isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00001183 isBitPerfect, &output.afTrackFlags);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001184 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
Glenn Kasten2fc14732013-08-05 14:58:14 -07001185 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
Eric Laurent39e94f82010-07-28 01:32:47 -07001186
Eric Laurent21da6472017-11-09 16:29:26 -08001187 output.afFrameCount = thread->frameCount();
1188 output.afSampleRate = thread->sampleRate();
Robert Wu310037a2022-09-06 21:48:18 +00001189 output.afChannelMask = static_cast<audio_channel_mask_t>(thread->channelMask() |
1190 thread->hapticChannelMask());
1191 output.afFormat = thread->format();
Eric Laurent21da6472017-11-09 16:29:26 -08001192 output.afLatencyMs = thread->latency();
Eric Laurent973db022018-11-20 14:54:31 -08001193 output.portId = portId;
Eric Laurent21da6472017-11-09 16:29:26 -08001194
Kevin Rocard153f92d2018-12-18 18:33:28 -08001195 if (lStatus == NO_ERROR) {
Andy Hung954b9712023-08-28 18:36:53 -07001196 // no risk of deadlock because AudioFlinger::mutex() is held
Andy Hungc5007f82023-08-29 14:26:09 -07001197 audio_utils::lock_guard _dl(thread->mutex());
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198 // Connect secondary outputs. Failure on a secondary output must not imped the primary
1199 // Any secondary output setup failure will lead to a desync between the AP and AF until
1200 // the track is destroyed.
jiabinf042b9b2021-05-07 23:46:28 +00001201 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
jiabin87991352023-04-25 20:59:55 +00001202 // move effect chain to this output thread if an effect on same session was waiting
1203 // for a track to be created
1204 if (effectThread != nullptr) {
Andy Hung972bec12023-08-31 16:13:39 -07001205 // No thread safety analysis: double lock on a thread capability.
1206 audio_utils::lock_guard_no_thread_safety_analysis _sl(effectThread->mutex());
1207 if (moveEffectChain_ll(sessionId, effectThread, thread) == NO_ERROR) {
jiabin87991352023-04-25 20:59:55 +00001208 effectThreadId = thread->id();
1209 effectIds = thread->getEffectIds_l(sessionId);
1210 }
Eric Laurent6c796322019-04-09 14:13:17 -07001211 }
Shunkai Yao29d10572024-03-19 04:31:47 +00001212 if (effectChain != nullptr) {
1213 if (moveEffectChain_ll(sessionId, nullptr, thread, effectChain.get())
1214 == NO_ERROR) {
1215 effectThreadId = thread->id();
1216 effectIds = thread->getEffectIds_l(sessionId);
1217 }
1218 }
Eric Laurent39e94f82010-07-28 01:32:47 -07001219 }
Eric Laurenta011e352012-03-29 15:51:43 -07001220
1221 // Look for sync events awaiting for a session to be used.
Andy Hung068e08e2023-05-15 19:02:55 -07001222 for (auto it = mPendingSyncEvents.begin(); it != mPendingSyncEvents.end();) {
1223 if ((*it)->triggerSession() == sessionId) {
1224 if (thread->isValidSyncEvent(*it)) {
Eric Laurent29864602012-05-08 18:57:51 -07001225 if (lStatus == NO_ERROR) {
Andy Hung068e08e2023-05-15 19:02:55 -07001226 (void) track->setSyncEvent(*it);
Eric Laurent29864602012-05-08 18:57:51 -07001227 } else {
Andy Hung068e08e2023-05-15 19:02:55 -07001228 (*it)->cancel();
Eric Laurent29864602012-05-08 18:57:51 -07001229 }
Andy Hung068e08e2023-05-15 19:02:55 -07001230 it = mPendingSyncEvents.erase(it);
1231 continue;
Eric Laurenta011e352012-03-29 15:51:43 -07001232 }
1233 }
Andy Hung068e08e2023-05-15 19:02:55 -07001234 ++it;
Eric Laurenta011e352012-03-29 15:51:43 -07001235 }
Andy Hung6eff0ff2021-07-30 19:01:48 -07001236 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1237 setAudioHwSyncForSession_l(thread, sessionId);
1238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 }
Glenn Kastene198c362013-08-13 09:13:36 -07001240
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001241 if (lStatus != NO_ERROR) {
1242 // remove local strong reference to Client before deleting the Track so that the
Andy Hung954b9712023-08-28 18:36:53 -07001243 // Client destructor is called by the TrackBase destructor with clientMutex() held
1244 // Don't hold clientMutex() when releasing the reference on the track as the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001245 // destructor will acquire it.
1246 {
Andy Hung954b9712023-08-28 18:36:53 -07001247 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07001248 client.clear();
1249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001250 track.clear();
Glenn Kasten3ef14ef2014-03-13 15:08:51 -07001251 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252 }
1253
Eric Laurent6c796322019-04-09 14:13:17 -07001254 // effectThreadId is not NONE if an effect chain corresponding to the track session
1255 // was found on another thread and must be moved on this thread
1256 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1257 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1258 }
1259
Andy Hungd29af632023-06-23 19:27:19 -07001260 output.audioTrack = IAfTrack::createIAudioTrackAdapter(track);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08001261 _output = VALUE_OR_FATAL(output.toAidl());
1262
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263Exit:
Eric Laurent21da6472017-11-09 16:29:26 -08001264 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07001265 AudioSystem::releaseOutput(portId);
Eric Laurent21da6472017-11-09 16:29:26 -08001266 }
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08001267 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268}
1269
Glenn Kasten2c073da2016-02-26 09:14:08 -08001270uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271{
Andy Hung954b9712023-08-28 18:36:53 -07001272 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001273 IAfThreadBase* const thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001275 ALOGW("sampleRate() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 return 0;
1277 }
1278 return thread->sampleRate();
1279}
1280
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001281audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282{
Andy Hung954b9712023-08-28 18:36:53 -07001283 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001284 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001286 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -08001287 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 }
1289 return thread->format();
1290}
1291
Glenn Kasten2c073da2016-02-26 09:14:08 -08001292size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293{
Andy Hung954b9712023-08-28 18:36:53 -07001294 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001295 IAfThreadBase* const thread = checkThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 if (thread == NULL) {
Glenn Kasten2c073da2016-02-26 09:14:08 -08001297 ALOGW("frameCount() unknown thread %d", ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 return 0;
1299 }
Glenn Kasten58912562012-04-03 10:45:00 -07001300 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1301 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302 return thread->frameCount();
1303}
1304
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001305size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1306{
Andy Hung954b9712023-08-28 18:36:53 -07001307 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001308 IAfThreadBase* const thread = checkThread_l(ioHandle);
Glenn Kasten4a8308b2016-04-18 14:10:01 -07001309 if (thread == NULL) {
1310 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1311 return 0;
1312 }
1313 return thread->frameCountHAL();
1314}
1315
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001316uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317{
Andy Hung954b9712023-08-28 18:36:53 -07001318 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001319 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320 if (thread == NULL) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08001321 ALOGW("latency(): no playback thread found for output handle %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 return 0;
1323 }
1324 return thread->latency();
1325}
1326
1327status_t AudioFlinger::setMasterVolume(float value)
1328{
Eric Laurenta1884f92011-08-23 08:25:03 -07001329 status_t ret = initCheck();
1330 if (ret != NO_ERROR) {
1331 return ret;
1332 }
1333
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334 // check calling permissions
1335 if (!settingsAllowed()) {
1336 return PERMISSION_DENIED;
1337 }
1338
Andy Hung954b9712023-08-28 18:36:53 -07001339 audio_utils::lock_guard _l(mutex());
John Grossmanee578c02012-07-23 17:05:46 -07001340 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -07001341
John Grossmanee578c02012-07-23 17:05:46 -07001342 // Set master volume in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001343 {
Andy Hung954b9712023-08-28 18:36:53 -07001344 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1346 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -08001347
Eric Laurent00abf0d2020-04-22 19:28:22 -07001348 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1349 if (dev->canSetMasterVolume()) {
1350 dev->hwDevice()->setMasterVolume(value);
1351 }
1352 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -08001353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 }
John Grossmanee578c02012-07-23 17:05:46 -07001355 // Now set the master volume in each playback thread. Playback threads
1356 // assigned to HALs which do not have master volume support will apply
1357 // master volume during the mix operation. Threads with HALs which do
1358 // support master volume will simply ignore the setting.
Eric Laurentf6870ae2015-05-08 10:50:03 -07001359 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1360 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1361 continue;
1362 }
John Grossmanee578c02012-07-23 17:05:46 -07001363 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001364 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365
1366 return NO_ERROR;
1367}
1368
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001369status_t AudioFlinger::setMasterBalance(float balance)
1370{
1371 status_t ret = initCheck();
1372 if (ret != NO_ERROR) {
1373 return ret;
1374 }
1375
1376 // check calling permissions
1377 if (!settingsAllowed()) {
1378 return PERMISSION_DENIED;
1379 }
1380
1381 // check range
1382 if (isnan(balance) || fabs(balance) > 1.f) {
1383 return BAD_VALUE;
1384 }
1385
Andy Hung954b9712023-08-28 18:36:53 -07001386 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001387
1388 // short cut.
1389 if (mMasterBalance == balance) return NO_ERROR;
1390
1391 mMasterBalance = balance;
1392
1393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1394 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1395 continue;
1396 }
1397 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1398 }
1399
1400 return NO_ERROR;
1401}
1402
Glenn Kastenf78aee72012-01-04 11:00:47 -08001403status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404{
Eric Laurenta1884f92011-08-23 08:25:03 -07001405 status_t ret = initCheck();
1406 if (ret != NO_ERROR) {
1407 return ret;
1408 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001409
1410 // check calling permissions
1411 if (!settingsAllowed()) {
1412 return PERMISSION_DENIED;
1413 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -08001414 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001415 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416 return BAD_VALUE;
1417 }
1418
1419 { // scope for the lock
Andy Hung954b9712023-08-28 18:36:53 -07001420 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001421 if (mPrimaryHardwareDev == nullptr) {
1422 return INVALID_OPERATION;
1423 }
Andy Hunge3748872023-08-30 19:05:16 -07001424 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425 mHardwareStatus = AUDIO_HW_SET_MODE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001426 ret = dev->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 mHardwareStatus = AUDIO_HW_IDLE;
1428 }
1429
1430 if (NO_ERROR == ret) {
Andy Hung954b9712023-08-28 18:36:53 -07001431 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 mMode = mode;
Andy Hung920f6572022-10-06 12:09:49 -07001433 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001434 mPlaybackThreads.valueAt(i)->setMode(mode);
Andy Hung920f6572022-10-06 12:09:49 -07001435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 }
1437
Joey Poomarin52989982020-03-05 17:40:49 +08001438 mediametrics::LogItem(mMetricsId)
1439 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1440 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1441 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442 return ret;
1443}
1444
1445status_t AudioFlinger::setMicMute(bool state)
1446{
Eric Laurenta1884f92011-08-23 08:25:03 -07001447 status_t ret = initCheck();
1448 if (ret != NO_ERROR) {
1449 return ret;
1450 }
1451
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 // check calling permissions
1453 if (!settingsAllowed()) {
1454 return PERMISSION_DENIED;
1455 }
1456
Andy Hung954b9712023-08-28 18:36:53 -07001457 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001458 if (mPrimaryHardwareDev == nullptr) {
1459 return INVALID_OPERATION;
1460 }
Andy Hunge3748872023-08-30 19:05:16 -07001461 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001462 if (primaryDev == nullptr) {
1463 ALOGW("%s: no primary HAL device", __func__);
1464 return INVALID_OPERATION;
1465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001467 ret = primaryDev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001468 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001469 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001470 if (dev != primaryDev) {
1471 (void)dev->setMicMute(state);
Eric Laurent2f035f52014-09-14 12:11:52 -07001472 }
1473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001475 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476 return ret;
1477}
1478
1479bool AudioFlinger::getMicMute() const
1480{
Eric Laurenta1884f92011-08-23 08:25:03 -07001481 status_t ret = initCheck();
1482 if (ret != NO_ERROR) {
1483 return false;
1484 }
Andy Hung954b9712023-08-28 18:36:53 -07001485 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001486 if (mPrimaryHardwareDev == nullptr) {
1487 return false;
1488 }
Andy Hunge3748872023-08-30 19:05:16 -07001489 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent2325bf02020-04-08 19:38:13 -07001490 if (primaryDev == nullptr) {
1491 ALOGW("%s: no primary HAL device", __func__);
1492 return false;
Ricardo Garcia3e91b5d2015-02-19 10:54:52 -08001493 }
Eric Laurent2325bf02020-04-08 19:38:13 -07001494 bool state;
1495 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1496 ret = primaryDev->getMicMute(&state);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent2325bf02020-04-08 19:38:13 -07001498 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1499 return (ret == NO_ERROR) && state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500}
1501
Eric Laurent5ada82e2019-08-29 17:53:54 -07001502void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001503{
Eric Laurent5ada82e2019-08-29 17:53:54 -07001504 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001505
Andy Hung954b9712023-08-28 18:36:53 -07001506 audio_utils::lock_guard lock(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001507 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001508 mRecordThreads[i]->setRecordSilenced(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -07001509 }
1510 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07001511 mMmapThreads[i]->setRecordSilenced(portId, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001512 }
1513}
1514
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515status_t AudioFlinger::setMasterMute(bool muted)
1516{
John Grossmand8f178d2012-07-20 14:51:35 -07001517 status_t ret = initCheck();
1518 if (ret != NO_ERROR) {
1519 return ret;
1520 }
1521
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 // check calling permissions
1523 if (!settingsAllowed()) {
1524 return PERMISSION_DENIED;
1525 }
1526
Andy Hung954b9712023-08-28 18:36:53 -07001527 audio_utils::lock_guard _l(mutex());
John Grossmanee578c02012-07-23 17:05:46 -07001528 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -07001529
John Grossmanee578c02012-07-23 17:05:46 -07001530 // Set master mute in the HALs which support it.
Eric Laurent00abf0d2020-04-22 19:28:22 -07001531 {
Andy Hung954b9712023-08-28 18:36:53 -07001532 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07001533 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1534 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -07001535
Eric Laurent00abf0d2020-04-22 19:28:22 -07001536 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1537 if (dev->canSetMasterMute()) {
1538 dev->hwDevice()->setMasterMute(muted);
1539 }
1540 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07001541 }
John Grossmand8f178d2012-07-20 14:51:35 -07001542 }
1543
John Grossmanee578c02012-07-23 17:05:46 -07001544 // Now set the master mute in each playback thread. Playback threads
Glenn Kastena2f59b32020-08-03 16:37:24 -07001545 // assigned to HALs which do not have master mute support will apply master mute
1546 // during the mix operation. Threads with HALs which do support master mute
1547 // will simply ignore the setting.
Andy Hung84074c62023-07-06 19:21:50 -07001548 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001549 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1550 volumeInterfaces[i]->setMasterMute(muted);
Eric Laurentf6870ae2015-05-08 10:50:03 -07001551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552
1553 return NO_ERROR;
1554}
1555
1556float AudioFlinger::masterVolume() const
1557{
Andy Hung954b9712023-08-28 18:36:53 -07001558 audio_utils::lock_guard _l(mutex());
Glenn Kasten98067102011-12-13 11:47:54 -08001559 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560}
1561
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001562status_t AudioFlinger::getMasterBalance(float *balance) const
1563{
Andy Hung954b9712023-08-28 18:36:53 -07001564 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001565 *balance = getMasterBalance_l();
1566 return NO_ERROR; // if called through binder, may return a transactional error
1567}
1568
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569bool AudioFlinger::masterMute() const
1570{
Andy Hung954b9712023-08-28 18:36:53 -07001571 audio_utils::lock_guard _l(mutex());
Glenn Kasten98067102011-12-13 11:47:54 -08001572 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573}
1574
John Grossman4ff14ba2012-02-08 16:37:41 -08001575float AudioFlinger::masterVolume_l() const
1576{
John Grossman4ff14ba2012-02-08 16:37:41 -08001577 return mMasterVolume;
1578}
1579
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01001580float AudioFlinger::getMasterBalance_l() const
1581{
1582 return mMasterBalance;
1583}
1584
John Grossmand8f178d2012-07-20 14:51:35 -07001585bool AudioFlinger::masterMute_l() const
1586{
John Grossmanee578c02012-07-23 17:05:46 -07001587 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -07001588}
1589
Andy Hungc2cf7ec2023-08-30 18:19:00 -07001590/* static */
1591status_t AudioFlinger::checkStreamType(audio_stream_type_t stream)
Eric Laurent223fd5c2014-11-11 13:43:36 -08001592{
1593 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08001594 ALOGW("checkStreamType() invalid stream %d", stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001595 return BAD_VALUE;
1596 }
Andy Hung4ef19fa2018-05-15 19:35:29 -07001597 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1598 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1599 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001600 return PERMISSION_DENIED;
1601 }
1602
1603 return NO_ERROR;
1604}
1605
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001606status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1607 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608{
1609 // check calling permissions
1610 if (!settingsAllowed()) {
1611 return PERMISSION_DENIED;
1612 }
1613
Eric Laurent223fd5c2014-11-11 13:43:36 -08001614 status_t status = checkStreamType(stream);
1615 if (status != NO_ERROR) {
1616 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617 }
Eric Laurent98e38192018-02-15 18:31:53 -08001618 if (output == AUDIO_IO_HANDLE_NONE) {
1619 return BAD_VALUE;
1620 }
François Gaffie9e1533c2019-04-11 16:07:36 +02001621 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1622 "AUDIO_STREAM_PATCH must have full scale volume");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623
Andy Hung954b9712023-08-28 18:36:53 -07001624 audio_utils::lock_guard lock(mutex());
Andy Hung84074c62023-07-06 19:21:50 -07001625 sp<VolumeInterface> volumeInterface = getVolumeInterface_l(output);
Eric Laurent98e38192018-02-15 18:31:53 -08001626 if (volumeInterface == NULL) {
1627 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 }
Eric Laurent98e38192018-02-15 18:31:53 -08001629 volumeInterface->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630
1631 return NO_ERROR;
1632}
1633
Eric Laurent076e7c72022-05-03 18:12:28 +02001634status_t AudioFlinger::setRequestedLatencyMode(
Eric Laurent68a40a82022-05-03 18:15:04 +02001635 audio_io_handle_t output, audio_latency_mode_t mode) {
Eric Laurent076e7c72022-05-03 18:12:28 +02001636 if (output == AUDIO_IO_HANDLE_NONE) {
1637 return BAD_VALUE;
1638 }
Andy Hung954b9712023-08-28 18:36:53 -07001639 audio_utils::lock_guard lock(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001640 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Eric Laurent68a40a82022-05-03 18:15:04 +02001641 if (thread == nullptr) {
1642 return BAD_VALUE;
1643 }
1644 return thread->setRequestedLatencyMode(mode);
Eric Laurent076e7c72022-05-03 18:12:28 +02001645}
1646
1647status_t AudioFlinger::getSupportedLatencyModes(audio_io_handle_t output,
Andy Hungcdd80ef2023-07-17 11:37:26 -07001648 std::vector<audio_latency_mode_t>* modes) const {
Eric Laurent076e7c72022-05-03 18:12:28 +02001649 if (output == AUDIO_IO_HANDLE_NONE) {
1650 return BAD_VALUE;
1651 }
Andy Hung954b9712023-08-28 18:36:53 -07001652 audio_utils::lock_guard lock(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07001653 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Eric Laurent68a40a82022-05-03 18:15:04 +02001654 if (thread == nullptr) {
1655 return BAD_VALUE;
1656 }
1657 return thread->getSupportedLatencyModes(modes);
Eric Laurent076e7c72022-05-03 18:12:28 +02001658}
1659
Eric Laurent50d72582022-12-20 20:20:23 +01001660status_t AudioFlinger::setBluetoothVariableLatencyEnabled(bool enabled) {
Andy Hung954b9712023-08-28 18:36:53 -07001661 audio_utils::lock_guard _l(mutex());
Eric Laurent52057642022-12-16 11:45:07 +01001662 status_t status = INVALID_OPERATION;
1663 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1664 // Success if at least one PlaybackThread supports Bluetooth latency modes
Eric Laurent50d72582022-12-20 20:20:23 +01001665 if (mPlaybackThreads.valueAt(i)->setBluetoothVariableLatencyEnabled(enabled) == NO_ERROR) {
Eric Laurent52057642022-12-16 11:45:07 +01001666 status = NO_ERROR;
1667 }
1668 }
1669 if (status == NO_ERROR) {
1670 mBluetoothLatencyModesEnabled.store(enabled);
1671 }
1672 return status;
1673}
1674
Andy Hungcdd80ef2023-07-17 11:37:26 -07001675status_t AudioFlinger::isBluetoothVariableLatencyEnabled(bool* enabled) const {
Eric Laurent50d72582022-12-20 20:20:23 +01001676 if (enabled == nullptr) {
1677 return BAD_VALUE;
1678 }
1679 *enabled = mBluetoothLatencyModesEnabled.load();
1680 return NO_ERROR;
1681}
1682
Andy Hungcdd80ef2023-07-17 11:37:26 -07001683status_t AudioFlinger::supportsBluetoothVariableLatency(bool* support) const {
Eric Laurent52057642022-12-16 11:45:07 +01001684 if (support == nullptr) {
1685 return BAD_VALUE;
1686 }
Andy Hungc2cf7ec2023-08-30 18:19:00 -07001687 audio_utils::lock_guard _l(hardwareMutex());
Eric Laurent52057642022-12-16 11:45:07 +01001688 *support = false;
1689 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurent50d72582022-12-20 20:20:23 +01001690 if (mAudioHwDevs.valueAt(i)->supportsBluetoothVariableLatency()) {
Eric Laurent52057642022-12-16 11:45:07 +01001691 *support = true;
1692 break;
1693 }
1694 }
1695 return NO_ERROR;
1696}
1697
Vlad Popae3fd1c22022-11-07 21:03:18 +01001698status_t AudioFlinger::getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
Andy Hungcdd80ef2023-07-17 11:37:26 -07001699 sp<media::ISoundDose>* soundDose) const {
Vlad Popae3fd1c22022-11-07 21:03:18 +01001700 if (soundDose == nullptr) {
1701 return BAD_VALUE;
1702 }
1703
1704 *soundDose = mMelReporter->getSoundDoseInterface(callback);
Vlad Popa63f047e2022-11-05 14:09:19 +01001705 return NO_ERROR;
1706}
1707
Glenn Kastenfff6d712012-01-12 16:38:12 -08001708status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709{
1710 // check calling permissions
1711 if (!settingsAllowed()) {
1712 return PERMISSION_DENIED;
1713 }
1714
Eric Laurent223fd5c2014-11-11 13:43:36 -08001715 status_t status = checkStreamType(stream);
1716 if (status != NO_ERROR) {
1717 return status;
1718 }
1719 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1720
1721 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +00001722 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 return BAD_VALUE;
1724 }
1725
Andy Hung954b9712023-08-28 18:36:53 -07001726 audio_utils::lock_guard lock(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 mStreamTypes[stream].mute = muted;
Andy Hung84074c62023-07-06 19:21:50 -07001728 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08001729 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1730 volumeInterfaces[i]->setStreamMute(stream, muted);
1731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732
1733 return NO_ERROR;
1734}
1735
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001736float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001738 status_t status = checkStreamType(stream);
1739 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 return 0.0f;
1741 }
Eric Laurent98e38192018-02-15 18:31:53 -08001742 if (output == AUDIO_IO_HANDLE_NONE) {
1743 return 0.0f;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 }
1745
Andy Hung954b9712023-08-28 18:36:53 -07001746 audio_utils::lock_guard lock(mutex());
Andy Hung84074c62023-07-06 19:21:50 -07001747 sp<VolumeInterface> volumeInterface = getVolumeInterface_l(output);
Eric Laurent98e38192018-02-15 18:31:53 -08001748 if (volumeInterface == NULL) {
1749 return 0.0f;
1750 }
1751
1752 return volumeInterface->streamVolume(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753}
1754
Glenn Kastenfff6d712012-01-12 16:38:12 -08001755bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756{
Eric Laurent223fd5c2014-11-11 13:43:36 -08001757 status_t status = checkStreamType(stream);
1758 if (status != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 return true;
1760 }
1761
Andy Hung954b9712023-08-28 18:36:53 -07001762 audio_utils::lock_guard lock(mutex());
Glenn Kasten6637baa2012-01-09 09:40:36 -08001763 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
Eric Laurent054d9d32015-04-24 08:48:48 -07001766
Andy Hungd9ef4b12020-11-11 15:13:18 -08001767void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
Eric Laurent054d9d32015-04-24 08:48:48 -07001768{
1769 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1770 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1771 }
1772}
1773
jiabinc52b1ff2019-10-31 17:20:42 -07001774void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1775{
1776 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1777 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1778 }
1779}
1780
Andy Hung954b9712023-08-28 18:36:53 -07001781// forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mutex() held
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001782void AudioFlinger::forwardParametersToDownstreamPatches_l(
1783 audio_io_handle_t upStream, const String8& keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07001784 const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread)
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001785{
Andy Hungb6692eb2023-07-13 16:52:46 -07001786 std::vector<SoftwarePatch> swPatches;
1787 if (mPatchPanel->getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001788 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1789 __func__, swPatches.size(), upStream);
1790 for (const auto& swPatch : swPatches) {
Andy Hung87c693c2023-07-06 20:56:16 -07001791 const sp<IAfPlaybackThread> downStream =
1792 checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001793 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1794 downStream->setParameters(keyValuePairs);
1795 }
1796 }
1797}
1798
Eric Laurent74c38dc2020-12-23 18:19:44 +01001799// Update downstream patches for all playback threads attached to an MSD module
1800void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
Andy Hung920f6572022-10-06 12:09:49 -07001801 const std::set<audio_io_handle_t>& streams)
Eric Laurent74c38dc2020-12-23 18:19:44 +01001802{
1803 for (const audio_io_handle_t stream : streams) {
Andy Hung87c693c2023-07-06 20:56:16 -07001804 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(stream);
Eric Laurent74c38dc2020-12-23 18:19:44 +01001805 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1806 continue;
1807 }
1808 playbackThread->setDownStreamPatch(patch);
1809 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1810 }
1811}
1812
Eric Laurentf1047e82018-04-16 19:18:20 -07001813// Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1814// Some keys are used for audio routing and audio path configuration and should be reserved for use
1815// by audio policy and audio flinger for functional, privacy and security reasons.
1816void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1817{
1818 static const String8 kReservedParameters[] = {
1819 String8(AudioParameter::keyRouting),
1820 String8(AudioParameter::keySamplingRate),
1821 String8(AudioParameter::keyFormat),
1822 String8(AudioParameter::keyChannels),
1823 String8(AudioParameter::keyFrameCount),
1824 String8(AudioParameter::keyInputSource),
1825 String8(AudioParameter::keyMonoOutput),
Mikhail Naganovf23fcf62019-07-08 15:28:43 -07001826 String8(AudioParameter::keyDeviceConnect),
1827 String8(AudioParameter::keyDeviceDisconnect),
Eric Laurentf1047e82018-04-16 19:18:20 -07001828 String8(AudioParameter::keyStreamSupportedFormats),
1829 String8(AudioParameter::keyStreamSupportedChannels),
1830 String8(AudioParameter::keyStreamSupportedSamplingRates),
Andy Hungdda7aed2023-03-27 15:53:06 -07001831 String8(AudioParameter::keyClosing),
1832 String8(AudioParameter::keyExiting),
Eric Laurentf1047e82018-04-16 19:18:20 -07001833 };
1834
Andy Hung4ef19fa2018-05-15 19:35:29 -07001835 if (isAudioServerUid(callingUid)) {
1836 return; // no need to filter if audioserver.
Eric Laurentf1047e82018-04-16 19:18:20 -07001837 }
1838
1839 AudioParameter param = AudioParameter(keyValuePairs);
1840 String8 value;
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001841 AudioParameter rejectedParam;
Eric Laurentf1047e82018-04-16 19:18:20 -07001842 for (auto& key : kReservedParameters) {
1843 if (param.get(key, value) == NO_ERROR) {
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001844 rejectedParam.add(key, value);
Eric Laurentf1047e82018-04-16 19:18:20 -07001845 param.remove(key);
1846 }
1847 }
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001848 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1849 rejectedParam.size(), rejectedParam.toString(), callingUid);
Eric Laurentf1047e82018-04-16 19:18:20 -07001850 keyValuePairs = param.toString();
1851}
1852
Kevin Rocarda0a5d2a2018-08-06 15:03:18 -07001853void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1854 size_t rejectedKVPSize, const String8& rejectedKVPs,
1855 uid_t callingUid) {
1856 auto prefix = String8::format("UID %5d", callingUid);
1857 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1858 if (rejectedKVPSize != 0) {
1859 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1860 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1861 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1862 } else {
1863 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1864 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1865 }
1866}
1867
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001868status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869{
Eric Laurentf1047e82018-04-16 19:18:20 -07001870 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001871 ioHandle, keyValuePairs.c_str(),
Eric Laurentf1047e82018-04-16 19:18:20 -07001872 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Eric Laurent81784c32012-11-19 14:55:58 -08001873
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 // check calling permissions
1875 if (!settingsAllowed()) {
1876 return PERMISSION_DENIED;
1877 }
1878
Eric Laurentf1047e82018-04-16 19:18:20 -07001879 String8 filteredKeyValuePairs = keyValuePairs;
1880 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1881
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001882 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.c_str());
Eric Laurentf1047e82018-04-16 19:18:20 -07001883
Glenn Kasten142f5192014-03-25 17:44:59 -07001884 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1885 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Andy Hung954b9712023-08-28 18:36:53 -07001886 audio_utils::lock_guard _l(mutex());
Eric Laurentd21bcd22016-09-08 18:25:54 -07001887 // result will remain NO_INIT if no audio device is present
1888 status_t final_result = NO_INIT;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001889 {
Andy Hung954b9712023-08-28 18:36:53 -07001890 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -07001891 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1892 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001893 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurentf1047e82018-04-16 19:18:20 -07001894 status_t result = dev->setParameters(filteredKeyValuePairs);
Eric Laurentd21bcd22016-09-08 18:25:54 -07001895 // return success if at least one audio device accepts the parameters as not all
1896 // HALs are requested to support all parameters. If no audio device supports the
1897 // requested parameters, the last error is reported.
1898 if (final_result != NO_ERROR) {
1899 final_result = result;
1900 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07001901 }
1902 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001903 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001904 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1047e82018-04-16 19:18:20 -07001905 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent59bd0da2011-08-01 09:52:20 -07001906 String8 value;
Mikhail Naganov00260b52016-10-13 12:54:24 -07001907 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1908 bool btNrecIsOff = (value == AudioParameter::valueOff);
Eric Laurentd8365c52017-07-16 15:27:05 -07001909 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07001910 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentd8365c52017-07-16 15:27:05 -07001911 mRecordThreads.valueAt(i)->checkBtNrec();
Eric Laurent59bd0da2011-08-01 09:52:20 -07001912 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07001913 }
1914 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001915 String8 screenState;
1916 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
Mikhail Naganov00260b52016-10-13 12:54:24 -07001917 bool isOff = (screenState == AudioParameter::valueOff);
Andy Hung1d2d2aea2023-07-19 16:22:58 -07001918 if (isOff != (mScreenState & 1)) {
1919 mScreenState = ((mScreenState & ~1) + 2) | isOff;
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001920 }
1921 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001922 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 }
1924
1925 // hold a strong ref on thread in case closeOutput() or closeInput() is called
1926 // and the thread is exited once the lock is released
Andy Hung87c693c2023-07-06 20:56:16 -07001927 sp<IAfThreadBase> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 {
Andy Hung954b9712023-08-28 18:36:53 -07001929 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -07001931 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001933 if (thread == 0) {
1934 thread = checkMmapThread_l(ioHandle);
1935 }
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08001936 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001937 // indicate output device change to all input threads for pre processing
Eric Laurentf1047e82018-04-16 19:18:20 -07001938 AudioParameter param = AudioParameter(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001939 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -07001940 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
1941 (value != 0)) {
Andy Hungd9ef4b12020-11-11 15:13:18 -08001942 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 }
1945 }
Glenn Kasten7378ca52012-01-20 13:44:40 -08001946 if (thread != 0) {
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001947 status_t result = thread->setParameters(filteredKeyValuePairs);
Andy Hungc2cf7ec2023-08-30 18:19:00 -07001948 audio_utils::lock_guard _l(mutex());
Mikhail Naganovb261ef52018-07-16 13:34:38 -07001949 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
1950 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 }
1952 return BAD_VALUE;
1953}
1954
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001955String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956{
Glenn Kasten827e5f12012-11-02 10:00:06 -07001957 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001958 ioHandle, keys.c_str(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959
Andy Hung954b9712023-08-28 18:36:53 -07001960 audio_utils::lock_guard _l(mutex());
Eric Laurenta4c5a552012-03-29 10:12:40 -07001961
Glenn Kasten142f5192014-03-25 17:44:59 -07001962 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001963 String8 out_s8;
1964
Andy Hung954b9712023-08-28 18:36:53 -07001965 audio_utils::lock_guard lock(hardwareMutex());
Dima Zavin799a70e2011-04-18 16:57:27 -07001966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001967 String8 s;
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001968 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001969 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07001970 status_t result = dev->getParameters(keys, &s);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001971 mHardwareStatus = AUDIO_HW_IDLE;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07001972 if (result == OK) out_s8 += s;
Dima Zavin799a70e2011-04-18 16:57:27 -07001973 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001974 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976
Andy Hung87c693c2023-07-06 20:56:16 -07001977 IAfThreadBase* thread = checkPlaybackThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001978 if (thread == NULL) {
Andy Hung87c693c2023-07-06 20:56:16 -07001979 thread = checkRecordThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001980 if (thread == NULL) {
Andy Hung87c693c2023-07-06 20:56:16 -07001981 thread = checkMmapThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08001982 if (thread == NULL) {
Mikhail Naganovaa165e52017-07-12 10:39:16 -07001983 return String8("");
Eric Laurent6acd1d42017-01-04 14:23:29 -08001984 }
1985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08001987 return thread->getParameters(keys);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988}
1989
Glenn Kastendd8104c2012-07-02 12:42:44 -07001990size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1991 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992{
Eric Laurenta1884f92011-08-23 08:25:03 -07001993 status_t ret = initCheck();
1994 if (ret != NO_ERROR) {
1995 return 0;
1996 }
Eric Laurentcdf924a2016-02-04 15:57:56 -08001997 if ((sampleRate == 0) ||
Dean Wheatley8d72b4b2023-11-16 06:43:58 +11001998 !audio_is_valid_format(format) ||
Eric Laurentcdf924a2016-02-04 15:57:56 -08001999 !audio_is_input_channel(channelMask)) {
Andy Hung6770c6f2015-04-07 13:43:36 -07002000 return 0;
2001 }
Eric Laurenta1884f92011-08-23 08:25:03 -07002002
Andy Hung954b9712023-08-28 18:36:53 -07002003 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002004 if (mPrimaryHardwareDev == nullptr) {
2005 return 0;
2006 }
Oleg Lyovin7434b722024-03-05 18:08:01 +03002007 if (mInputBufferSizeOrderedDevs.empty()) {
2008 return 0;
2009 }
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002010 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Richard Fitzgeraldad3af332013-03-25 16:54:37 +00002011
Judy Hsiaoabab5222019-11-09 18:14:58 +08002012 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
Andy Hung920f6572022-10-06 12:09:49 -07002013 if (channelMask != AUDIO_CHANNEL_IN_MONO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002014 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
Andy Hung920f6572022-10-06 12:09:49 -07002015 }
2016 if (channelMask != AUDIO_CHANNEL_IN_STEREO) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002017 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
Andy Hung920f6572022-10-06 12:09:49 -07002018 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002019
2020 std::vector<audio_format_t> formats = {format};
Andy Hung920f6572022-10-06 12:09:49 -07002021 if (format != AUDIO_FORMAT_PCM_16_BIT) {
Dean Wheatley8d72b4b2023-11-16 06:43:58 +11002022 // For compressed format, buffer size may be queried using PCM. Allow this for compatibility
2023 // in cases the primary hw dev does not support the format.
2024 // TODO: replace with a table of formats and nominal buffer sizes (based on nominal bitrate
2025 // and codec frame size).
Judy Hsiaoabab5222019-11-09 18:14:58 +08002026 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
Andy Hung920f6572022-10-06 12:09:49 -07002027 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002028
2029 std::vector<uint32_t> sampleRates = {sampleRate};
2030 static const uint32_t SR_44100 = 44100;
2031 static const uint32_t SR_48000 = 48000;
Andy Hung920f6572022-10-06 12:09:49 -07002032 if (sampleRate != SR_48000) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002033 sampleRates.push_back(SR_48000);
Andy Hung920f6572022-10-06 12:09:49 -07002034 }
2035 if (sampleRate != SR_44100) {
Judy Hsiaoabab5222019-11-09 18:14:58 +08002036 sampleRates.push_back(SR_44100);
Andy Hung920f6572022-10-06 12:09:49 -07002037 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002038
Glenn Kasten2b213bc2012-02-02 14:05:20 -08002039 mHardwareStatus = AUDIO_HW_IDLE;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002040
Oleg Lyovin7434b722024-03-05 18:08:01 +03002041 auto getInputBufferSize = [](const sp<DeviceHalInterface>& dev, audio_config_t config,
2042 size_t* bytes) -> status_t {
2043 if (!dev) {
2044 return BAD_VALUE;
2045 }
2046 status_t result = dev->getInputBufferSize(&config, bytes);
2047 if (result == BAD_VALUE) {
2048 // Retry with the config suggested by the HAL.
2049 result = dev->getInputBufferSize(&config, bytes);
2050 }
2051 if (result != OK || *bytes == 0) {
2052 return BAD_VALUE;
2053 }
2054 return result;
2055 };
2056
Robin Lee9899ff72019-12-24 22:02:08 +01002057 // Change parameters of the configuration each iteration until we find a
Mikhail Naganovd5b643f2024-02-15 11:51:26 -08002058 // configuration that the device will support, or HAL suggests what it supports.
Robin Lee9899ff72019-12-24 22:02:08 +01002059 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Judy Hsiaoabab5222019-11-09 18:14:58 +08002060 for (auto testChannelMask : channelMasks) {
2061 config.channel_mask = testChannelMask;
2062 for (auto testFormat : formats) {
2063 config.format = testFormat;
2064 for (auto testSampleRate : sampleRates) {
2065 config.sample_rate = testSampleRate;
Robin Lee9899ff72019-12-24 22:02:08 +01002066
Judy Hsiaoabab5222019-11-09 18:14:58 +08002067 size_t bytes = 0;
Oleg Lyovin7434b722024-03-05 18:08:01 +03002068 ret = BAD_VALUE;
2069 for (const AudioHwDevice* dev : mInputBufferSizeOrderedDevs) {
2070 ret = getInputBufferSize(dev->hwDevice(), config, &bytes);
2071 if (ret == OK) {
2072 break;
2073 }
Mikhail Naganovd5b643f2024-02-15 11:51:26 -08002074 }
Oleg Lyovin7434b722024-03-05 18:08:01 +03002075 if (ret == BAD_VALUE) continue;
2076
Judy Hsiaoabab5222019-11-09 18:14:58 +08002077 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
2078 config.format != format) {
2079 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
2080 uint32_t srcChannelCount =
2081 audio_channel_count_from_in_mask(config.channel_mask);
2082 size_t srcFrames =
2083 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
2084 size_t dstFrames = destinationFramesPossible(
2085 srcFrames, config.sample_rate, sampleRate);
2086 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
2087 }
2088 return bytes;
2089 }
2090 }
Andy Hung6770c6f2015-04-07 13:43:36 -07002091 }
Judy Hsiaoabab5222019-11-09 18:14:58 +08002092
2093 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
2094 "format %#x, channelMask %#x",sampleRate, format, channelMask);
2095 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096}
2097
Glenn Kasten5f972c02014-01-13 09:59:31 -08002098uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099{
Andy Hung954b9712023-08-28 18:36:53 -07002100 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101
Andy Hung87c693c2023-07-06 20:56:16 -07002102 IAfRecordThread* const recordThread = checkRecordThread_l(ioHandle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 if (recordThread != NULL) {
2104 return recordThread->getInputFramesLost();
2105 }
2106 return 0;
2107}
2108
2109status_t AudioFlinger::setVoiceVolume(float value)
2110{
Eric Laurenta1884f92011-08-23 08:25:03 -07002111 status_t ret = initCheck();
2112 if (ret != NO_ERROR) {
2113 return ret;
2114 }
2115
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116 // check calling permissions
2117 if (!settingsAllowed()) {
2118 return PERMISSION_DENIED;
2119 }
2120
Andy Hung954b9712023-08-28 18:36:53 -07002121 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002122 if (mPrimaryHardwareDev == nullptr) {
2123 return INVALID_OPERATION;
2124 }
Andy Hunge3748872023-08-30 19:05:16 -07002125 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08002126 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002127 ret = dev->setVoiceVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 mHardwareStatus = AUDIO_HW_IDLE;
2129
Joey Poomarin52989982020-03-05 17:40:49 +08002130 mediametrics::LogItem(mMetricsId)
2131 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
2132 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
2133 .record();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 return ret;
2135}
2136
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002137status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002138 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139{
Andy Hung954b9712023-08-28 18:36:53 -07002140 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141
Andy Hung87c693c2023-07-06 20:56:16 -07002142 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 if (playbackThread != NULL) {
2144 return playbackThread->getRenderPosition(halFrames, dspFrames);
2145 }
2146
2147 return BAD_VALUE;
2148}
2149
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002150void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151{
Andy Hung954b9712023-08-28 18:36:53 -07002152 audio_utils::lock_guard _l(mutex());
Eric Laurent44622db2014-08-01 19:00:33 -07002153 if (client == 0) {
2154 return;
2155 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002156 pid_t pid = IPCThreadState::self()->getCallingPid();
Andy Hung5bdc5352019-12-23 14:36:31 -08002157 const uid_t uid = IPCThreadState::self()->getCallingUid();
Eric Laurent021cf962014-05-13 10:18:14 -07002158 {
Andy Hung954b9712023-08-28 18:36:53 -07002159 audio_utils::lock_guard _cl(clientMutex());
Eric Laurent021cf962014-05-13 10:18:14 -07002160 if (mNotificationClients.indexOfKey(pid) < 0) {
2161 sp<NotificationClient> notificationClient = new NotificationClient(this,
2162 client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002163 pid,
2164 uid);
2165 ALOGV("registerClient() client %p, pid %d, uid %u",
2166 notificationClient.get(), pid, uid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167
Eric Laurent021cf962014-05-13 10:18:14 -07002168 mNotificationClients.add(pid, notificationClient);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169
Marco Nelissen06b46062014-11-14 07:58:25 -08002170 sp<IBinder> binder = IInterface::asBinder(client);
Eric Laurent021cf962014-05-13 10:18:14 -07002171 binder->linkToDeath(notificationClient);
Eric Laurent021cf962014-05-13 10:18:14 -07002172 }
2173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174
Andy Hung954b9712023-08-28 18:36:53 -07002175 // clientMutex() should not be held here because ThreadBase::sendIoConfigEvent()
2176 // will lock the ThreadBase::mutex() and the locking order is
2177 // ThreadBase::mutex() then AudioFlinger::clientMutex().
2178 // The config change is always sent from playback or record threads to avoid deadlock
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002179 // with AudioSystem::gLock
2180 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002181 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002184 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002185 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186 }
2187}
2188
2189void AudioFlinger::removeNotificationClient(pid_t pid)
2190{
Andy Hung6ac17eb2023-06-20 18:56:17 -07002191 std::vector<sp<IAfEffectModule>> removedEffects;
Eric Laurent021cf962014-05-13 10:18:14 -07002192 {
Andy Hung954b9712023-08-28 18:36:53 -07002193 audio_utils::lock_guard _l(mutex());
Eric Laurent6c796322019-04-09 14:13:17 -07002194 {
Andy Hung954b9712023-08-28 18:36:53 -07002195 audio_utils::lock_guard _cl(clientMutex());
Eric Laurent6c796322019-04-09 14:13:17 -07002196 mNotificationClients.removeItem(pid);
2197 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002198
Eric Laurent6c796322019-04-09 14:13:17 -07002199 ALOGV("%d died, releasing its sessions", pid);
2200 size_t num = mAudioSessionRefs.size();
2201 bool removed = false;
2202 for (size_t i = 0; i < num; ) {
2203 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2204 ALOGV(" pid %d @ %zu", ref->mPid, i);
2205 if (ref->mPid == pid) {
2206 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
2207 mAudioSessionRefs.removeAt(i);
2208 delete ref;
2209 removed = true;
2210 num--;
2211 } else {
2212 i++;
2213 }
2214 }
2215 if (removed) {
2216 removedEffects = purgeStaleEffects_l();
François Gaffie1b4753e2023-02-06 10:36:33 +01002217 std::vector< sp<IAfEffectModule> > removedOrphanEffects = purgeOrphanEffectChains_l();
2218 removedEffects.insert(removedEffects.end(), removedOrphanEffects.begin(),
2219 removedOrphanEffects.end());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002220 }
2221 }
Eric Laurent6c796322019-04-09 14:13:17 -07002222 for (auto& effect : removedEffects) {
2223 effect->updatePolicyState();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07002224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225}
2226
Andy Hungab65b182023-09-06 19:41:47 -07002227// Hold either AudioFlinger::mutex or ThreadBase::mutex
2228void AudioFlinger::ioConfigChanged_l(audio_io_config_event_t event,
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002229 const sp<AudioIoDescriptor>& ioDesc,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002230 pid_t pid) {
Andy Hungb75b6242021-07-29 16:46:14 +00002231 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
2232 legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07002233 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
2234 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002235
Andy Hung954b9712023-08-28 18:36:53 -07002236 audio_utils::lock_guard _l(clientMutex());
Eric Laurent021cf962014-05-13 10:18:14 -07002237 size_t size = mNotificationClients.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238 for (size_t i = 0; i < size; i++) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002239 if ((pid == 0) || (mNotificationClients.keyAt(i) == pid)) {
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002240 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(eventAidl,
2241 descAidl);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 }
2244}
2245
Eric Laurent076e7c72022-05-03 18:12:28 +02002246void AudioFlinger::onSupportedLatencyModesChanged(
2247 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) {
2248 int32_t outputAidl = VALUE_OR_FATAL(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovf53e1822022-12-18 02:48:14 +00002249 std::vector<media::audio::common::AudioLatencyMode> modesAidl = VALUE_OR_FATAL(
2250 convertContainer<std::vector<media::audio::common::AudioLatencyMode>>(
2251 modes, legacy2aidl_audio_latency_mode_t_AudioLatencyMode));
Eric Laurent076e7c72022-05-03 18:12:28 +02002252
Andy Hung954b9712023-08-28 18:36:53 -07002253 audio_utils::lock_guard _l(clientMutex());
Eric Laurent076e7c72022-05-03 18:12:28 +02002254 size_t size = mNotificationClients.size();
2255 for (size_t i = 0; i < size; i++) {
2256 mNotificationClients.valueAt(i)->audioFlingerClient()
2257 ->onSupportedLatencyModesChanged(outputAidl, modesAidl);
2258 }
2259}
2260
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07002261void AudioFlinger::onHardError(std::set<audio_port_handle_t>& trackPortIds) {
2262 ALOGI("releasing tracks due to a hard error occurred on an I/O thread");
2263 for (const auto portId : trackPortIds) {
2264 AudioSystem::releaseOutput(portId);
2265 }
2266}
2267
Atneya Nair07c665d2024-05-17 15:46:48 -07002268const IPermissionProvider& AudioFlinger::getPermissionProvider() {
2269 // This is inited as part of service construction, prior to binder registration,
2270 // so it should always be non-null.
2271 return mAudioPolicyServiceLocal.load()->getPermissionProvider();
2272}
2273
Andy Hung954b9712023-08-28 18:36:53 -07002274// removeClient_l() must be called with AudioFlinger::clientMutex() held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275void AudioFlinger::removeClient_l(pid_t pid)
2276{
Glenn Kasten827e5f12012-11-02 10:00:06 -07002277 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002278 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 mClients.removeItem(pid);
2280}
2281
Andy Hung954b9712023-08-28 18:36:53 -07002282// getEffectThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07002283sp<IAfThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002284 int effectId)
Eric Laurent717e1282012-06-29 16:36:52 -07002285{
Andy Hung87c693c2023-07-06 20:56:16 -07002286 sp<IAfThreadBase> thread;
Eric Laurent717e1282012-06-29 16:36:52 -07002287
2288 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002289 thread = mPlaybackThreads.valueAt(i);
2290 if (thread->getEffect(sessionId, effectId) != 0) {
2291 return thread;
Eric Laurent717e1282012-06-29 16:36:52 -07002292 }
2293 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002294 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002295 thread = mRecordThreads.valueAt(i);
2296 if (thread->getEffect(sessionId, effectId) != 0) {
2297 return thread;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002298 }
2299 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002300 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Shunkai Yao0bc64562024-02-14 03:01:33 +00002301 thread = mMmapThreads.valueAt(i);
2302 if (thread->getEffect(sessionId, effectId) != 0) {
2303 return thread;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002304 }
2305 }
Shunkai Yao0bc64562024-02-14 03:01:33 +00002306 return nullptr;
Eric Laurent717e1282012-06-29 16:36:52 -07002307}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309// ----------------------------------------------------------------------------
2310
2311AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
Ytai Ben-Tsvi10dc0a62020-09-18 11:31:55 -07002312 const sp<media::IAudioFlingerClient>& client,
Andy Hung5bdc5352019-12-23 14:36:31 -08002313 pid_t pid,
2314 uid_t uid)
2315 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316{
2317}
2318
2319AudioFlinger::NotificationClient::~NotificationClient()
2320{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321}
2322
Glenn Kasten0f11b512014-01-31 16:18:54 -08002323void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324{
2325 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08002326 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327}
2328
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002329// ----------------------------------------------------------------------------
2330AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2331 : mPendingRequests(false) {}
2332
2333
2334void AudioFlinger::MediaLogNotifier::requestMerge() {
Andy Hung954b9712023-08-28 18:36:53 -07002335 audio_utils::lock_guard _l(mMutex);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002336 mPendingRequests = true;
Andy Hung954b9712023-08-28 18:36:53 -07002337 mCondition.notify_one();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002338}
2339
2340bool AudioFlinger::MediaLogNotifier::threadLoop() {
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002341 // Should already have been checked, but just in case
2342 if (sMediaLogService == 0) {
2343 return false;
2344 }
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002345 // Wait until there are pending requests
2346 {
Andy Hung954b9712023-08-28 18:36:53 -07002347 audio_utils::unique_lock _l(mMutex);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002348 mPendingRequests = false; // to ignore past requests
2349 while (!mPendingRequests) {
Andy Hung954b9712023-08-28 18:36:53 -07002350 mCondition.wait(_l);
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002351 // TODO may also need an exitPending check
2352 }
2353 mPendingRequests = false;
2354 }
2355 // Execute the actual MediaLogService binder call and ignore extra requests for a while
Glenn Kasten04b96fc2017-04-10 14:58:47 -07002356 sMediaLogService->requestMergeWakeup();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002357 usleep(kPostTriggerSleepPeriod);
2358 return true;
2359}
2360
2361void AudioFlinger::requestLogMerge() {
2362 mMediaLogNotifier->requestMerge();
2363}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364
2365// ----------------------------------------------------------------------------
2366
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002367status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2368 media::CreateRecordResponse& _output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369{
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08002370 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002371 CreateRecordOutput output;
2372
Andy Hung8d31fd22023-06-26 19:20:57 -07002373 sp<IAfRecordTrack> recordTrack;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 status_t lStatus;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002376 audio_session_t sessionId = input.sessionId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002377 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378
Eric Laurentf14db3c2017-12-08 14:20:36 -08002379 output.cblk.clear();
2380 output.buffers.clear();
Eric Laurent896c9672017-12-08 14:08:45 -08002381 output.inputId = AUDIO_IO_HANDLE_NONE;
Glenn Kastend776ac62014-05-07 09:16:09 -07002382
Atneya Nair07c665d2024-05-17 15:46:48 -07002383 AttributionSourceState adjAttributionSource;
2384 pid_t callingPid;
2385 if (!com::android::media::audio::audioserver_permissions()) {
2386 adjAttributionSource = input.clientInfo.attributionSource;
2387 bool updatePid = (adjAttributionSource.pid == -1);
2388 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2389 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2390 adjAttributionSource.uid));
2391 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
2392 ALOGW_IF(currentUid != callingUid,
2393 "%s uid %d tried to pass itself off as %d",
2394 __FUNCTION__, callingUid, currentUid);
2395 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
2396 legacy2aidl_uid_t_int32_t(callingUid));
2397 updatePid = true;
2398 }
2399 callingPid = IPCThreadState::self()->getCallingPid();
2400 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2401 adjAttributionSource.pid));
2402 if (updatePid) {
2403 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
2404 "%s uid %d pid %d tried to pass itself off as pid %d",
2405 __func__, callingUid, callingPid, currentPid);
2406 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
2407 legacy2aidl_pid_t_int32_t(callingPid));
2408 }
2409 adjAttributionSource = afutils::checkAttributionSourcePackage(
2410 adjAttributionSource);
2411 } else {
2412 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
2413 validateAttributionFromContextOrTrustedCaller(
2414 input.clientInfo.attributionSource,
2415 getPermissionProvider()
2416 ));
2417 // TODO pass wrapped object around
2418 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
2419 callingPid = adjAttributionSource.pid;
Haynes Mathew George9ea77cd2016-04-06 17:07:48 -07002420 }
Atneya Nair07c665d2024-05-17 15:46:48 -07002421
Dean Wheatleya404ff42023-10-20 13:25:02 +11002422 // further format checks are performed by createRecordTrack_l()
2423 if (!audio_is_valid_format(input.config.format)) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002424 ALOGE("createRecord() invalid format %#x", input.config.format);
Glenn Kasten291bb6d2013-07-16 17:23:39 -07002425 lStatus = BAD_VALUE;
2426 goto Exit;
2427 }
2428
Glenn Kasten53b5d092014-02-05 10:00:23 -08002429 // further channel mask checks are performed by createRecordTrack_l()
Eric Laurentf14db3c2017-12-08 14:20:36 -08002430 if (!audio_is_input_channel(input.config.channel_mask)) {
2431 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
Glenn Kasten53b5d092014-02-05 10:00:23 -08002432 lStatus = BAD_VALUE;
2433 goto Exit;
2434 }
2435
Eric Laurentf14db3c2017-12-08 14:20:36 -08002436 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2437 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2438 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2439 lStatus = BAD_VALUE;
2440 goto Exit;
2441 }
2442
2443 output.sessionId = sessionId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002444 output.selectedDeviceId = input.selectedDeviceId;
2445 output.flags = input.flags;
2446
Svet Ganov33761132021-05-13 22:51:08 +00002447 client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid)));
Eric Laurentf14db3c2017-12-08 14:20:36 -08002448
2449 // Not a conventional loop, but a retry loop for at most two iterations total.
2450 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2451 // Exits loop via break on no error of got exit on error
2452 // The sp<> references will be dropped when re-entering scope.
2453 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2454 for (;;) {
Eric Laurent896c9672017-12-08 14:08:45 -08002455 // release previously opened input if retrying.
2456 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2457 recordTrack.clear();
Eric Laurentfee19762018-01-29 18:44:13 -08002458 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002459 output.inputId = AUDIO_IO_HANDLE_NONE;
Yung Ti Su5fac9c62018-05-15 15:07:43 +08002460 output.selectedDeviceId = input.selectedDeviceId;
Eric Laurent77881cd2018-02-09 16:01:31 -08002461 portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent896c9672017-12-08 14:08:45 -08002462 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002463 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002464 input.riid,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002465 sessionId,
2466 // FIXME compare to AudioTrack
Svet Ganov33761132021-05-13 22:51:08 +00002467 adjAttributionSource,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002468 &input.config,
2469 output.flags, &output.selectedDeviceId, &portId);
jiabinc1de2df2019-05-07 14:26:40 -07002470 if (lStatus != NO_ERROR) {
2471 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2472 goto Exit;
2473 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002474
Glenn Kasten05997e22014-03-13 15:08:33 -07002475 {
Andy Hung954b9712023-08-28 18:36:53 -07002476 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002477 IAfRecordThread* const thread = checkRecordThread_l(output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 if (thread == NULL) {
Eric Laurentd52a28c2020-08-21 17:10:39 -07002479 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2480 lStatus = FAILED_TRANSACTION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002481 goto Exit;
2482 }
2483
Eric Laurentf14db3c2017-12-08 14:20:36 -08002484 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
Eric Laurentf14db3c2017-12-08 14:20:36 -08002486 output.sampleRate = input.config.sample_rate;
2487 output.frameCount = input.frameCount;
2488 output.notificationFrameCount = input.notificationFrameCount;
Glenn Kasten570f6332014-03-13 15:01:06 -07002489
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002490 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002491 input.config.format, input.config.channel_mask,
2492 &output.frameCount, sessionId,
2493 &output.notificationFrameCount,
Svet Ganov33761132021-05-13 22:51:08 +00002494 callingPid, adjAttributionSource, &output.flags,
Eric Laurentf14db3c2017-12-08 14:20:36 -08002495 input.clientInfo.clientTid,
Eric Laurentec376dc2021-04-08 20:41:22 +02002496 &lStatus, portId, input.maxSharedAudioHistoryMs);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002497 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
Eric Laurent1b928682014-10-02 19:41:47 -07002498
Eric Laurentf14db3c2017-12-08 14:20:36 -08002499 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2500 // audio policy manager without FAST constraint
2501 if (lStatus == BAD_TYPE) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002502 continue;
Eric Laurent1b928682014-10-02 19:41:47 -07002503 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08002504
2505 if (lStatus != NO_ERROR) {
Eric Laurentf14db3c2017-12-08 14:20:36 -08002506 goto Exit;
2507 }
2508
jiabinb00edc32021-08-16 16:27:54 +00002509 if (recordTrack->isFastTrack()) {
2510 output.serverConfig = {
2511 thread->sampleRate(),
2512 thread->channelMask(),
2513 thread->format()
2514 };
2515 } else {
2516 output.serverConfig = {
2517 recordTrack->sampleRate(),
2518 recordTrack->channelMask(),
2519 recordTrack->format()
2520 };
2521 }
2522
Robert Wu310037a2022-09-06 21:48:18 +00002523 output.halConfig = {
2524 thread->sampleRate(),
2525 thread->channelMask(),
2526 thread->format()
2527 };
2528
Eric Laurentf14db3c2017-12-08 14:20:36 -08002529 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2530 // session and move it to this thread.
Andy Hung6ac17eb2023-06-20 18:56:17 -07002531 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentf14db3c2017-12-08 14:20:36 -08002532 if (chain != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07002533 audio_utils::lock_guard _l2(thread->mutex());
Eric Laurentf14db3c2017-12-08 14:20:36 -08002534 thread->addEffectChain_l(chain);
2535 }
2536 break;
2537 }
2538 // End of retry loop.
2539 // The lack of indentation is deliberate, to reduce code churn and ease merges.
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 }
Glenn Kastene198c362013-08-13 09:13:36 -07002541
Eric Laurentf14db3c2017-12-08 14:20:36 -08002542 output.cblk = recordTrack->getCblk();
2543 output.buffers = recordTrack->getBuffers();
Eric Laurent973db022018-11-20 14:54:31 -08002544 output.portId = portId;
Eric Laurentf14db3c2017-12-08 14:20:36 -08002545
Andy Hungd29af632023-06-23 19:27:19 -07002546 output.audioRecord = IAfRecordTrack::createIAudioRecordAdapter(recordTrack);
Ytai Ben-Tsvi4dfeb622020-11-02 12:47:30 -08002547 _output = VALUE_OR_FATAL(output.toAidl());
2548
Eric Laurentf14db3c2017-12-08 14:20:36 -08002549Exit:
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002550 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002551 // remove local strong reference to Client before deleting the RecordTrack so that the
Andy Hung954b9712023-08-28 18:36:53 -07002552 // Client destructor is called by the TrackBase destructor with clientMutex() held
2553 // Don't hold clientMutex() when releasing the reference on the track as the
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002554 // destructor will acquire it.
2555 {
Andy Hung954b9712023-08-28 18:36:53 -07002556 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07002557 client.clear();
2558 }
Eric Laurent896c9672017-12-08 14:08:45 -08002559 recordTrack.clear();
2560 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfee19762018-01-29 18:44:13 -08002561 AudioSystem::releaseInput(portId);
Eric Laurent896c9672017-12-08 14:08:45 -08002562 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 }
2564
Ytai Ben-Tsvi16d87612020-11-03 16:32:36 -08002565 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566}
2567
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002568
2569
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570// ----------------------------------------------------------------------------
2571
Mikhail Naganovffd97712023-05-03 17:45:36 -07002572status_t AudioFlinger::getAudioPolicyConfig(media::AudioPolicyConfig *config)
2573{
2574 if (config == nullptr) {
2575 return BAD_VALUE;
2576 }
Andy Hung954b9712023-08-28 18:36:53 -07002577 audio_utils::lock_guard _l(mutex());
2578 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovffd97712023-05-03 17:45:36 -07002579 RETURN_STATUS_IF_ERROR(
2580 mDevicesFactoryHal->getSurroundSoundConfig(&config->surroundSoundConfig));
2581 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getEngineConfig(&config->engineConfig));
2582 std::vector<std::string> hwModuleNames;
2583 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getDeviceNames(&hwModuleNames));
2584 std::set<AudioMode> allSupportedModes;
2585 for (const auto& name : hwModuleNames) {
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002586 AudioHwDevice* module = loadHwModule_ll(name.c_str());
Mikhail Naganovffd97712023-05-03 17:45:36 -07002587 if (module == nullptr) continue;
2588 media::AudioHwModule aidlModule;
2589 if (module->hwDevice()->getAudioPorts(&aidlModule.ports) == OK &&
2590 module->hwDevice()->getAudioRoutes(&aidlModule.routes) == OK) {
2591 aidlModule.handle = module->handle();
2592 aidlModule.name = module->moduleName();
2593 config->modules.push_back(std::move(aidlModule));
2594 }
2595 std::vector<AudioMode> supportedModes;
2596 if (module->hwDevice()->getSupportedModes(&supportedModes) == OK) {
2597 allSupportedModes.insert(supportedModes.begin(), supportedModes.end());
2598 }
2599 }
2600 if (!allSupportedModes.empty()) {
2601 config->supportedModes.insert(config->supportedModes.end(),
2602 allSupportedModes.begin(), allSupportedModes.end());
2603 } else {
2604 ALOGW("%s: The HAL does not provide telephony functionality", __func__);
2605 config->supportedModes = { media::audio::common::AudioMode::NORMAL,
2606 media::audio::common::AudioMode::RINGTONE,
2607 media::audio::common::AudioMode::IN_CALL,
2608 media::audio::common::AudioMode::IN_COMMUNICATION };
2609 }
2610 return OK;
2611}
2612
Eric Laurenta4c5a552012-03-29 10:12:40 -07002613audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2614{
Eric Laurent44622db2014-08-01 19:00:33 -07002615 if (name == NULL) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002616 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurent44622db2014-08-01 19:00:33 -07002617 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002618 if (!settingsAllowed()) {
Glenn Kastena13cde92016-03-28 15:26:02 -07002619 return AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002620 }
Andy Hung954b9712023-08-28 18:36:53 -07002621 audio_utils::lock_guard _l(mutex());
2622 audio_utils::lock_guard lock(hardwareMutex());
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002623 AudioHwDevice* module = loadHwModule_ll(name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002624 return module != nullptr ? module->handle() : AUDIO_MODULE_HANDLE_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002625}
2626
Andy Hung954b9712023-08-28 18:36:53 -07002627// loadHwModule_l() must be called with AudioFlinger::mutex()
2628// and AudioFlinger::hardwareMutex() held
Andy Hungc2cf7ec2023-08-30 18:19:00 -07002629AudioHwDevice* AudioFlinger::loadHwModule_ll(const char *name)
Eric Laurenta4c5a552012-03-29 10:12:40 -07002630{
2631 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2632 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2633 ALOGW("loadHwModule() module %s already loaded", name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002634 return mAudioHwDevs.valueAt(i);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002635 }
2636 }
2637
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002638 sp<DeviceHalInterface> dev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002639
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002640 int rc = mDevicesFactoryHal->openDevice(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002641 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002642 ALOGE("loadHwModule() error %d loading module %s", rc, name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002643 return nullptr;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002644 }
Vlad Popa03bd5bc2023-01-17 16:16:51 +01002645 if (!mMelReporter->activateHalSoundDoseComputation(name, dev)) {
Vlad Popa1d5f0d52022-12-18 12:21:26 +01002646 ALOGW("loadHwModule() sound dose reporting is not available");
2647 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002648
2649 mHardwareStatus = AUDIO_HW_INIT;
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002650 rc = dev->initCheck();
Eric Laurenta4c5a552012-03-29 10:12:40 -07002651 mHardwareStatus = AUDIO_HW_IDLE;
2652 if (rc) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002653 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
Mikhail Naganovffd97712023-05-03 17:45:36 -07002654 return nullptr;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002655 }
2656
John Grossmanee578c02012-07-23 17:05:46 -07002657 // Check and cache this HAL's level of support for master mute and master
2658 // volume. If this is the first HAL opened, and it supports the get
2659 // methods, use the initial values provided by the HAL as the current
2660 // master mute and volume settings.
2661
2662 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002663 if (0 == mAudioHwDevs.size()) {
2664 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2665 float mv;
2666 if (OK == dev->getMasterVolume(&mv)) {
2667 mMasterVolume = mv;
John Grossmanee578c02012-07-23 17:05:46 -07002668 }
2669
Eric Laurent00abf0d2020-04-22 19:28:22 -07002670 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2671 bool mm;
2672 if (OK == dev->getMasterMute(&mm)) {
2673 mMasterMute = mm;
Andy Hung0e26ec62024-02-20 16:32:57 -08002674 ALOGI_IF(mMasterMute, "%s: applying mute from HAL %s", __func__, name);
John Grossmanee578c02012-07-23 17:05:46 -07002675 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002676 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07002677
2678 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2679 if (OK == dev->setMasterVolume(mMasterVolume)) {
2680 flags = static_cast<AudioHwDevice::Flags>(flags |
2681 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2682 }
2683
2684 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2685 if (OK == dev->setMasterMute(mMasterMute)) {
2686 flags = static_cast<AudioHwDevice::Flags>(flags |
2687 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2688 }
2689
2690 mHardwareStatus = AUDIO_HW_IDLE;
2691
Mikhail Naganov97373b02018-07-23 13:27:24 -07002692 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
Mikhail Naganovadca70f2018-07-09 12:49:25 -07002693 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2694 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2695 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002696
Eric Laurent52057642022-12-16 11:45:07 +01002697
2698 if (bool supports = false;
Eric Laurent50d72582022-12-20 20:20:23 +01002699 dev->supportsBluetoothVariableLatency(&supports) == NO_ERROR && supports) {
Eric Laurent52057642022-12-16 11:45:07 +01002700 flags = static_cast<AudioHwDevice::Flags>(flags |
2701 AudioHwDevice::AHWD_SUPPORTS_BT_LATENCY_MODES);
2702 }
2703
Glenn Kastena13cde92016-03-28 15:26:02 -07002704 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002705 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2706 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2707 mPrimaryHardwareDev = audioDevice;
2708 mHardwareStatus = AUDIO_HW_SET_MODE;
Andy Hunge3748872023-08-30 19:05:16 -07002709 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
Eric Laurent00abf0d2020-04-22 19:28:22 -07002710 mHardwareStatus = AUDIO_HW_IDLE;
2711 }
2712
Shunkai Yao2b8fed42022-12-09 01:12:02 +00002713 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
jiabine504e7b2021-09-18 00:27:08 +00002714 if (int32_t mixerBursts = dev->getAAudioMixerBurstCount();
jiabina4ff38f2022-02-11 19:42:25 +00002715 mixerBursts > 0 && mixerBursts > mAAudioBurstsPerBuffer) {
jiabine504e7b2021-09-18 00:27:08 +00002716 mAAudioBurstsPerBuffer = mixerBursts;
2717 }
2718 if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec();
jiabina4ff38f2022-02-11 19:42:25 +00002719 hwBurstMinMicros > 0
2720 && (hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0)) {
jiabine504e7b2021-09-18 00:27:08 +00002721 mAAudioHwBurstMinMicros = hwBurstMinMicros;
2722 }
2723 }
2724
Eric Laurent00abf0d2020-04-22 19:28:22 -07002725 mAudioHwDevs.add(handle, audioDevice);
Oleg Lyovin7434b722024-03-05 18:08:01 +03002726 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_STUB) != 0) {
2727 mInputBufferSizeOrderedDevs.insert(audioDevice);
2728 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07002729
Mikhail Naganove4f1f632016-08-31 11:35:10 -07002730 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07002731
Mikhail Naganovffd97712023-05-03 17:45:36 -07002732 return audioDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -07002733}
2734
Oleg Lyovin7434b722024-03-05 18:08:01 +03002735// Sort AudioHwDevice to be traversed in the getInputBufferSize call in the following order:
2736// Primary, Usb, Bluetooth, A2DP, other modules, remote submix.
2737/* static */
2738bool AudioFlinger::inputBufferSizeDevsCmp(const AudioHwDevice* lhs, const AudioHwDevice* rhs) {
2739 static const std::map<std::string_view, int> kPriorities = {
2740 { AUDIO_HARDWARE_MODULE_ID_PRIMARY, 0 }, { AUDIO_HARDWARE_MODULE_ID_USB, 1 },
2741 { AUDIO_HARDWARE_MODULE_ID_BLUETOOTH, 2 }, { AUDIO_HARDWARE_MODULE_ID_A2DP, 3 },
2742 { AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, std::numeric_limits<int>::max() }
2743 };
2744
2745 const std::string_view lhsName = lhs->moduleName();
2746 const std::string_view rhsName = rhs->moduleName();
2747
2748 auto lhsPriority = std::numeric_limits<int>::max() - 1;
2749 if (const auto lhsIt = kPriorities.find(lhsName); lhsIt != kPriorities.end()) {
2750 lhsPriority = lhsIt->second;
2751 }
2752 auto rhsPriority = std::numeric_limits<int>::max() - 1;
2753 if (const auto rhsIt = kPriorities.find(rhsName); rhsIt != kPriorities.end()) {
2754 rhsPriority = rhsIt->second;
2755 }
2756
2757 if (lhsPriority != rhsPriority) {
2758 return lhsPriority < rhsPriority;
2759 }
2760 return lhsName < rhsName;
2761}
2762
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002763// ----------------------------------------------------------------------------
2764
Andy Hungcdd80ef2023-07-17 11:37:26 -07002765uint32_t AudioFlinger::getPrimaryOutputSamplingRate() const
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002766{
Andy Hung954b9712023-08-28 18:36:53 -07002767 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002768 IAfPlaybackThread* const thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002769 return thread != NULL ? thread->sampleRate() : 0;
2770}
2771
Andy Hungcdd80ef2023-07-17 11:37:26 -07002772size_t AudioFlinger::getPrimaryOutputFrameCount() const
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002773{
Andy Hung954b9712023-08-28 18:36:53 -07002774 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07002775 IAfPlaybackThread* const thread = fastPlaybackThread_l();
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07002776 return thread != NULL ? thread->frameCountHAL() : 0;
2777}
2778
2779// ----------------------------------------------------------------------------
2780
Andy Hung6f248bb2018-01-23 14:04:37 -08002781status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002782{
2783 uid_t uid = IPCThreadState::self()->getCallingUid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07002784 if (!isAudioServerOrSystemServerUid(uid)) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002785 return PERMISSION_DENIED;
2786 }
Andy Hung954b9712023-08-28 18:36:53 -07002787 audio_utils::lock_guard _l(mutex());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002788 if (mIsDeviceTypeKnown) {
2789 return INVALID_OPERATION;
2790 }
2791 mIsLowRamDevice = isLowRamDevice;
Andy Hung6f248bb2018-01-23 14:04:37 -08002792 mTotalMemory = totalMemory;
2793 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2794 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2795 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2796 // though actual setting is determined through device configuration.
2797 constexpr int64_t GB = 1024 * 1024 * 1024;
2798 mClientSharedHeapSize =
2799 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2800 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2801 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2802 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2803 : 32 * kMinimumClientSharedHeapSizeBytes;
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002804 mIsDeviceTypeKnown = true;
Andy Hung6f248bb2018-01-23 14:04:37 -08002805
2806 // TODO: Cache the client shared heap size in a persistent property.
2807 // It's possible that a native process or Java service or app accesses audioserver
2808 // after it is registered by system server, but before AudioService updates
2809 // the memory info. This would occur immediately after boot or an audioserver
2810 // crash and restore. Before update from AudioService, the client would get the
2811 // minimum heap size.
2812
2813 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2814 (isLowRamDevice ? "true" : "false"),
2815 (long long)mTotalMemory,
2816 mClientSharedHeapSize.load());
Glenn Kasten4182c4e2013-07-15 14:45:07 -07002817 return NO_ERROR;
2818}
2819
Andy Hung6f248bb2018-01-23 14:04:37 -08002820size_t AudioFlinger::getClientSharedHeapSize() const
2821{
2822 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2823 if (heapSizeInBytes != 0) { // read-only property overrides all.
2824 return heapSizeInBytes;
2825 }
2826 return mClientSharedHeapSize;
2827}
2828
Mikhail Naganovdea53042018-04-26 13:10:21 -07002829status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2830{
2831 ALOGV(__func__);
2832
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08002833 status_t status = AudioValidator::validateAudioPortConfig(*config);
2834 if (status != NO_ERROR) {
2835 return status;
2836 }
2837
Mikhail Naganovdea53042018-04-26 13:10:21 -07002838 audio_module_handle_t module;
2839 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2840 module = config->ext.device.hw_module;
2841 } else {
2842 module = config->ext.mix.hw_module;
2843 }
2844
Andy Hung954b9712023-08-28 18:36:53 -07002845 audio_utils::lock_guard _l(mutex());
2846 audio_utils::lock_guard lock(hardwareMutex());
Mikhail Naganovdea53042018-04-26 13:10:21 -07002847 ssize_t index = mAudioHwDevs.indexOfKey(module);
2848 if (index < 0) {
2849 ALOGW("%s() bad hw module %d", __func__, module);
2850 return BAD_VALUE;
2851 }
2852
2853 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2854 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2855}
2856
Eric Laurent93c3d412014-08-01 14:48:35 -07002857audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2858{
Andy Hung954b9712023-08-28 18:36:53 -07002859 audio_utils::lock_guard _l(mutex());
Eric Laurentfa90e842014-10-17 18:12:31 -07002860
2861 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2862 if (index >= 0) {
2863 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2864 mHwAvSyncIds.valueAt(index), sessionId);
2865 return mHwAvSyncIds.valueAt(index);
2866 }
2867
Eric Laurent00abf0d2020-04-22 19:28:22 -07002868 sp<DeviceHalInterface> dev;
2869 {
Andy Hung954b9712023-08-28 18:36:53 -07002870 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002871 if (mPrimaryHardwareDev == nullptr) {
2872 return AUDIO_HW_SYNC_INVALID;
2873 }
Andy Hunge3748872023-08-30 19:05:16 -07002874 dev = mPrimaryHardwareDev.load()->hwDevice();
Eric Laurent00abf0d2020-04-22 19:28:22 -07002875 }
2876 if (dev == nullptr) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002877 return AUDIO_HW_SYNC_INVALID;
2878 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002879
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002880 error::Result<audio_hw_sync_t> result = dev->getHwAvSync();
2881 if (!result.ok()) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002882 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2883 return AUDIO_HW_SYNC_INVALID;
2884 }
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002885 audio_hw_sync_t value = VALUE_OR_FATAL(result);
Eric Laurentfa90e842014-10-17 18:12:31 -07002886
2887 // allow only one session for a given HW A/V sync ID.
2888 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
Ytai Ben-Tsvi48287b52021-12-01 15:07:11 -08002889 if (mHwAvSyncIds.valueAt(i) == value) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002890 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2891 value, mHwAvSyncIds.keyAt(i));
2892 mHwAvSyncIds.removeItemsAt(i);
Eric Laurent93c3d412014-08-01 14:48:35 -07002893 break;
2894 }
2895 }
Eric Laurentfa90e842014-10-17 18:12:31 -07002896
2897 mHwAvSyncIds.add(sessionId, value);
2898
2899 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07002900 const sp<IAfPlaybackThread> thread = mPlaybackThreads.valueAt(i);
Eric Laurentfa90e842014-10-17 18:12:31 -07002901 uint32_t sessions = thread->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07002902 if (sessions & IAfThreadBase::TRACK_SESSION) {
Eric Laurentfa90e842014-10-17 18:12:31 -07002903 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002904 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002905 String8 keyValuePairs = param.toString();
2906 thread->setParameters(keyValuePairs);
2907 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07002908 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07002909 break;
2910 }
2911 }
2912
2913 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2914 return (audio_hw_sync_t)value;
Eric Laurent93c3d412014-08-01 14:48:35 -07002915}
2916
Eric Laurent72e3f392015-05-20 14:43:50 -07002917status_t AudioFlinger::systemReady()
2918{
Andy Hung954b9712023-08-28 18:36:53 -07002919 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07002920 ALOGI("%s", __FUNCTION__);
2921 if (mSystemReady) {
2922 ALOGW("%s called twice", __FUNCTION__);
2923 return NO_ERROR;
2924 }
2925 mSystemReady = true;
2926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07002927 IAfThreadBase* const thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent72e3f392015-05-20 14:43:50 -07002928 thread->systemReady();
2929 }
2930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07002931 IAfThreadBase* const thread = mRecordThreads.valueAt(i).get();
Eric Laurent72e3f392015-05-20 14:43:50 -07002932 thread->systemReady();
2933 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02002934 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07002935 IAfThreadBase* const thread = mMmapThreads.valueAt(i).get();
Eric Laurentd66d7a12021-07-13 13:35:32 +02002936 thread->systemReady();
2937 }
Vlad Popae8d99472022-06-30 16:02:48 +02002938
2939 // Java services are ready, so we can create a reference to AudioService
2940 getOrCreateAudioManager();
2941
Eric Laurent72e3f392015-05-20 14:43:50 -07002942 return NO_ERROR;
2943}
2944
Vlad Popae8d99472022-06-30 16:02:48 +02002945sp<IAudioManager> AudioFlinger::getOrCreateAudioManager()
2946{
2947 if (mAudioManager.load() == nullptr) {
2948 // use checkService() to avoid blocking
2949 sp<IBinder> binder =
2950 defaultServiceManager()->checkService(String16(kAudioServiceName));
2951 if (binder != nullptr) {
2952 mAudioManager = interface_cast<IAudioManager>(binder);
2953 } else {
2954 ALOGE("%s(): binding to audio service failed.", __func__);
2955 }
2956 }
2957 return mAudioManager.load();
2958}
2959
Andy Hungcdd80ef2023-07-17 11:37:26 -07002960status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const
jiabin46a76fa2018-01-05 10:18:21 -08002961{
Andy Hung954b9712023-08-28 18:36:53 -07002962 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07002963 status_t status = INVALID_OPERATION;
2964
2965 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Shunkai Yaoed624a72022-12-12 06:11:46 +00002966 std::vector<audio_microphone_characteristic_t> mics;
Eric Laurent00abf0d2020-04-22 19:28:22 -07002967 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
2968 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
2969 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
2970 mHardwareStatus = AUDIO_HW_IDLE;
2971 if (devStatus == NO_ERROR) {
Eric Laurent00abf0d2020-04-22 19:28:22 -07002972 // report success if at least one HW module supports the function.
Mikhail Naganovd5d9de72023-02-13 11:45:03 -08002973 std::transform(mics.begin(), mics.end(), std::back_inserter(*microphones), [](auto& mic)
2974 {
2975 auto microphone =
2976 legacy2aidl_audio_microphone_characteristic_t_MicrophoneInfoFw(mic);
2977 return microphone.ok() ? microphone.value() : media::MicrophoneInfoFw{};
2978 });
Eric Laurent00abf0d2020-04-22 19:28:22 -07002979 status = NO_ERROR;
2980 }
2981 }
2982
jiabin9ff780e2018-03-19 18:19:52 -07002983 return status;
jiabin46a76fa2018-01-05 10:18:21 -08002984}
2985
Andy Hung954b9712023-08-28 18:36:53 -07002986// setAudioHwSyncForSession_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07002987void AudioFlinger::setAudioHwSyncForSession_l(
2988 IAfPlaybackThread* const thread, audio_session_t sessionId)
Eric Laurentfa90e842014-10-17 18:12:31 -07002989{
2990 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2991 if (index >= 0) {
2992 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
2993 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
2994 AudioParameter param = AudioParameter();
Mikhail Naganov00260b52016-10-13 12:54:24 -07002995 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
Mikhail Naganovb261ef52018-07-16 13:34:38 -07002996 String8 keyValuePairs = param.toString();
2997 thread->setParameters(keyValuePairs);
2998 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
Andy Hung87c693c2023-07-06 20:56:16 -07002999 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
Eric Laurentfa90e842014-10-17 18:12:31 -07003000 }
3001}
3002
3003
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003004// ----------------------------------------------------------------------------
3005
Eric Laurent83b88082014-06-20 18:31:16 -07003006
Andy Hung87c693c2023-07-06 20:56:16 -07003007sp<IAfThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
jiabin43810402019-10-24 14:58:31 -07003008 audio_io_handle_t *output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003009 audio_config_t *halConfig,
Andy Hung920f6572022-10-06 12:09:49 -07003010 audio_config_base_t *mixerConfig,
jiabin43810402019-10-24 14:58:31 -07003011 audio_devices_t deviceType,
3012 const String8& address,
3013 audio_output_flags_t flags)
Eric Laurent83b88082014-06-20 18:31:16 -07003014{
jiabin43810402019-10-24 14:58:31 -07003015 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
Eric Laurent83b88082014-06-20 18:31:16 -07003016 if (outHwDev == NULL) {
Eric Laurente28c66d2022-01-21 13:40:41 +01003017 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07003018 }
3019
Eric Laurentcf2c0212014-07-25 16:20:43 -07003020 if (*output == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08003021 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
3022 } else {
3023 // Audio Policy does not currently request a specific output handle.
3024 // If this is ever needed, see openInput_l() for example code.
3025 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
Eric Laurente28c66d2022-01-21 13:40:41 +01003026 return nullptr;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003027 }
Eric Laurent83b88082014-06-20 18:31:16 -07003028
3029 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Phil Burk062e67a2015-02-11 13:40:50 -08003030 AudioStreamOut *outputStream = NULL;
3031 status_t status = outHwDev->openOutputStream(
3032 &outputStream,
3033 *output,
jiabin43810402019-10-24 14:58:31 -07003034 deviceType,
Phil Burk062e67a2015-02-11 13:40:50 -08003035 flags,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003036 halConfig,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003037 address.c_str());
Eric Laurent83b88082014-06-20 18:31:16 -07003038
3039 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent83b88082014-06-20 18:31:16 -07003040
Phil Burk062e67a2015-02-11 13:40:50 -08003041 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003042 if (flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003043 const sp<IAfMmapPlaybackThread> thread = IAfMmapPlaybackThread::create(
3044 this, *output, outHwDev, outputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003045 mMmapThreads.add(*output, thread);
3046 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
3047 *output, thread.get());
3048 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003049 } else {
Andy Hung87c693c2023-07-06 20:56:16 -07003050 sp<IAfPlaybackThread> thread;
jiabinc658e452022-10-21 20:52:21 +00003051 if (flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003052 thread = IAfPlaybackThread::createBitPerfectThread(
3053 this, outputStream, *output, mSystemReady);
jiabinc658e452022-10-21 20:52:21 +00003054 ALOGV("%s() created bit-perfect output: ID %d thread %p",
3055 __func__, *output, thread.get());
3056 } else if (flags & AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003057 thread = IAfPlaybackThread::createSpatializerThread(this, outputStream, *output,
Eric Laurentb3f315a2021-07-13 15:09:05 +02003058 mSystemReady, mixerConfig);
Eric Laurente28c66d2022-01-21 13:40:41 +01003059 ALOGV("openOutput_l() created spatializer output: ID %d thread %p",
Eric Laurentb3f315a2021-07-13 15:09:05 +02003060 *output, thread.get());
3061 } else if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003062 thread = IAfPlaybackThread::createOffloadThread(this, outputStream, *output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07003063 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003064 ALOGV("openOutput_l() created offload output: ID %d thread %p",
3065 *output, thread.get());
3066 } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT)
Andy Hung81994d62023-07-20 21:44:14 -07003067 || !IAfThreadBase::isValidPcmSinkFormat(halConfig->format)
3068 || !IAfThreadBase::isValidPcmSinkChannelMask(halConfig->channel_mask)) {
Andy Hungee58e4a2023-07-07 13:47:37 -07003069 thread = IAfPlaybackThread::createDirectOutputThread(this, outputStream, *output,
Gareth Fennb18c1a32022-10-05 13:42:36 -07003070 mSystemReady, halConfig->offload_info);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003071 ALOGV("openOutput_l() created direct output: ID %d thread %p",
3072 *output, thread.get());
3073 } else {
Andy Hungee58e4a2023-07-07 13:47:37 -07003074 thread = IAfPlaybackThread::createMixerThread(
3075 this, outputStream, *output, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003076 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
3077 *output, thread.get());
3078 }
3079 mPlaybackThreads.add(*output, thread);
Eric Laurent74c38dc2020-12-23 18:19:44 +01003080 struct audio_patch patch;
Andy Hungb6692eb2023-07-13 16:52:46 -07003081 mPatchPanel->notifyStreamOpened(outHwDev, *output, &patch);
Eric Laurent74c38dc2020-12-23 18:19:44 +01003082 if (thread->isMsdDevice()) {
3083 thread->setDownStreamPatch(&patch);
3084 }
Eric Laurent50d72582022-12-20 20:20:23 +01003085 thread->setBluetoothVariableLatencyEnabled(mBluetoothLatencyModesEnabled.load());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003086 return thread;
Eric Laurent83b88082014-06-20 18:31:16 -07003087 }
Eric Laurent83b88082014-06-20 18:31:16 -07003088 }
3089
Eric Laurente28c66d2022-01-21 13:40:41 +01003090 return nullptr;
Eric Laurent83b88082014-06-20 18:31:16 -07003091}
3092
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003093status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
3094 media::OpenOutputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095{
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003096 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
3097 aidl2legacy_int32_t_audio_module_handle_t(request.module));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003098 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003099 aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/));
Eric Laurentf1f22e72021-07-13 14:04:14 +02003100 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003101 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003102 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
3103 aidl2legacy_DeviceDescriptorBase(request.device));
3104 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
Andy Hung973638a2020-12-08 20:47:45 -08003105 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003106
3107 audio_io_handle_t output;
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003108
jiabin43810402019-10-24 14:58:31 -07003109 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003110 "Channels %#x, flags %#x",
Eric Laurent6acd1d42017-01-04 14:23:29 -08003111 this, module,
jiabin43810402019-10-24 14:58:31 -07003112 device->toString().c_str(),
Eric Laurentf1f22e72021-07-13 14:04:14 +02003113 halConfig.sample_rate,
3114 halConfig.format,
3115 halConfig.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07003116 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117
jiabin43810402019-10-24 14:58:31 -07003118 audio_devices_t deviceType = device->type();
3119 const String8 address = String8(device->address().c_str());
3120
3121 if (deviceType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003122 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003124
Andy Hung954b9712023-08-28 18:36:53 -07003125 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126
Andy Hung87c693c2023-07-06 20:56:16 -07003127 const sp<IAfThreadBase> thread = openOutput_l(module, &output, &halConfig,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003128 &mixerConfig, deviceType, address, flags);
Eric Laurent83b88082014-06-20 18:31:16 -07003129 if (thread != 0) {
Andy Hung920f6572022-10-06 12:09:49 -07003130 uint32_t latencyMs = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003131 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
Andy Hung87c693c2023-07-06 20:56:16 -07003132 const auto playbackThread = thread->asIAfPlaybackThread();
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003133 latencyMs = playbackThread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134
Eric Laurent6acd1d42017-01-04 14:23:29 -08003135 // notify client processes of the new output creation
Andy Hungab65b182023-09-06 19:41:47 -07003136 playbackThread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003137
Eric Laurent00abf0d2020-04-22 19:28:22 -07003138 // the first primary output opened designates the primary hw device if no HW module
3139 // named "primary" was already loaded.
Andy Hung954b9712023-08-28 18:36:53 -07003140 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07003141 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08003142 ALOGI("Using module %d as the primary audio interface", module);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003143 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
Eric Laurenta4c5a552012-03-29 10:12:40 -07003144
Eric Laurent6acd1d42017-01-04 14:23:29 -08003145 mHardwareStatus = AUDIO_HW_SET_MODE;
Andy Hunge3748872023-08-30 19:05:16 -07003146 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003147 mHardwareStatus = AUDIO_HW_IDLE;
3148 }
3149 } else {
Andy Hungab65b182023-09-06 19:41:47 -07003150 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07003151 }
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003152 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003153 response->config = VALUE_OR_RETURN_STATUS(
3154 legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/));
Ytai Ben-Tsvi50e016a2020-11-12 14:26:12 -08003155 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
Andy Hung973638a2020-12-08 20:47:45 -08003156 response->flags = VALUE_OR_RETURN_STATUS(
3157 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
Eric Laurentcf2c0212014-07-25 16:20:43 -07003158 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 }
3160
Eric Laurentcf2c0212014-07-25 16:20:43 -07003161 return NO_INIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162}
3163
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003164audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
3165 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166{
Andy Hung954b9712023-08-28 18:36:53 -07003167 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003168 IAfPlaybackThread* const thread1 = checkMixerThread_l(output1);
3169 IAfPlaybackThread* const thread2 = checkMixerThread_l(output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170
3171 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003172 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
3173 output2);
Glenn Kasten142f5192014-03-25 17:44:59 -07003174 return AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175 }
3176
Glenn Kasteneeecb982016-02-26 10:44:04 -08003177 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
Andy Hungee58e4a2023-07-07 13:47:37 -07003178 const sp<IAfDuplicatingThread> thread = IAfDuplicatingThread::create(
3179 this, thread1, id, mSystemReady);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 thread->addOutputTrack(thread2);
3181 mPlaybackThreads.add(id, thread);
3182 // notify client processes of the new output creation
Andy Hungab65b182023-09-06 19:41:47 -07003183 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 return id;
3185}
3186
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003187status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188{
Glenn Kastend96c5722012-04-25 13:44:49 -07003189 return closeOutput_nonvirtual(output);
3190}
3191
3192status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
3193{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 // keep strong reference on the playback thread so that
3195 // it is not destroyed while exit() is executed
Andy Hung87c693c2023-07-06 20:56:16 -07003196 sp<IAfPlaybackThread> playbackThread;
Andy Hung7aa7d102023-07-07 15:58:48 -07003197 sp<IAfMmapPlaybackThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 {
Andy Hung954b9712023-08-28 18:36:53 -07003199 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003200 playbackThread = checkPlaybackThread_l(output);
3201 if (playbackThread != NULL) {
3202 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203
Andy Hungdc099c22018-09-18 13:46:39 -07003204 dumpToThreadLog_l(playbackThread);
Andy Hunga8115dc2018-08-24 15:51:59 -07003205
Andy Hung87c693c2023-07-06 20:56:16 -07003206 if (playbackThread->type() == IAfThreadBase::MIXER) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003207 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3208 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
Andy Hung87c693c2023-07-06 20:56:16 -07003209 IAfDuplicatingThread* const dupThread =
3210 mPlaybackThreads.valueAt(i)->asIAfDuplicatingThread().get();
3211 dupThread->removeOutputTrack(playbackThread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003212 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003213 }
3214 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003215
3216
Eric Laurent6acd1d42017-01-04 14:23:29 -08003217 mPlaybackThreads.removeItem(output);
Shunkai Yao517fc2a2024-03-19 04:31:47 +00003218 // Save AUDIO_SESSION_OUTPUT_MIX effect to orphan chains
3219 // Output Mix Effect session is used to manage Music Effect by AudioPolicy Manager.
3220 // It exists across all playback threads.
3221 if (playbackThread->type() == IAfThreadBase::MIXER
3222 || playbackThread->type() == IAfThreadBase::OFFLOAD
3223 || playbackThread->type() == IAfThreadBase::SPATIALIZER) {
3224 sp<IAfEffectChain> mixChain;
3225 {
3226 audio_utils::scoped_lock sl(playbackThread->mutex());
3227 mixChain = playbackThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3228 if (mixChain != nullptr) {
3229 ALOGW("%s() output %d moving mix session to orphans", __func__, output);
3230 playbackThread->removeEffectChain_l(mixChain);
3231 }
3232 }
3233 if (mixChain != nullptr) {
3234 putOrphanEffectChain_l(mixChain);
3235 }
3236 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003237 // save all effects to the default thread
3238 if (mPlaybackThreads.size()) {
Andy Hung87c693c2023-07-06 20:56:16 -07003239 IAfPlaybackThread* const dstThread =
3240 checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
Eric Laurent6acd1d42017-01-04 14:23:29 -08003241 if (dstThread != NULL) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003242 // audioflinger lock is held so order of thread lock acquisition doesn't matter
Andy Hunge0f5ec52023-08-30 11:26:06 -07003243 // Use scoped_lock to avoid deadlock order issues with duplicating threads.
3244 audio_utils::scoped_lock sl(dstThread->mutex(), playbackThread->mutex());
Andy Hung6ac17eb2023-06-20 18:56:17 -07003245 Vector<sp<IAfEffectChain>> effectChains = playbackThread->getEffectChains_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003246 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003247 moveEffectChain_ll(effectChains[i]->sessionId(), playbackThread.get(),
Eric Laurent6c796322019-04-09 14:13:17 -07003248 dstThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 }
3251 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003252 } else {
Andy Hung7aa7d102023-07-07 15:58:48 -07003253 const sp<IAfMmapThread> mt = checkMmapThread_l(output);
3254 mmapThread = mt ? mt->asIAfMmapPlaybackThread().get() : nullptr;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003255 if (mmapThread == 0) {
3256 return BAD_VALUE;
3257 }
Andy Hungdc099c22018-09-18 13:46:39 -07003258 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003259 mMmapThreads.removeItem(output);
Phil Burk7f6b40d2017-02-09 13:18:38 -08003260 ALOGD("closing mmapThread %p", mmapThread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 }
Andy Hungab65b182023-09-06 19:41:47 -07003262 ioConfigChanged_l(AUDIO_OUTPUT_CLOSED, sp<AudioIoDescriptor>::make(output));
Andy Hungb6692eb2023-07-13 16:52:46 -07003263 mPatchPanel->notifyStreamClosed(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08003265 // The thread entity (active unit of execution) is no longer running here,
Andy Hung87c693c2023-07-06 20:56:16 -07003266 // but the IAfThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267
Eric Laurent6acd1d42017-01-04 14:23:29 -08003268 if (playbackThread != 0) {
3269 playbackThread->exit();
3270 if (!playbackThread->isDuplicating()) {
3271 closeOutputFinish(playbackThread);
3272 }
3273 } else if (mmapThread != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08003274 ALOGD("mmapThread exit()");
Eric Laurent6acd1d42017-01-04 14:23:29 -08003275 mmapThread->exit();
3276 AudioStreamOut *out = mmapThread->clearOutput();
3277 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3278 // from now on thread->mOutput is NULL
3279 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 }
3281 return NO_ERROR;
3282}
3283
Andy Hungc2cf7ec2023-08-30 18:19:00 -07003284/* static */
Andy Hung87c693c2023-07-06 20:56:16 -07003285void AudioFlinger::closeOutputFinish(const sp<IAfPlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003286{
3287 AudioStreamOut *out = thread->clearOutput();
3288 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3289 // from now on thread->mOutput is NULL
Eric Laurent83b88082014-06-20 18:31:16 -07003290 delete out;
3291}
3292
Andy Hung87c693c2023-07-06 20:56:16 -07003293void AudioFlinger::closeThreadInternal_l(const sp<IAfPlaybackThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003294{
Andy Hung87c693c2023-07-06 20:56:16 -07003295 mPlaybackThreads.removeItem(thread->id());
Eric Laurent83b88082014-06-20 18:31:16 -07003296 thread->exit();
3297 closeOutputFinish(thread);
3298}
3299
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003300status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301{
Andy Hung954b9712023-08-28 18:36:53 -07003302 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003303 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304
3305 if (thread == NULL) {
3306 return BAD_VALUE;
3307 }
3308
Steve Block3856b092011-10-20 11:56:00 +01003309 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 thread->suspend();
3311
3312 return NO_ERROR;
3313}
3314
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003315status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316{
Andy Hung954b9712023-08-28 18:36:53 -07003317 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003318 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319
3320 if (thread == NULL) {
3321 return BAD_VALUE;
3322 }
3323
Steve Block3856b092011-10-20 11:56:00 +01003324 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325
3326 thread->restore();
3327
3328 return NO_ERROR;
3329}
3330
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003331status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
3332 media::OpenInputResponse* response)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333{
Andy Hung954b9712023-08-28 18:36:53 -07003334 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07003335
Mikhail Naganov21a32ec2021-07-08 14:40:12 -07003336 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
3337 aidl2legacy_AudioDeviceTypeAddress(request.device));
3338 if (device.mType == AUDIO_DEVICE_NONE) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003339 return BAD_VALUE;
Eric Laurent83b88082014-06-20 18:31:16 -07003340 }
3341
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003342 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
3343 aidl2legacy_int32_t_audio_io_handle_t(request.input));
3344 audio_config_t config = VALUE_OR_RETURN_STATUS(
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003345 aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003346
Andy Hung87c693c2023-07-06 20:56:16 -07003347 const sp<IAfThreadBase> thread = openInput_l(
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003348 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
3349 &input,
3350 &config,
3351 device.mType,
3352 device.address().c_str(),
Mikhail Naganovddceecc2021-09-03 13:58:56 -07003353 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)),
Andy Hung973638a2020-12-08 20:47:45 -08003354 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003355 AUDIO_DEVICE_NONE,
3356 String8{});
3357
3358 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
Mikhail Naganovde3fa182021-07-30 15:06:42 -07003359 response->config = VALUE_OR_RETURN_STATUS(
3360 legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003361 response->device = request.device;
Eric Laurent83b88082014-06-20 18:31:16 -07003362
3363 if (thread != 0) {
Eric Laurent83b88082014-06-20 18:31:16 -07003364 // notify client processes of the new input creation
Andy Hungab65b182023-09-06 19:41:47 -07003365 thread->ioConfigChanged_l(AUDIO_INPUT_OPENED);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003366 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003368 return NO_INIT;
Eric Laurent83b88082014-06-20 18:31:16 -07003369}
Dima Zavin799a70e2011-04-18 16:57:27 -07003370
Andy Hung87c693c2023-07-06 20:56:16 -07003371sp<IAfThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003372 audio_io_handle_t *input,
3373 audio_config_t *config,
Glenn Kastene7d66712015-03-05 13:46:52 -08003374 audio_devices_t devices,
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08003375 const char* address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003376 audio_source_t source,
Mikhail Naganovb4e037e2019-01-14 15:56:33 -08003377 audio_input_flags_t flags,
3378 audio_devices_t outputDevice,
3379 const String8& outputDeviceAddress)
Eric Laurent83b88082014-06-20 18:31:16 -07003380{
Glenn Kastene7d66712015-03-05 13:46:52 -08003381 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003382 if (inHwDev == NULL) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003383 *input = AUDIO_IO_HANDLE_NONE;
Dima Zavin799a70e2011-04-18 16:57:27 -07003384 return 0;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -07003385 }
Dima Zavin799a70e2011-04-18 16:57:27 -07003386
Glenn Kasteneeecb982016-02-26 10:44:04 -08003387 // Audio Policy can request a specific handle for hardware hotword.
3388 // The goal here is not to re-open an already opened input.
3389 // It is to use a pre-assigned I/O handle.
Eric Laurentcf2c0212014-07-25 16:20:43 -07003390 if (*input == AUDIO_IO_HANDLE_NONE) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08003391 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3392 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
3393 ALOGE("openInput_l() requested input handle %d is invalid", *input);
3394 return 0;
3395 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
3396 // This should not happen in a transient state with current design.
3397 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
3398 return 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003399 }
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07003400
Dean Wheatley6c009512023-10-23 09:34:14 +11003401 AudioStreamIn *inputStream = nullptr;
3402 status_t status = inHwDev->openInputStream(
3403 &inputStream,
3404 *input,
Mikhail Naganovf558e022016-11-14 17:45:17 -08003405 devices,
Glenn Kastenec40d282014-07-15 15:31:26 -07003406 flags,
Dean Wheatley6c009512023-10-23 09:34:14 +11003407 config,
3408 address,
3409 source,
3410 outputDevice,
3411 outputDeviceAddress.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412
Dean Wheatley6c009512023-10-23 09:34:14 +11003413 if (status == NO_ERROR) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003414 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003415 const sp<IAfMmapCaptureThread> thread =
Andy Hungee58e4a2023-07-07 13:47:37 -07003416 IAfMmapCaptureThread::create(this, *input, inHwDev, inputStream, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003417 mMmapThreads.add(*input, thread);
Glenn Kastend3bb6452016-12-05 18:14:37 -08003418 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
3419 thread.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003420 return thread;
3421 } else {
Eric Laurent6acd1d42017-01-04 14:23:29 -08003422 // Start record thread
Andy Hung87c693c2023-07-06 20:56:16 -07003423 // IAfRecordThread requires both input and output device indication
3424 // to forward to audio pre processing modules
3425 const sp<IAfRecordThread> thread =
3426 IAfRecordThread::create(this, inputStream, *input, mSystemReady);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003427 mRecordThreads.add(*input, thread);
3428 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
3429 return thread;
3430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 }
3432
Eric Laurentcf2c0212014-07-25 16:20:43 -07003433 *input = AUDIO_IO_HANDLE_NONE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 return 0;
3435}
3436
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003437status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438{
Glenn Kastend96c5722012-04-25 13:44:49 -07003439 return closeInput_nonvirtual(input);
3440}
3441
3442status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
3443{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 // keep strong reference on the record thread so that
3445 // it is not destroyed while exit() is executed
Andy Hung87c693c2023-07-06 20:56:16 -07003446 sp<IAfRecordThread> recordThread;
Andy Hung7aa7d102023-07-07 15:58:48 -07003447 sp<IAfMmapCaptureThread> mmapThread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448 {
Andy Hung954b9712023-08-28 18:36:53 -07003449 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003450 recordThread = checkRecordThread_l(input);
3451 if (recordThread != 0) {
3452 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453
Andy Hungdc099c22018-09-18 13:46:39 -07003454 dumpToThreadLog_l(recordThread);
Andy Hung0264e7d2018-09-17 19:30:46 -07003455
Eric Laurent6acd1d42017-01-04 14:23:29 -08003456 // If we still have effect chains, it means that a client still holds a handle
3457 // on at least one effect. We must either move the chain to an existing thread with the
3458 // same session ID or put it aside in case a new record thread is opened for a
3459 // new capture on the same session
Andy Hung6ac17eb2023-06-20 18:56:17 -07003460 sp<IAfEffectChain> chain;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003461 {
Andy Hungc5007f82023-08-29 14:26:09 -07003462 audio_utils::lock_guard _sl(recordThread->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003463 const Vector<sp<IAfEffectChain>> effectChains = recordThread->getEffectChains_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003464 // Note: maximum one chain per record thread
3465 if (effectChains.size() != 0) {
3466 chain = effectChains[0];
Eric Laurent1b928682014-10-02 19:41:47 -07003467 }
3468 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003469 if (chain != 0) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08003470 // first check if a record thread is already opened with a client on same session.
Eric Laurent6acd1d42017-01-04 14:23:29 -08003471 // This should only happen in case of overlap between one thread tear down and the
3472 // creation of its replacement
3473 size_t i;
3474 for (i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003475 const sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003476 if (t == recordThread) {
3477 continue;
3478 }
3479 if (t->hasAudioSession(chain->sessionId()) != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07003480 audio_utils::lock_guard _l2(t->mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003481 ALOGV("closeInput() found thread %d for effect session %d",
3482 t->id(), chain->sessionId());
3483 t->addEffectChain_l(chain);
3484 break;
3485 }
3486 }
Glenn Kastend3bb6452016-12-05 18:14:37 -08003487 // put the chain aside if we could not find a record thread with the same session id
Eric Laurent6acd1d42017-01-04 14:23:29 -08003488 if (i == mRecordThreads.size()) {
3489 putOrphanEffectChain_l(chain);
3490 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003491 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003492 mRecordThreads.removeItem(input);
3493 } else {
Andy Hung7aa7d102023-07-07 15:58:48 -07003494 const sp<IAfMmapThread> mt = checkMmapThread_l(input);
3495 mmapThread = mt ? mt->asIAfMmapCaptureThread().get() : nullptr;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003496 if (mmapThread == 0) {
3497 return BAD_VALUE;
3498 }
Andy Hungdc099c22018-09-18 13:46:39 -07003499 dumpToThreadLog_l(mmapThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003500 mMmapThreads.removeItem(input);
Eric Laurentaaa44472014-09-12 17:41:50 -07003501 }
Andy Hungab65b182023-09-06 19:41:47 -07003502 ioConfigChanged_l(AUDIO_INPUT_CLOSED, sp<AudioIoDescriptor>::make(input));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 }
Andy Hung954b9712023-08-28 18:36:53 -07003504 // FIXME: calling thread->exit() without mutex() held should not be needed anymore now that
Eric Laurent83b88082014-06-20 18:31:16 -07003505 // we have a different lock for notification client
Eric Laurent6acd1d42017-01-04 14:23:29 -08003506 if (recordThread != 0) {
3507 closeInputFinish(recordThread);
3508 } else if (mmapThread != 0) {
3509 mmapThread->exit();
3510 AudioStreamIn *in = mmapThread->clearInput();
3511 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3512 // from now on thread->mInput is NULL
3513 delete in;
3514 }
Eric Laurent83b88082014-06-20 18:31:16 -07003515 return NO_ERROR;
3516}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517
Andy Hung87c693c2023-07-06 20:56:16 -07003518void AudioFlinger::closeInputFinish(const sp<IAfRecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003519{
3520 thread->exit();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003521 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003522 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003523 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07003524 delete in;
Eric Laurent83b88082014-06-20 18:31:16 -07003525}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526
Andy Hung87c693c2023-07-06 20:56:16 -07003527void AudioFlinger::closeThreadInternal_l(const sp<IAfRecordThread>& thread)
Eric Laurent83b88082014-06-20 18:31:16 -07003528{
Andy Hung87c693c2023-07-06 20:56:16 -07003529 mRecordThreads.removeItem(thread->id());
Eric Laurent83b88082014-06-20 18:31:16 -07003530 closeInputFinish(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531}
3532
jiabinc44b3462022-12-08 12:52:31 -08003533status_t AudioFlinger::invalidateTracks(const std::vector<audio_port_handle_t> &portIds) {
Andy Hung954b9712023-08-28 18:36:53 -07003534 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003535 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536
jiabinc44b3462022-12-08 12:52:31 -08003537 std::set<audio_port_handle_t> portIdSet(portIds.begin(), portIds.end());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003539 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
jiabinc44b3462022-12-08 12:52:31 -08003540 thread->invalidateTracks(portIdSet);
3541 if (portIdSet.empty()) {
3542 return NO_ERROR;
3543 }
Eric Laurentde070132010-07-13 04:45:46 -07003544 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003545 for (size_t i = 0; i < mMmapThreads.size(); i++) {
jiabinc44b3462022-12-08 12:52:31 -08003546 mMmapThreads[i]->invalidateTracks(portIdSet);
3547 if (portIdSet.empty()) {
3548 return NO_ERROR;
3549 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08003550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 return NO_ERROR;
3552}
3553
3554
Glenn Kasteneeecb982016-02-26 10:44:04 -08003555audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556{
Glenn Kasten9d003132016-04-06 14:38:09 -07003557 // This is a binder API, so a malicious client could pass in a bad parameter.
3558 // Check for that before calling the internal API nextUniqueId().
3559 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3560 ALOGE("newAudioUniqueId invalid use %d", use);
3561 return AUDIO_UNIQUE_ID_ALLOCATE;
3562 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003563 return nextUniqueId(use);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564}
3565
Andy Hung8b0bfd92019-12-23 13:11:11 -08003566void AudioFlinger::acquireAudioSessionId(
3567 audio_session_t audioSession, pid_t pid, uid_t uid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003568{
Andy Hung954b9712023-08-28 18:36:53 -07003569 audio_utils::lock_guard _l(mutex());
Glenn Kastenbb001922012-02-03 11:10:26 -08003570 pid_t caller = IPCThreadState::self()->getCallingPid();
Marco Nelissend457c972014-02-11 08:47:07 -08003571 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
Andy Hung4ef19fa2018-05-15 19:35:29 -07003572 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003573 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3574 caller = pid; // check must match releaseAudioSessionId()
3575 }
3576 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3577 uid = callerUid;
Marco Nelissend457c972014-02-11 08:47:07 -08003578 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003579
Eric Laurent021cf962014-05-13 10:18:14 -07003580 {
Andy Hung954b9712023-08-28 18:36:53 -07003581 audio_utils::lock_guard _cl(clientMutex());
Eric Laurent021cf962014-05-13 10:18:14 -07003582 // Ignore requests received from processes not known as notification client. The request
3583 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3584 // called from a different pid leaving a stale session reference. Also we don't know how
3585 // to clear this reference if the client process dies.
3586 if (mNotificationClients.indexOfKey(caller) < 0) {
3587 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3588 return;
3589 }
Eric Laurentd1b28d42013-09-18 18:47:13 -07003590 }
3591
Glenn Kasten8d6a2442012-02-08 14:04:28 -08003592 size_t num = mAudioSessionRefs.size();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003593 for (size_t i = 0; i < num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003594 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003595 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3596 ref->mCnt++;
3597 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003598 return;
3599 }
3600 }
Andy Hung8b0bfd92019-12-23 13:11:11 -08003601 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003602 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003603}
3604
Glenn Kastend848eb42016-03-08 13:42:11 -08003605void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003606{
Andy Hung6ac17eb2023-06-20 18:56:17 -07003607 std::vector<sp<IAfEffectModule>> removedEffects;
Eric Laurent6c796322019-04-09 14:13:17 -07003608 {
Andy Hung954b9712023-08-28 18:36:53 -07003609 audio_utils::lock_guard _l(mutex());
Eric Laurent6c796322019-04-09 14:13:17 -07003610 pid_t caller = IPCThreadState::self()->getCallingPid();
3611 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3612 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
Andy Hung8b0bfd92019-12-23 13:11:11 -08003613 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3614 caller = pid; // check must match acquireAudioSessionId()
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003615 }
Eric Laurent6c796322019-04-09 14:13:17 -07003616 size_t num = mAudioSessionRefs.size();
3617 for (size_t i = 0; i < num; i++) {
3618 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3619 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3620 ref->mCnt--;
3621 ALOGV(" decremented refcount to %d", ref->mCnt);
3622 if (ref->mCnt == 0) {
3623 mAudioSessionRefs.removeAt(i);
3624 delete ref;
Andy Hung6ac17eb2023-06-20 18:56:17 -07003625 std::vector<sp<IAfEffectModule>> effects = purgeStaleEffects_l();
Eric Laurent6c796322019-04-09 14:13:17 -07003626 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3627 }
3628 goto Exit;
3629 }
3630 }
3631 // If the caller is audioserver it is likely that the session being released was acquired
3632 // on behalf of a process not in notification clients and we ignore the warning.
3633 ALOGW_IF(!isAudioServerUid(callerUid),
3634 "session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003635 }
Eric Laurent6c796322019-04-09 14:13:17 -07003636
3637Exit:
3638 for (auto& effect : removedEffects) {
3639 effect->updatePolicyState();
3640 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003641}
3642
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08003643bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3644{
3645 size_t num = mAudioSessionRefs.size();
3646 for (size_t i = 0; i < num; i++) {
3647 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3648 if (ref->mSessionid == audioSession) {
3649 return true;
3650 }
3651 }
3652 return false;
3653}
3654
Andy Hung6ac17eb2023-06-20 18:56:17 -07003655std::vector<sp<IAfEffectModule>> AudioFlinger::purgeStaleEffects_l() {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003656
Steve Block3856b092011-10-20 11:56:00 +01003657 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003658
Andy Hung87c693c2023-07-06 20:56:16 -07003659 Vector<sp<IAfEffectChain>> chains;
Andy Hung6ac17eb2023-06-20 18:56:17 -07003660 std::vector< sp<IAfEffectModule> > removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003661
3662 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003663 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003664 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003665 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3666 for (size_t j = 0; j < threadChains.size(); j++) {
3667 sp<IAfEffectChain> ec = threadChains[j];
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003668 if (!audio_is_global_session(ec->sessionId())) {
Marco Nelissen0270b182011-08-12 14:14:39 -07003669 chains.push(ec);
3670 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003671 }
3672 }
Eric Laurent6c796322019-04-09 14:13:17 -07003673
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003674 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003675 sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003676 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003677 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3678 for (size_t j = 0; j < threadChains.size(); j++) {
3679 sp<IAfEffectChain> ec = threadChains[j];
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003680 chains.push(ec);
3681 }
3682 }
3683
Eric Laurent6c796322019-04-09 14:13:17 -07003684 for (size_t i = 0; i < mMmapThreads.size(); i++) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003685 const sp<IAfMmapThread> t = mMmapThreads.valueAt(i);
Andy Hungc5007f82023-08-29 14:26:09 -07003686 audio_utils::lock_guard _l(t->mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07003687 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3688 for (size_t j = 0; j < threadChains.size(); j++) {
3689 sp<IAfEffectChain> ec = threadChains[j];
Eric Laurent6c796322019-04-09 14:13:17 -07003690 chains.push(ec);
3691 }
3692 }
3693
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003694 for (size_t i = 0; i < chains.size(); i++) {
Andy Hung920f6572022-10-06 12:09:49 -07003695 // clang-tidy suggests const ref
Andy Hung6ac17eb2023-06-20 18:56:17 -07003696 sp<IAfEffectChain> ec = chains[i]; // NOLINT(performance-unnecessary-copy-initialization)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003697 int sessionid = ec->sessionId();
Andy Hung99b1ba62023-07-14 11:00:08 -07003698 const auto t = ec->thread().promote();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003699 if (t == 0) {
3700 continue;
3701 }
3702 size_t numsessionrefs = mAudioSessionRefs.size();
3703 bool found = false;
3704 for (size_t k = 0; k < numsessionrefs; k++) {
3705 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08003706 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01003707 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003708 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003709 found = true;
3710 break;
3711 }
3712 }
3713 if (!found) {
Andy Hungc5007f82023-08-29 14:26:09 -07003714 audio_utils::lock_guard _l(t->mutex());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003715 // remove all effects from the chain
Andy Hung6ac17eb2023-06-20 18:56:17 -07003716 while (ec->numberOfEffects()) {
3717 sp<IAfEffectModule> effect = ec->getEffectModule(0);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003718 effect->unPin();
Mikhail Naganov424c4f52017-07-19 17:54:29 -07003719 t->removeEffect_l(effect, /*release*/ true);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003720 if (effect->purgeHandles()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08003721 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003722 }
Eric Laurent6c796322019-04-09 14:13:17 -07003723 removedEffects.push_back(effect);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003724 }
3725 }
3726 }
Eric Laurent6c796322019-04-09 14:13:17 -07003727 return removedEffects;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07003728}
3729
François Gaffie1b4753e2023-02-06 10:36:33 +01003730std::vector< sp<IAfEffectModule> > AudioFlinger::purgeOrphanEffectChains_l()
3731{
3732 ALOGV("purging stale effects from orphan chains");
3733 std::vector< sp<IAfEffectModule> > removedEffects;
3734 for (size_t index = 0; index < mOrphanEffectChains.size(); index++) {
3735 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
3736 audio_session_t session = mOrphanEffectChains.keyAt(index);
3737 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_DEVICE
3738 || session == AUDIO_SESSION_OUTPUT_STAGE) {
3739 continue;
3740 }
3741 size_t numSessionRefs = mAudioSessionRefs.size();
3742 bool found = false;
3743 for (size_t k = 0; k < numSessionRefs; k++) {
3744 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3745 if (ref->mSessionid == session) {
3746 ALOGV(" session %d still exists for %d with %d refs", session, ref->mPid,
3747 ref->mCnt);
3748 found = true;
3749 break;
3750 }
3751 }
3752 if (!found) {
3753 for (size_t i = 0; i < chain->numberOfEffects(); i++) {
3754 sp<IAfEffectModule> effect = chain->getEffectModule(i);
3755 removedEffects.push_back(effect);
3756 }
3757 }
3758 }
3759 for (auto& effect : removedEffects) {
3760 effect->unPin();
3761 updateOrphanEffectChains_l(effect);
3762 }
3763 return removedEffects;
3764}
3765
Andy Hung954b9712023-08-28 18:36:53 -07003766// dumpToThreadLog_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003767void AudioFlinger::dumpToThreadLog_l(const sp<IAfThreadBase> &thread)
Andy Hungdc099c22018-09-18 13:46:39 -07003768{
Jaideep Sharma330845f2020-10-22 12:14:58 +05303769 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
Atneya Nair50ffdd12023-12-05 20:42:35 -08003770 constexpr auto PREFIX = "- ";
3771 if (com::android::media::audioserver::fdtostring_timeout_fix()) {
3772 using ::android::audio_utils::FdToString;
3773
3774 auto writer = OR_RETURN(FdToString::createWriter(PREFIX));
3775 thread->dump(writer.borrowFdUnsafe(), {} /* args */);
3776 mThreadLog.logs(-1 /* time */, FdToString::closeWriterAndGetString(std::move(writer)));
3777 } else {
3778 audio_utils::FdToStringOldImpl fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
3779 const int fd = fdToString.borrowFdUnsafe();
3780 if (fd >= 0) {
3781 thread->dump(fd, {} /* args */);
3782 mThreadLog.logs(-1 /* time */, fdToString.closeAndGetString());
3783 }
Andy Hungdc099c22018-09-18 13:46:39 -07003784 }
3785}
3786
Andy Hung954b9712023-08-28 18:36:53 -07003787// checkThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003788IAfThreadBase* AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
Glenn Kasteneeecb982016-02-26 10:44:04 -08003789{
Andy Hung87c693c2023-07-06 20:56:16 -07003790 IAfThreadBase* thread = checkMmapThread_l(ioHandle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003791 if (thread == 0) {
3792 switch (audio_unique_id_get_use(ioHandle)) {
3793 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3794 thread = checkPlaybackThread_l(ioHandle);
3795 break;
3796 case AUDIO_UNIQUE_ID_USE_INPUT:
3797 thread = checkRecordThread_l(ioHandle);
3798 break;
3799 default:
3800 break;
3801 }
Glenn Kasteneeecb982016-02-26 10:44:04 -08003802 }
3803 return thread;
3804}
3805
Andy Hung954b9712023-08-28 18:36:53 -07003806// checkOutputThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003807sp<IAfThreadBase> AudioFlinger::checkOutputThread_l(audio_io_handle_t ioHandle) const
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003808{
3809 if (audio_unique_id_get_use(ioHandle) != AUDIO_UNIQUE_ID_USE_OUTPUT) {
3810 return nullptr;
3811 }
3812
Andy Hung87c693c2023-07-06 20:56:16 -07003813 sp<IAfThreadBase> thread = mPlaybackThreads.valueFor(ioHandle);
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01003814 if (thread == nullptr) {
3815 thread = mMmapThreads.valueFor(ioHandle);
3816 }
3817 return thread;
3818}
3819
Andy Hung954b9712023-08-28 18:36:53 -07003820// checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003821IAfPlaybackThread* AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822{
Glenn Kastena1117922012-01-26 10:53:32 -08003823 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824}
3825
Andy Hung954b9712023-08-28 18:36:53 -07003826// checkMixerThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003827IAfPlaybackThread* AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828{
Andy Hung87c693c2023-07-06 20:56:16 -07003829 IAfPlaybackThread * const thread = checkPlaybackThread_l(output);
3830 return thread != nullptr && thread->type() != IAfThreadBase::DIRECT ? thread : nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831}
3832
Andy Hung954b9712023-08-28 18:36:53 -07003833// checkRecordThread_l() must be called with AudioFlinger::mutex() held
Andy Hung87c693c2023-07-06 20:56:16 -07003834IAfRecordThread* AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003835{
Glenn Kastena1117922012-01-26 10:53:32 -08003836 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837}
3838
Andy Hung954b9712023-08-28 18:36:53 -07003839// checkMmapThread_l() must be called with AudioFlinger::mutex() held
Andy Hung7aa7d102023-07-07 15:58:48 -07003840IAfMmapThread* AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003841{
3842 return mMmapThreads.valueFor(io).get();
3843}
3844
3845
Andy Hung954b9712023-08-28 18:36:53 -07003846// checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
Andy Hung84074c62023-07-06 19:21:50 -07003847sp<VolumeInterface> AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003848{
Andy Hung84074c62023-07-06 19:21:50 -07003849 sp<VolumeInterface> volumeInterface = mPlaybackThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003850 if (volumeInterface == nullptr) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003851 IAfMmapThread* const mmapThread = mMmapThreads.valueFor(output).get();
Eric Laurent6acd1d42017-01-04 14:23:29 -08003852 if (mmapThread != nullptr) {
3853 if (mmapThread->isOutput()) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003854 IAfMmapPlaybackThread* const mmapPlaybackThread =
3855 mmapThread->asIAfMmapPlaybackThread().get();
Eric Laurent7459b902017-04-19 18:10:41 -07003856 volumeInterface = mmapPlaybackThread;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003857 }
3858 }
3859 }
3860 return volumeInterface;
3861}
3862
Andy Hung84074c62023-07-06 19:21:50 -07003863std::vector<sp<VolumeInterface>> AudioFlinger::getAllVolumeInterfaces_l() const
Eric Laurent6acd1d42017-01-04 14:23:29 -08003864{
Andy Hung84074c62023-07-06 19:21:50 -07003865 std::vector<sp<VolumeInterface>> volumeInterfaces;
Eric Laurent6acd1d42017-01-04 14:23:29 -08003866 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung84074c62023-07-06 19:21:50 -07003867 volumeInterfaces.push_back(mPlaybackThreads.valueAt(i).get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08003868 }
3869 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3870 if (mMmapThreads.valueAt(i)->isOutput()) {
Andy Hung7aa7d102023-07-07 15:58:48 -07003871 IAfMmapPlaybackThread* const mmapPlaybackThread =
3872 mMmapThreads.valueAt(i)->asIAfMmapPlaybackThread().get();
Andy Hung84074c62023-07-06 19:21:50 -07003873 volumeInterfaces.push_back(mmapPlaybackThread);
Eric Laurent6acd1d42017-01-04 14:23:29 -08003874 }
3875 }
3876 return volumeInterfaces;
3877}
3878
Glenn Kasteneeecb982016-02-26 10:44:04 -08003879audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880{
Glenn Kasten9d003132016-04-06 14:38:09 -07003881 // This is the internal API, so it is OK to assert on bad parameter.
Glenn Kasteneeecb982016-02-26 10:44:04 -08003882 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
Glenn Kastend2e67e12016-04-11 08:26:37 -07003883 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3884 for (int retry = 0; retry < maxRetries; retry++) {
3885 // The cast allows wraparound from max positive to min negative instead of abort
3886 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3887 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3888 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3889 // allow wrap by skipping 0 and -1 for session ids
3890 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3891 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3892 return (audio_unique_id_t) (base | use);
3893 }
3894 }
3895 // We have no way of recovering from wraparound
3896 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3897 // TODO Use a floor after wraparound. This may need a mutex.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898}
3899
Andy Hung87c693c2023-07-06 20:56:16 -07003900IAfPlaybackThread* AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003901{
Andy Hung954b9712023-08-28 18:36:53 -07003902 audio_utils::lock_guard lock(hardwareMutex());
Eric Laurent00abf0d2020-04-22 19:28:22 -07003903 if (mPrimaryHardwareDev == nullptr) {
3904 return nullptr;
3905 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003906 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003907 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentf6870ae2015-05-08 10:50:03 -07003908 if(thread->isDuplicating()) {
3909 continue;
3910 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07003911 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07003912 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003913 return thread;
3914 }
3915 }
Eric Laurent00abf0d2020-04-22 19:28:22 -07003916 return nullptr;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003917}
3918
jiabinc52b1ff2019-10-31 17:20:42 -07003919DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003920{
Andy Hung87c693c2023-07-06 20:56:16 -07003921 IAfPlaybackThread* const thread = primaryPlaybackThread_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003922
3923 if (thread == NULL) {
Andy Hung920f6572022-10-06 12:09:49 -07003924 return {};
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003925 }
3926
Andy Hungab65b182023-09-06 19:41:47 -07003927 audio_utils::lock_guard l(thread->mutex());
3928 return thread->outDeviceTypes_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003929}
3930
Andy Hung87c693c2023-07-06 20:56:16 -07003931IAfPlaybackThread* AudioFlinger::fastPlaybackThread_l() const
Glenn Kastena7335632016-06-09 17:09:53 -07003932{
3933 size_t minFrameCount = 0;
Andy Hung87c693c2023-07-06 20:56:16 -07003934 IAfPlaybackThread* minThread = nullptr;
Glenn Kastena7335632016-06-09 17:09:53 -07003935 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07003936 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena7335632016-06-09 17:09:53 -07003937 if (!thread->isDuplicating()) {
3938 size_t frameCount = thread->frameCountHAL();
3939 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
3940 (frameCount == minFrameCount && thread->hasFastMixer() &&
3941 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
3942 minFrameCount = frameCount;
3943 minThread = thread;
3944 }
3945 }
3946 }
3947 return minThread;
3948}
3949
Andy Hung87c693c2023-07-06 20:56:16 -07003950IAfThreadBase* AudioFlinger::hapticPlaybackThread_l() const {
jiabineb3bda02020-06-30 14:07:03 -07003951 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
Andy Hung87c693c2023-07-06 20:56:16 -07003952 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
jiabineb3bda02020-06-30 14:07:03 -07003953 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
3954 return thread;
3955 }
3956 }
3957 return nullptr;
3958}
3959
jiabinf042b9b2021-05-07 23:46:28 +00003960void AudioFlinger::updateSecondaryOutputsForTrack_l(
Andy Hungd29af632023-06-23 19:27:19 -07003961 IAfTrack* track,
Andy Hung87c693c2023-07-06 20:56:16 -07003962 IAfPlaybackThread* thread,
jiabinf042b9b2021-05-07 23:46:28 +00003963 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
3964 TeePatches teePatches;
3965 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
Andy Hung87c693c2023-07-06 20:56:16 -07003966 IAfPlaybackThread* const secondaryThread = checkPlaybackThread_l(secondaryOutput);
jiabinf042b9b2021-05-07 23:46:28 +00003967 if (secondaryThread == nullptr) {
3968 ALOGE("no playback thread found for secondary output %d", thread->id());
3969 continue;
3970 }
3971
3972 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
3973 / thread->sampleRate();
3974 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
3975 / secondaryThread->sampleRate();
3976 // If the secondary output has just been opened, the first secondaryThread write
3977 // will not block as it will fill the empty startup buffer of the HAL,
3978 // so a second sink buffer needs to be ready for the immediate next blocking write.
3979 // Additionally, have a margin of one main thread buffer as the scheduling jitter
3980 // can reorder the writes (eg if thread A&B have the same write intervale,
3981 // the scheduler could schedule AB...BA)
3982 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
3983 // Total secondary output buffer must be at least as the read frames plus
3984 // the margin of a few buffers on both sides in case the
3985 // threads scheduling has some jitter.
3986 // That value should not impact latency as the secondary track is started before
3987 // its buffer is full, see frameCountToBeReady.
3988 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
3989 // The frameCount should also not be smaller than the secondary thread min frame
3990 // count
3991 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
Andy Hungc5007f82023-08-29 14:26:09 -07003992 [&] { audio_utils::lock_guard _l(secondaryThread->mutex());
jiabinf042b9b2021-05-07 23:46:28 +00003993 return secondaryThread->latency_l(); }(),
Andy Hung87c693c2023-07-06 20:56:16 -07003994 secondaryThread->frameCount(), // normal frame count
3995 secondaryThread->sampleRate(),
jiabinf042b9b2021-05-07 23:46:28 +00003996 track->sampleRate(),
3997 track->getSpeed());
3998 frameCount = std::max(frameCount, minFrameCount);
3999
4000 using namespace std::chrono_literals;
4001 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
jiabin73e303c2022-09-15 17:49:50 +00004002 if (inChannelMask == AUDIO_CHANNEL_INVALID) {
4003 // The downstream PatchTrack has the proper output channel mask,
4004 // so if there is no input channel mask equivalent, we can just
4005 // use an index mask here to create the PatchRecord.
4006 inChannelMask = audio_channel_mask_out_to_in_index_mask(track->channelMask());
4007 }
Andy Hung8d31fd22023-06-26 19:20:57 -07004008 sp<IAfPatchRecord> patchRecord = IAfPatchRecord::create(nullptr /* thread */,
jiabinf042b9b2021-05-07 23:46:28 +00004009 track->sampleRate(),
4010 inChannelMask,
4011 track->format(),
4012 frameCount,
4013 nullptr /* buffer */,
4014 (size_t)0 /* bufferSize */,
4015 AUDIO_INPUT_FLAG_DIRECT,
4016 0ns /* timeout */);
4017 status_t status = patchRecord->initCheck();
4018 if (status != NO_ERROR) {
4019 ALOGE("Secondary output patchRecord init failed: %d", status);
4020 continue;
4021 }
4022
4023 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
4024 // for fast usage: thread has fast mixer, sample rate matches, etc.;
4025 // for now, we exclude fast tracks by removing the Fast flag.
4026 const audio_output_flags_t outputFlags =
4027 (audio_output_flags_t)(track->getOutputFlags() & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung8d31fd22023-06-26 19:20:57 -07004028 sp<IAfPatchTrack> patchTrack = IAfPatchTrack::create(secondaryThread,
jiabinf042b9b2021-05-07 23:46:28 +00004029 track->streamType(),
4030 track->sampleRate(),
4031 track->channelMask(),
4032 track->format(),
4033 frameCount,
4034 patchRecord->buffer(),
4035 patchRecord->bufferSize(),
4036 outputFlags,
4037 0ns /* timeout */,
4038 frameCountToBeReady);
4039 status = patchTrack->initCheck();
4040 if (status != NO_ERROR) {
4041 ALOGE("Secondary output patchTrack init failed: %d", status);
4042 continue;
4043 }
4044 teePatches.push_back({patchRecord, patchTrack});
4045 secondaryThread->addPatchTrack(patchTrack);
4046 // In case the downstream patchTrack on the secondaryThread temporarily outlives
4047 // our created track, ensure the corresponding patchRecord is still alive.
4048 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
4049 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
4050 }
Andy Hung16ed0da2023-07-14 11:45:38 -07004051 track->setTeePatchesToUpdate_l(std::move(teePatches));
jiabinf042b9b2021-05-07 23:46:28 +00004052}
4053
Andy Hung068e08e2023-05-15 19:02:55 -07004054sp<audioflinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
Glenn Kastend848eb42016-03-08 13:42:11 -08004055 audio_session_t triggerSession,
4056 audio_session_t listenerSession,
Andy Hunga9acac52023-05-22 18:13:40 -07004057 const audioflinger::SyncEventCallback& callBack,
Andy Hungd29af632023-06-23 19:27:19 -07004058 const wp<IAfTrackBase>& cookie)
Eric Laurenta011e352012-03-29 15:51:43 -07004059{
Andy Hung954b9712023-08-28 18:36:53 -07004060 audio_utils::lock_guard _l(mutex());
Eric Laurenta011e352012-03-29 15:51:43 -07004061
Andy Hung068e08e2023-05-15 19:02:55 -07004062 auto event = sp<audioflinger::SyncEvent>::make(
4063 type, triggerSession, listenerSession, callBack, cookie);
Eric Laurenta011e352012-03-29 15:51:43 -07004064 status_t playStatus = NAME_NOT_FOUND;
4065 status_t recStatus = NAME_NOT_FOUND;
4066 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4067 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
4068 if (playStatus == NO_ERROR) {
4069 return event;
4070 }
4071 }
4072 for (size_t i = 0; i < mRecordThreads.size(); i++) {
4073 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
4074 if (recStatus == NO_ERROR) {
4075 return event;
4076 }
4077 }
4078 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
Andy Hung068e08e2023-05-15 19:02:55 -07004079 mPendingSyncEvents.emplace_back(event);
Eric Laurenta011e352012-03-29 15:51:43 -07004080 } else {
4081 ALOGV("createSyncEvent() invalid event %d", event->type());
4082 event.clear();
4083 }
4084 return event;
4085}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004086
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087// ----------------------------------------------------------------------------
4088// Effect management
4089// ----------------------------------------------------------------------------
4090
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004091sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
4092 return mEffectsFactoryHal;
4093}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094
Glenn Kastenf587ba52012-01-26 16:25:10 -08004095status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096{
Andy Hung954b9712023-08-28 18:36:53 -07004097 audio_utils::lock_guard _l(mutex());
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004098 if (mEffectsFactoryHal.get()) {
4099 return mEffectsFactoryHal->queryNumberEffects(numEffects);
4100 } else {
4101 return -ENODEV;
4102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103}
4104
Glenn Kastenf587ba52012-01-26 16:25:10 -08004105status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106{
Andy Hung954b9712023-08-28 18:36:53 -07004107 audio_utils::lock_guard _l(mutex());
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004108 if (mEffectsFactoryHal.get()) {
4109 return mEffectsFactoryHal->getDescriptor(index, descriptor);
4110 } else {
4111 return -ENODEV;
4112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113}
4114
Glenn Kasten5e92a782012-01-30 07:40:52 -08004115status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004116 const effect_uuid_t *pTypeUuid,
4117 uint32_t preferredTypeFlag,
4118 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119{
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004120 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
4121 return BAD_VALUE;
4122 }
4123
Andy Hung954b9712023-08-28 18:36:53 -07004124 audio_utils::lock_guard _l(mutex());
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004125
4126 if (!mEffectsFactoryHal.get()) {
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004127 return -ENODEV;
4128 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004130 status_t status = NO_ERROR;
4131 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
4132 // If uuid is specified, request effect descriptor from that.
4133 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
4134 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
4135 // If uuid is not specified, look for an available implementation
4136 // of the required type instead.
4137
4138 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
4139 effect_descriptor_t desc;
4140 desc.flags = 0; // prevent compiler warning
4141
4142 uint32_t numEffects = 0;
4143 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
4144 if (status < 0) {
4145 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
4146 return status;
4147 }
4148
4149 bool found = false;
4150 for (uint32_t i = 0; i < numEffects; i++) {
4151 status = mEffectsFactoryHal->getDescriptor(i, &desc);
4152 if (status < 0) {
4153 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
4154 continue;
4155 }
4156 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
4157 // If matching type found save effect descriptor.
4158 found = true;
4159 *descriptor = desc;
4160
4161 // If there's no preferred flag or this descriptor matches the preferred
4162 // flag, success! If this descriptor doesn't match the preferred
4163 // flag, continue enumeration in case a better matching version of this
4164 // effect type is available. Note that this means if no effect with a
4165 // correct flag is found, the descriptor returned will correspond to the
4166 // last effect that at least had a matching type uuid (if any).
4167 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
4168 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
4169 break;
4170 }
4171 }
4172 }
4173
4174 if (!found) {
4175 status = NAME_NOT_FOUND;
4176 ALOGW("getEffectDescriptor(): Effect not found by type.");
4177 }
4178 } else {
4179 status = BAD_VALUE;
4180 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
4181 }
4182 return status;
4183}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004185status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
4186 media::CreateEffectResponse* response) {
4187 const sp<IEffectClient>& effectClient = request.client;
4188 const int32_t priority = request.priority;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004189 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004190 aidl2legacy_AudioDeviceTypeAddress(request.device));
Svet Ganov33761132021-05-13 22:51:08 +00004191 AttributionSourceState adjAttributionSource = request.attributionSource;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004192 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004193 aidl2legacy_int32_t_audio_session_t(request.sessionId));
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004194 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
4195 aidl2legacy_int32_t_audio_io_handle_t(request.output));
4196 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004197 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
4198 const bool probe = request.probe;
4199
Andy Hung6ac17eb2023-06-20 18:56:17 -07004200 sp<IAfEffectHandle> handle;
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004201 effect_descriptor_t descOut;
4202 int enabledOut = 0;
4203 int idOut = -1;
4204
4205 status_t lStatus = NO_ERROR;
Atneya Nair07c665d2024-05-17 15:46:48 -07004206 uid_t callingUid;
4207 pid_t currentPid;
4208 if (!com::android::media::audio::audioserver_permissions()) {
4209 callingUid = IPCThreadState::self()->getCallingUid();
4210 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
4211 currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
4212 if (currentPid == -1 || !isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
4213 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
4214 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
4215 "%s uid %d pid %d tried to pass itself off as pid %d",
4216 __func__, callingUid, callingPid, currentPid);
4217 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
4218 legacy2aidl_pid_t_int32_t(callingPid));
4219 currentPid = callingPid;
4220 }
4221 adjAttributionSource = afutils::checkAttributionSourcePackage(adjAttributionSource);
4222 } else {
4223 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
4224 validateAttributionFromContextOrTrustedCaller(request.attributionSource,
4225 getPermissionProvider()
4226 ));
4227 // TODO pass wrapped object around
4228 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
4229 callingUid = adjAttributionSource.uid;
4230 currentPid = adjAttributionSource.pid;
Eric Laurentb6436272016-12-07 19:24:50 -08004231 }
Atneya Nair07c665d2024-05-17 15:46:48 -07004232
Eric Laurentb6436272016-12-07 19:24:50 -08004233
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004234 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
Svet Ganov33761132021-05-13 22:51:08 +00004235 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
4236 mEffectsFactoryHal.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004238 if (mEffectsFactoryHal == 0) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004239 ALOGE("%s: no effects factory hal", __func__);
Mikhail Naganov4a3d5c22016-08-15 13:47:42 -07004240 lStatus = NO_INIT;
4241 goto Exit;
4242 }
4243
Andy Hung6096dcd2019-03-13 13:20:30 -07004244 // check audio settings permission for global effects
4245 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4246 if (!settingsAllowed()) {
4247 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
4248 lStatus = PERMISSION_DENIED;
4249 goto Exit;
4250 }
4251 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung6096dcd2019-03-13 13:20:30 -07004252 if (io == AUDIO_IO_HANDLE_NONE) {
4253 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
4254 lStatus = BAD_VALUE;
4255 goto Exit;
4256 }
Andy Hungc2cf7ec2023-08-30 18:19:00 -07004257 IAfPlaybackThread* thread;
4258 {
4259 audio_utils::lock_guard l(mutex());
4260 thread = checkPlaybackThread_l(io);
4261 }
Eric Laurenta74058e2022-05-26 15:08:00 +00004262 if (thread == nullptr) {
4263 ALOGE("%s: invalid output %d specified for AUDIO_SESSION_OUTPUT_STAGE", __func__, io);
4264 lStatus = BAD_VALUE;
4265 goto Exit;
4266 }
4267 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)
4268 && !isAudioServerUid(callingUid)) {
4269 ALOGE("%s: effect on AUDIO_SESSION_OUTPUT_STAGE not granted for uid %d",
4270 __func__, callingUid);
4271 lStatus = PERMISSION_DENIED;
4272 goto Exit;
4273 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004274 } else if (sessionId == AUDIO_SESSION_DEVICE) {
Svet Ganov33761132021-05-13 22:51:08 +00004275 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004276 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
4277 lStatus = PERMISSION_DENIED;
4278 goto Exit;
4279 }
Eric Laurent94876032019-11-13 12:45:28 -08004280 if (io != AUDIO_IO_HANDLE_NONE) {
4281 ALOGE("%s: io handle should not be specified for device effect", __func__);
4282 lStatus = BAD_VALUE;
4283 goto Exit;
4284 }
Andy Hung6096dcd2019-03-13 13:20:30 -07004285 } else {
4286 // general sessionId.
4287
4288 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
4289 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
4290 lStatus = BAD_VALUE;
4291 goto Exit;
4292 }
4293
4294 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
4295 // to prevent creating an effect when one doesn't actually have track with that session?
4296 }
4297
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 {
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004299 // Get the full effect descriptor from the uuid/type.
4300 // If the session is the output mix, prefer an auxiliary effect,
4301 // otherwise no preference.
4302 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
4303 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004304 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
Ari Hausman-Cohen2046ec72018-04-24 14:00:55 -07004305 if (lStatus < 0) {
4306 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
4307 goto Exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 }
4309
4310 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004311 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004312 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 lStatus = INVALID_OPERATION;
4314 goto Exit;
4315 }
4316
Eric Laurent59255e42011-07-27 19:49:51 -07004317 // check recording permission for visualizer
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004318 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
Svet Ganov6e641372018-03-02 09:21:30 -08004319 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
Svet Ganov33761132021-05-13 22:51:08 +00004320 !recordingAllowed(adjAttributionSource)) {
Eric Laurent59255e42011-07-27 19:49:51 -07004321 lStatus = PERMISSION_DENIED;
4322 goto Exit;
4323 }
4324
Andy Hung6ac17eb2023-06-20 18:56:17 -07004325 const bool hapticPlaybackRequired = IAfEffectModule::isHapticGenerator(&descOut.type);
jiabineb3bda02020-06-30 14:07:03 -07004326 if (hapticPlaybackRequired
4327 && (sessionId == AUDIO_SESSION_DEVICE
4328 || sessionId == AUDIO_SESSION_OUTPUT_MIX
4329 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
4330 // haptic-generating effect is only valid when the session id is a general session id
4331 lStatus = INVALID_OPERATION;
4332 goto Exit;
4333 }
4334
Eric Laurentf690c462021-09-17 14:47:03 +02004335 // Only audio policy service can create a spatializer effect
Eric Laurent4eb45d02023-12-20 12:07:17 +01004336 if (IAfEffectModule::isSpatializer(&descOut.type) &&
Eric Laurentf690c462021-09-17 14:47:03 +02004337 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
4338 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
4339 __func__, callingUid, currentPid);
4340 lStatus = PERMISSION_DENIED;
4341 goto Exit;
4342 }
4343
Glenn Kasten142f5192014-03-25 17:44:59 -07004344 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004345 // if the output returned by getOutputForEffect() is removed before we lock the
4346 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
4347 // and we will exit safely
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004348 io = AudioSystem::getOutputForEffect(&descOut);
Eric Laurenteb3c3372013-09-25 12:25:29 -07004349 ALOGV("createEffect got output %d", io);
4350 }
4351
Andy Hung954b9712023-08-28 18:36:53 -07004352 audio_utils::lock_guard _l(mutex());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353
Eric Laurentb82e6b72019-11-22 17:25:04 -08004354 if (sessionId == AUDIO_SESSION_DEVICE) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004355 sp<Client> client = registerPid(currentPid);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004356 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
Vlad Popa5161f8a2022-10-10 16:17:20 +02004357 handle = mDeviceEffectManager->createEffect_l(
Andy Hungb6692eb2023-07-13 16:52:46 -07004358 &descOut, device, client, effectClient, mPatchPanel->patches_l(),
Eric Laurentde8caf42021-08-11 17:19:25 +02004359 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
Eric Laurentb82e6b72019-11-22 17:25:04 -08004360 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung954b9712023-08-28 18:36:53 -07004361 // remove local strong reference to Client with clientMutex() held
4362 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentb82e6b72019-11-22 17:25:04 -08004363 client.clear();
4364 } else {
4365 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004366 if (handle.get() != nullptr) idOut = handle->id();
Eric Laurentb82e6b72019-11-22 17:25:04 -08004367 }
4368 goto Register;
4369 }
4370
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 // If output is not specified try to find a matching audio session ID in one of the
4372 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004373 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4374 // because of code checking output when entering the function.
Andy Hung444bb552019-03-14 17:06:39 -07004375 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
4376 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
Glenn Kasten142f5192014-03-25 17:44:59 -07004377 if (io == AUDIO_IO_HANDLE_NONE) {
Eric Laurenteb3c3372013-09-25 12:25:29 -07004378 // look for the thread where the specified audio session is present
Andy Hunge778c422019-03-14 15:04:30 -07004379 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
4380 if (io == AUDIO_IO_HANDLE_NONE) {
4381 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08004383 if (io == AUDIO_IO_HANDLE_NONE) {
Andy Hunge778c422019-03-14 15:04:30 -07004384 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
Eric Laurent6acd1d42017-01-04 14:23:29 -08004385 }
Andy Hung444bb552019-03-14 17:06:39 -07004386
4387 // If you wish to create a Record preprocessing AudioEffect in Java,
4388 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
4389 // Otherwise it will fail when created on a Playback thread by legacy
4390 // handling below. Ditto with Mmap, the associated Mmap track must be created
4391 // before creating the AudioEffect or the io handle must be specified.
4392 //
4393 // Detect if the effect is created after an AudioRecord is destroyed.
Shunkai Yao29d10572024-03-19 04:31:47 +00004394 if (sessionId != AUDIO_SESSION_OUTPUT_MIX
4395 && ((descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)
4396 && getOrphanEffectChain_l(sessionId).get() != nullptr) {
Andy Hung444bb552019-03-14 17:06:39 -07004397 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004398 " for session %d no longer exists",
4399 __func__, descOut.name, sessionId);
Andy Hung444bb552019-03-14 17:06:39 -07004400 lStatus = PERMISSION_DENIED;
4401 goto Exit;
4402 }
4403
4404 // Legacy handling of creating an effect on an expired or made-up
4405 // session id. We think that it is a Playback effect.
4406 //
Shunkai Yao29d10572024-03-19 04:31:47 +00004407 // If no output thread contains the requested session ID, park the effect to
4408 // the orphan chains. The effect chain will be moved to the correct output
4409 // thread when a track with the same session ID is created.
4410 if (io == AUDIO_IO_HANDLE_NONE) {
4411 if (probe) {
4412 // In probe mode, as no compatible thread found, exit with error.
4413 lStatus = BAD_VALUE;
4414 goto Exit;
4415 }
4416 ALOGV("%s() got io %d for effect %s", __func__, io, descOut.name);
4417 sp<Client> client = registerPid(currentPid);
4418 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
4419 handle = createOrphanEffect_l(client, effectClient, priority, sessionId,
4420 &descOut, &enabledOut, &lStatus, pinned,
4421 request.notifyFramesProcessed);
4422 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4423 // remove local strong reference to Client with clientMutex() held
4424 audio_utils::lock_guard _cl(clientMutex());
4425 client.clear();
4426 }
4427 goto Register;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004428 }
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004429 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
Eric Laurentb3f315a2021-07-13 15:09:05 +02004430 } else if (checkPlaybackThread_l(io) != nullptr
4431 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
Andy Hung1631f062019-03-12 19:39:03 -07004432 // allow only one effect chain per sessionId on mPlaybackThreads.
4433 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4434 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
jiabineb3bda02020-06-30 14:07:03 -07004435 if (io == checkIo) {
4436 if (hapticPlaybackRequired
4437 && mPlaybackThreads.valueAt(i)
4438 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4439 ALOGE("%s: haptic playback thread is required while the required playback "
4440 "thread(io=%d) doesn't support", __func__, (int)io);
4441 lStatus = BAD_VALUE;
4442 goto Exit;
4443 }
4444 continue;
4445 }
Andy Hung1631f062019-03-12 19:39:03 -07004446 const uint32_t sessionType =
4447 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07004448 if ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0) {
Andy Hung1631f062019-03-12 19:39:03 -07004449 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004450 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
Andy Hung1631f062019-03-12 19:39:03 -07004451 android_errorWriteLog(0x534e4554, "123237974");
4452 lStatus = BAD_VALUE;
4453 goto Exit;
4454 }
4455 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004456 }
Andy Hung87c693c2023-07-06 20:56:16 -07004457 IAfThreadBase* thread = checkRecordThread_l(io);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004458 if (thread == NULL) {
4459 thread = checkPlaybackThread_l(io);
4460 if (thread == NULL) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08004461 thread = checkMmapThread_l(io);
4462 if (thread == NULL) {
4463 ALOGE("createEffect() unknown output thread");
4464 lStatus = BAD_VALUE;
4465 goto Exit;
4466 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004467 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004468 }
4469 if (thread->type() == IAfThreadBase::RECORD || sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentaaa44472014-09-12 17:41:50 -07004470 // Check if one effect chain was awaiting for an effect to be created on this
4471 // session and used it instead of creating a new one.
Andy Hung6ac17eb2023-06-20 18:56:17 -07004472 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
Eric Laurentaaa44472014-09-12 17:41:50 -07004473 if (chain != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -07004474 audio_utils::lock_guard _l2(thread->mutex());
Eric Laurentaaa44472014-09-12 17:41:50 -07004475 thread->addEffectChain_l(chain);
4476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004478
Philip P. Moltmannbda45752020-07-17 16:41:18 -07004479 sp<Client> client = registerPid(currentPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480
Marco Nelissen3a34bef2011-08-02 13:33:41 -07004481 // create effect on selected output thread
Eric Laurent3f75a5b2019-11-12 15:55:51 -08004482 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
Andy Hung87c693c2023-07-06 20:56:16 -07004483 IAfThreadBase* oriThread = nullptr;
jiabineb3bda02020-06-30 14:07:03 -07004484 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
Andy Hung87c693c2023-07-06 20:56:16 -07004485 IAfThreadBase* const hapticThread = hapticPlaybackThread_l();
jiabineb3bda02020-06-30 14:07:03 -07004486 if (hapticThread == nullptr) {
4487 ALOGE("%s haptic thread not found while it is required", __func__);
4488 lStatus = INVALID_OPERATION;
4489 goto Exit;
4490 }
4491 if (hapticThread != thread) {
4492 // Force to use haptic thread for haptic-generating effect.
4493 oriThread = thread;
4494 thread = hapticThread;
4495 }
4496 }
Eric Laurentde070132010-07-13 04:45:46 -07004497 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
Eric Laurentde8caf42021-08-11 17:19:25 +02004498 &descOut, &enabledOut, &lStatus, pinned, probe,
4499 request.notifyFramesProcessed);
haobo101735295ff7b0d2017-03-17 17:44:03 +08004500 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung954b9712023-08-28 18:36:53 -07004501 // remove local strong reference to Client with clientMutex() held
4502 audio_utils::lock_guard _cl(clientMutex());
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004503 client.clear();
haobo101735295ff7b0d2017-03-17 17:44:03 +08004504 } else {
4505 // handle must be valid here, but check again to be safe.
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004506 if (handle.get() != nullptr) idOut = handle->id();
jiabineb3bda02020-06-30 14:07:03 -07004507 // Invalidate audio session when haptic playback is created.
4508 if (hapticPlaybackRequired && oriThread != nullptr) {
4509 // invalidateTracksForAudioSession will trigger locking the thread.
4510 oriThread->invalidateTracksForAudioSession(sessionId);
4511 }
Eric Laurentfe1a94e2014-05-26 16:03:08 -07004512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513 }
4514
Eric Laurentb82e6b72019-11-22 17:25:04 -08004515Register:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07004516 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
Eric Laurent4f1d4e92022-02-01 14:37:16 +01004517 if (lStatus == ALREADY_EXISTS) {
4518 response->alreadyExists = true;
4519 lStatus = NO_ERROR;
4520 } else {
4521 response->alreadyExists = false;
4522 }
Eric Laurent6c796322019-04-09 14:13:17 -07004523 // Check CPU and memory usage
Andy Hung6ac17eb2023-06-20 18:56:17 -07004524 sp<IAfEffectBase> effect = handle->effect().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004525 if (effect != nullptr) {
4526 status_t rStatus = effect->updatePolicyState();
4527 if (rStatus != NO_ERROR) {
4528 lStatus = rStatus;
4529 }
4530 }
4531 } else {
haobo101735295ff7b0d2017-03-17 17:44:03 +08004532 handle.clear();
4533 }
4534
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004535 response->id = idOut;
4536 response->enabled = enabledOut != 0;
Shunkai Yao8ade2572023-07-28 00:55:00 +00004537 response->effect = handle.get() ? handle->asIEffect() : nullptr;
Ytai Ben-Tsvi12a0b842020-11-05 13:47:32 -08004538 response->desc = VALUE_OR_RETURN_STATUS(
4539 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004540
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541Exit:
Ytai Ben-Tsvice182942020-11-04 14:48:01 -08004542 return lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543}
4544
Shunkai Yao29d10572024-03-19 04:31:47 +00004545sp<IAfEffectHandle> AudioFlinger::createOrphanEffect_l(
4546 const sp<Client>& client,
4547 const sp<IEffectClient>& effectClient,
4548 int32_t priority,
4549 audio_session_t sessionId,
4550 effect_descriptor_t *desc,
4551 int *enabled,
4552 status_t *status,
4553 bool pinned,
4554 bool notifyFramesProcessed)
4555{
4556 ALOGV("%s effectClient %p, priority %d, sessionId %d, factory %p",
4557 __func__, effectClient.get(), priority, sessionId, mEffectsFactoryHal.get());
4558
4559 // Check if an orphan effect chain exists for this session or create new chain for this session
4560 sp<IAfEffectModule> effect;
4561 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
4562 bool chainCreated = false;
4563 if (chain == nullptr) {
4564 chain = IAfEffectChain::create(/* ThreadBase= */ nullptr, sessionId, this);
4565 chainCreated = true;
4566 } else {
4567 effect = chain->getEffectFromDesc(desc);
4568 }
4569 bool effectCreated = false;
4570 if (effect == nullptr) {
4571 audio_unique_id_t effectId = nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
4572 // create a new effect module if none present in the chain
4573 status_t llStatus =
4574 chain->createEffect(effect, desc, effectId, sessionId, pinned);
4575 if (llStatus != NO_ERROR) {
4576 *status = llStatus;
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004577 // if the effect chain was not created here, put it back
4578 if (!chainCreated) {
4579 putOrphanEffectChain_l(chain);
4580 }
Shunkai Yao29d10572024-03-19 04:31:47 +00004581 return nullptr;
4582 }
4583 effect->setMode(getMode());
4584
4585 if (effect->isHapticGenerator()) {
4586 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
4587 // for the HapticGenerator.
4588 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
4589 std::move(getDefaultVibratorInfo_l());
4590 if (defaultVibratorInfo) {
4591 // Only set the vibrator info when it is a valid one.
4592 audio_utils::lock_guard _cl(chain->mutex());
4593 effect->setVibratorInfo_l(*defaultVibratorInfo);
4594 }
4595 }
4596 effectCreated = true;
4597 }
4598 // create effect handle and connect it to effect module
4599 sp<IAfEffectHandle> handle =
4600 IAfEffectHandle::create(effect, client, effectClient, priority, notifyFramesProcessed);
4601 status_t lStatus = handle->initCheck();
4602 if (lStatus == OK) {
4603 lStatus = effect->addHandle(handle.get());
4604 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004605 // in case of lStatus error, EffectHandle will still return and caller should do the clear
Shunkai Yao29d10572024-03-19 04:31:47 +00004606 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4607 if (effectCreated) {
4608 chain->removeEffect(effect);
4609 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004610 // if the effect chain was not created here, put it back
4611 if (!chainCreated) {
4612 putOrphanEffectChain_l(chain);
4613 }
Shunkai Yao29d10572024-03-19 04:31:47 +00004614 } else {
4615 if (enabled != NULL) {
4616 *enabled = (int)effect->isEnabled();
4617 }
Shunkai Yao7eb61b82024-03-21 23:17:38 +00004618 putOrphanEffectChain_l(chain);
Shunkai Yao29d10572024-03-19 04:31:47 +00004619 }
4620 *status = lStatus;
4621 return handle;
4622}
4623
François Gaffie1b4753e2023-02-06 10:36:33 +01004624status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcIo,
4625 audio_io_handle_t dstIo)
4626NO_THREAD_SAFETY_ANALYSIS
Eric Laurentde070132010-07-13 04:45:46 -07004627{
François Gaffie1b4753e2023-02-06 10:36:33 +01004628 ALOGV("%s() session %d, srcIo %d, dstIo %d", __func__, sessionId, srcIo, dstIo);
Andy Hung954b9712023-08-28 18:36:53 -07004629 audio_utils::lock_guard _l(mutex());
François Gaffie1b4753e2023-02-06 10:36:33 +01004630 if (srcIo == dstIo) {
4631 ALOGW("%s() same dst and src outputs %d", __func__, dstIo);
Eric Laurentde070132010-07-13 04:45:46 -07004632 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 }
Andy Hung87c693c2023-07-06 20:56:16 -07004634 IAfRecordThread* const srcRecordThread = checkRecordThread_l(srcIo);
4635 IAfRecordThread* const dstRecordThread = checkRecordThread_l(dstIo);
François Gaffie1b4753e2023-02-06 10:36:33 +01004636 if (srcRecordThread != nullptr || dstRecordThread != nullptr) {
4637 if (srcRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004638 srcRecordThread->mutex().lock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004639 }
4640 if (dstRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004641 dstRecordThread->mutex().lock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004642 }
Andy Hung972bec12023-08-31 16:13:39 -07004643 status_t ret = moveEffectChain_ll(sessionId, srcRecordThread, dstRecordThread);
François Gaffie1b4753e2023-02-06 10:36:33 +01004644 if (srcRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004645 srcRecordThread->mutex().unlock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004646 }
4647 if (dstRecordThread != nullptr) {
Andy Hung87c693c2023-07-06 20:56:16 -07004648 dstRecordThread->mutex().unlock();
François Gaffie1b4753e2023-02-06 10:36:33 +01004649 }
4650 return ret;
4651 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004652
4653 IAfPlaybackThread* dstThread = checkPlaybackThread_l(dstIo);
François Gaffie1b4753e2023-02-06 10:36:33 +01004654 if (dstThread == nullptr) {
4655 ALOGW("%s() bad dstIo %d", __func__, dstIo);
Eric Laurentde070132010-07-13 04:45:46 -07004656 return BAD_VALUE;
4657 }
4658
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004659 IAfPlaybackThread* srcThread = checkPlaybackThread_l(srcIo);
4660 sp<IAfEffectChain> orphanChain = getOrphanEffectChain_l(sessionId);
4661 if (srcThread == nullptr && orphanChain == nullptr && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4662 ALOGW("%s() AUDIO_SESSION_OUTPUT_MIX not found in orphans, checking other mix", __func__);
4663 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4664 const sp<IAfPlaybackThread> pt = mPlaybackThreads.valueAt(i);
4665 const uint32_t sessionType = pt->hasAudioSession(AUDIO_SESSION_OUTPUT_MIX);
4666 if ((pt->type() == IAfThreadBase::MIXER || pt->type() == IAfThreadBase::OFFLOAD) &&
4667 ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0)) {
4668 srcThread = pt.get();
4669 ALOGW("%s() found srcOutput %d hosting AUDIO_SESSION_OUTPUT_MIX", __func__,
4670 pt->id());
4671 break;
4672 }
4673 }
4674 }
4675 if (srcThread == nullptr && orphanChain == nullptr) {
4676 ALOGW("moveEffects() bad srcIo %d", srcIo);
4677 return BAD_VALUE;
4678 }
4679 // dstThread pointer validity has already been checked
4680 if (orphanChain != nullptr) {
4681 audio_utils::scoped_lock _ll(dstThread->mutex());
4682 return moveEffectChain_ll(sessionId, nullptr, dstThread, orphanChain.get());
4683 }
4684 // srcThread pointer validity has already been checked
Andy Hunge0f5ec52023-08-30 11:26:06 -07004685 audio_utils::scoped_lock _ll(dstThread->mutex(), srcThread->mutex());
Andy Hung972bec12023-08-31 16:13:39 -07004686 return moveEffectChain_ll(sessionId, srcThread, dstThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004687}
4688
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004689
4690void AudioFlinger::setEffectSuspended(int effectId,
4691 audio_session_t sessionId,
4692 bool suspended)
4693{
Andy Hung954b9712023-08-28 18:36:53 -07004694 audio_utils::lock_guard _l(mutex());
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004695
Andy Hung87c693c2023-07-06 20:56:16 -07004696 sp<IAfThreadBase> thread = getEffectThread_l(sessionId, effectId);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004697 if (thread == nullptr) {
Shunkai Yao8da94182024-02-14 02:49:47 +00004698 return;
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004699 }
Andy Hungc5007f82023-08-29 14:26:09 -07004700 audio_utils::lock_guard _sl(thread->mutex());
Shunkai Yao8da94182024-02-14 02:49:47 +00004701 if (const auto& effect = thread->getEffect_l(sessionId, effectId)) {
4702 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4703 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004704}
4705
4706
Andy Hung972bec12023-08-31 16:13:39 -07004707// moveEffectChain_ll must be called with the AudioFlinger::mutex()
4708// and both srcThread and dstThread mutex()s held
4709status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004710 IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread,
4711 IAfEffectChain* srcChain)
Eric Laurentde070132010-07-13 04:45:46 -07004712{
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004713 ALOGV("%s: session %d from thread %p to thread %p %s",
4714 __func__, sessionId, srcThread, dstThread,
4715 (srcChain != nullptr ? "from specific chain" : ""));
4716 ALOG_ASSERT((srcThread != nullptr) != (srcChain != nullptr),
4717 "no source provided for source chain");
Eric Laurentde070132010-07-13 04:45:46 -07004718
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004719 sp<IAfEffectChain> chain =
4720 srcChain != nullptr ? srcChain : srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07004721 if (chain == 0) {
Andy Hung972bec12023-08-31 16:13:39 -07004722 ALOGW("%s: effect chain for session %d not on source thread %p",
4723 __func__, sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07004724 return INVALID_OPERATION;
4725 }
4726
Eric Laurent4c415062016-06-17 16:14:16 -07004727 // Check whether the destination thread and all effects in the chain are compatible
4728 if (!chain->isCompatibleWithThread_l(dstThread)) {
Andy Hung972bec12023-08-31 16:13:39 -07004729 ALOGW("%s: effect chain failed because"
Eric Laurent4c415062016-06-17 16:14:16 -07004730 " destination thread %p is not compatible with effects in the chain",
Andy Hung972bec12023-08-31 16:13:39 -07004731 __func__, dstThread);
Andy Hung9a592762014-07-21 21:56:01 -07004732 return INVALID_OPERATION;
4733 }
4734
Eric Laurent39e94f82010-07-28 01:32:47 -07004735 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004736 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07004737 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07004738 // removed.
Andy Hung180f49a2022-01-27 10:25:02 -08004739 // TODO(b/216875016): consider holding the effect chain locks for the duration of the move.
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004740 if (srcThread != nullptr) {
4741 srcThread->removeEffectChain_l(chain);
4742 }
Eric Laurentde070132010-07-13 04:45:46 -07004743 // transfer all effects one by one so that new effect chain is created on new thread with
4744 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Andy Hung6ac17eb2023-06-20 18:56:17 -07004745 sp<IAfEffectChain> dstChain;
4746 Vector<sp<IAfEffectModule>> removed;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004747 status_t status = NO_ERROR;
Andy Hung03410c02022-01-27 08:24:31 -08004748 std::string errorString;
Andy Hung920f6572022-10-06 12:09:49 -07004749 // process effects one by one.
Andy Hung6ac17eb2023-06-20 18:56:17 -07004750 for (sp<IAfEffectModule> effect = chain->getEffectFromId_l(0); effect != nullptr;
Andy Hung920f6572022-10-06 12:09:49 -07004751 effect = chain->getEffectFromId_l(0)) {
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004752 if (srcThread != nullptr) {
4753 srcThread->removeEffect_l(effect);
4754 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00004755 chain->removeEffect(effect);
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004756 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004757 removed.add(effect);
Andy Hung972bec12023-08-31 16:13:39 -07004758 status = dstThread->addEffect_ll(effect);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004759 if (status != NO_ERROR) {
Andy Hung03410c02022-01-27 08:24:31 -08004760 errorString = StringPrintf(
4761 "cannot add effect %p to destination thread", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004762 break;
4763 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004764 // if the move request is not received from audio policy manager, the effect must be
Andy Hung180f49a2022-01-27 10:25:02 -08004765 // re-registered with the new strategy and output.
4766
4767 // We obtain the dstChain once the effect is on the new thread.
4768 if (dstChain == nullptr) {
Andy Hungfda44002021-06-03 17:23:16 -07004769 dstChain = effect->getCallback()->chain().promote();
Andy Hung180f49a2022-01-27 10:25:02 -08004770 if (dstChain == nullptr) {
Andy Hung03410c02022-01-27 08:24:31 -08004771 errorString = StringPrintf("cannot get chain from effect %p", effect.get());
Eric Laurent5baf2af2013-09-12 17:37:00 -07004772 status = NO_INIT;
4773 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004774 }
Eric Laurent39e94f82010-07-28 01:32:47 -07004775 }
Eric Laurentde070132010-07-13 04:45:46 -07004776 }
4777
Andy Hung03410c02022-01-27 08:24:31 -08004778 size_t restored = 0;
Eric Laurent5baf2af2013-09-12 17:37:00 -07004779 if (status != NO_ERROR) {
Andy Hung180f49a2022-01-27 10:25:02 -08004780 dstChain.clear(); // dstChain is now from the srcThread (could be recreated).
Andy Hung03410c02022-01-27 08:24:31 -08004781 for (const auto& effect : removed) {
Andy Hung5c4dd0d2022-01-27 10:21:59 -08004782 dstThread->removeEffect_l(effect); // Note: Depending on error location, the last
4783 // effect may not have been placed on dstThread.
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004784 if (srcThread != nullptr && srcThread->addEffect_ll(effect) == NO_ERROR) {
Andy Hung03410c02022-01-27 08:24:31 -08004785 ++restored;
Andy Hung180f49a2022-01-27 10:25:02 -08004786 if (dstChain == nullptr) {
4787 dstChain = effect->getCallback()->chain().promote();
4788 }
Andy Hung03410c02022-01-27 08:24:31 -08004789 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004790 }
4791 }
4792
Andy Hung180f49a2022-01-27 10:25:02 -08004793 // After all the effects have been moved to new thread (or put back) we restart the effects
4794 // because removeEffect_l() has stopped the effect if it is currently active.
4795 size_t started = 0;
4796 if (dstChain != nullptr && !removed.empty()) {
4797 // If we do not take the dstChain lock, it is possible that processing is ongoing
4798 // while we are starting the effect. This can cause glitches with volume,
4799 // see b/202360137.
Andy Hungf65f5a72023-08-29 12:19:17 -07004800 dstChain->mutex().lock();
Andy Hung180f49a2022-01-27 10:25:02 -08004801 for (const auto& effect : removed) {
Andy Hung6ac17eb2023-06-20 18:56:17 -07004802 if (effect->state() == IAfEffectModule::ACTIVE ||
4803 effect->state() == IAfEffectModule::STOPPING) {
Andy Hung180f49a2022-01-27 10:25:02 -08004804 ++started;
Shunkai Yaod125e402024-01-20 03:19:06 +00004805 effect->start_l();
Andy Hung180f49a2022-01-27 10:25:02 -08004806 }
4807 }
Andy Hungf65f5a72023-08-29 12:19:17 -07004808 dstChain->mutex().unlock();
Andy Hung180f49a2022-01-27 10:25:02 -08004809 }
4810
Andy Hung03410c02022-01-27 08:24:31 -08004811 if (status != NO_ERROR) {
4812 if (errorString.empty()) {
4813 errorString = StringPrintf("%s: failed status %d", __func__, status);
4814 }
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004815 ALOGW("%s: %s unsuccessful move of session %d from %s %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004816 "(%zu effects removed from srcThread, %zu effects restored to srcThread, "
4817 "%zu effects started)",
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004818 __func__, errorString.c_str(), sessionId,
4819 (srcThread != nullptr ? "srcThread" : "srcChain"),
4820 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
Andy Hung180f49a2022-01-27 10:25:02 -08004821 removed.size(), restored, started);
Andy Hung03410c02022-01-27 08:24:31 -08004822 } else {
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004823 ALOGD("%s: successful move of session %d from %s %p to dstThread %p "
Andy Hung180f49a2022-01-27 10:25:02 -08004824 "(%zu effects moved, %zu effects started)",
Shunkai Yao517fc2a2024-03-19 04:31:47 +00004825 __func__, sessionId, (srcThread != nullptr ? "srcThread" : "srcChain"),
4826 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
4827 removed.size(), started);
Andy Hung03410c02022-01-27 08:24:31 -08004828 }
Eric Laurent5baf2af2013-09-12 17:37:00 -07004829 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830}
4831
François Gaffie1b4753e2023-02-06 10:36:33 +01004832
Andy Hung972bec12023-08-31 16:13:39 -07004833// moveEffectChain_ll must be called with both srcThread (if not null) and dstThread (if not null)
Andy Hung954b9712023-08-28 18:36:53 -07004834// mutex()s held
Andy Hung972bec12023-08-31 16:13:39 -07004835status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
Andy Hung87c693c2023-07-06 20:56:16 -07004836 IAfRecordThread* srcThread, IAfRecordThread* dstThread)
François Gaffie1b4753e2023-02-06 10:36:33 +01004837{
4838 sp<IAfEffectChain> chain = nullptr;
4839 if (srcThread != 0) {
Andy Hung87c693c2023-07-06 20:56:16 -07004840 const Vector<sp<IAfEffectChain>> effectChains = srcThread->getEffectChains_l();
François Gaffie1b4753e2023-02-06 10:36:33 +01004841 for (size_t i = 0; i < effectChains.size(); i ++) {
4842 if (effectChains[i]->sessionId() == sessionId) {
4843 chain = effectChains[i];
4844 break;
4845 }
4846 }
4847 ALOGV_IF(effectChains.size() == 0, "%s: no effect chain on io=%d", __func__,
4848 srcThread->id());
4849 if (chain == nullptr) {
4850 ALOGE("%s wrong session id %d", __func__, sessionId);
4851 return BAD_VALUE;
4852 }
4853 ALOGV("%s: removing effect chain for session=%d io=%d", __func__, sessionId,
4854 srcThread->id());
4855 srcThread->removeEffectChain_l(chain);
4856 } else {
4857 chain = getOrphanEffectChain_l(sessionId);
4858 if (chain == nullptr) {
4859 ALOGE("%s: no orphan effect chain found for session=%d", __func__, sessionId);
4860 return BAD_VALUE;
4861 }
4862 }
4863 if (dstThread != 0) {
4864 ALOGV("%s: adding effect chain for session=%d on io=%d", __func__, sessionId,
4865 dstThread->id());
4866 dstThread->addEffectChain_l(chain);
4867 return NO_ERROR;
4868 }
4869 ALOGV("%s: parking to orphan effect chain for session=%d", __func__, sessionId);
4870 putOrphanEffectChain_l(chain);
4871 return NO_ERROR;
4872}
4873
Eric Laurent6c796322019-04-09 14:13:17 -07004874status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
Andy Hung87c693c2023-07-06 20:56:16 -07004875 const sp<IAfPlaybackThread>& dstThread, sp<IAfPlaybackThread>* srcThread)
Eric Laurent6c796322019-04-09 14:13:17 -07004876{
4877 status_t status = NO_ERROR;
Andy Hung954b9712023-08-28 18:36:53 -07004878 audio_utils::lock_guard _l(mutex());
Andy Hung87c693c2023-07-06 20:56:16 -07004879 const sp<IAfThreadBase> threadBase = getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4880 const sp<IAfPlaybackThread> thread = threadBase ? threadBase->asIAfPlaybackThread() : nullptr;
Eric Laurent6c796322019-04-09 14:13:17 -07004881
4882 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
Andy Hunge0f5ec52023-08-30 11:26:06 -07004883 audio_utils::scoped_lock _ll(dstThread->mutex(), thread->mutex());
Andy Hung6ac17eb2023-06-20 18:56:17 -07004884 sp<IAfEffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4885 sp<IAfEffectChain> dstChain;
Eric Laurent6c796322019-04-09 14:13:17 -07004886 if (srcChain == 0) {
4887 return INVALID_OPERATION;
4888 }
4889
Andy Hung6ac17eb2023-06-20 18:56:17 -07004890 sp<IAfEffectModule> effect = srcChain->getEffectFromId_l(EffectId);
Eric Laurent6c796322019-04-09 14:13:17 -07004891 if (effect == 0) {
4892 return INVALID_OPERATION;
4893 }
4894 thread->removeEffect_l(effect);
Andy Hung972bec12023-08-31 16:13:39 -07004895 status = dstThread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004896 if (status != NO_ERROR) {
Andy Hung972bec12023-08-31 16:13:39 -07004897 thread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004898 status = INVALID_OPERATION;
4899 goto Exit;
4900 }
4901
Andy Hungfda44002021-06-03 17:23:16 -07004902 dstChain = effect->getCallback()->chain().promote();
Eric Laurent6c796322019-04-09 14:13:17 -07004903 if (dstChain == 0) {
Andy Hung972bec12023-08-31 16:13:39 -07004904 thread->addEffect_ll(effect);
Eric Laurent6c796322019-04-09 14:13:17 -07004905 status = INVALID_OPERATION;
4906 }
4907
4908Exit:
4909 // removeEffect_l() has stopped the effect if it was active so it must be restarted
Andy Hung6ac17eb2023-06-20 18:56:17 -07004910 if (effect->state() == IAfEffectModule::ACTIVE ||
4911 effect->state() == IAfEffectModule::STOPPING) {
Shunkai Yaod125e402024-01-20 03:19:06 +00004912 effect->start_l();
Eric Laurent6c796322019-04-09 14:13:17 -07004913 }
4914 }
4915
4916 if (status == NO_ERROR && srcThread != nullptr) {
4917 *srcThread = thread;
4918 }
4919 return status;
4920}
4921
Andy Hung583043b2023-07-17 17:05:00 -07004922bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() const
Eric Laurent813e2a72013-08-31 12:59:48 -07004923{
4924 if (mGlobalEffectEnableTime != 0 &&
4925 ((systemTime() - mGlobalEffectEnableTime) < kMinGlobalEffectEnabletimeNs)) {
4926 return true;
4927 }
4928
4929 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hungab65b182023-09-06 19:41:47 -07004930 const auto thread = mPlaybackThreads.valueAt(i);
4931 audio_utils::lock_guard l(thread->mutex());
4932 const sp<IAfEffectChain> ec = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent5baf2af2013-09-12 17:37:00 -07004933 if (ec != 0 && ec->isNonOffloadableEnabled()) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004934 return true;
4935 }
4936 }
4937 return false;
4938}
4939
Eric Laurent5baf2af2013-09-12 17:37:00 -07004940void AudioFlinger::onNonOffloadableGlobalEffectEnable()
Eric Laurent813e2a72013-08-31 12:59:48 -07004941{
Andy Hung954b9712023-08-28 18:36:53 -07004942 audio_utils::lock_guard _l(mutex());
Eric Laurent813e2a72013-08-31 12:59:48 -07004943
4944 mGlobalEffectEnableTime = systemTime();
4945
4946 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07004947 const sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
4948 if (t->type() == IAfThreadBase::OFFLOAD) {
Eric Laurent813e2a72013-08-31 12:59:48 -07004949 t->invalidateTracks(AUDIO_STREAM_MUSIC);
4950 }
4951 }
4952
4953}
4954
Andy Hung6ac17eb2023-06-20 18:56:17 -07004955status_t AudioFlinger::putOrphanEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurentaaa44472014-09-12 17:41:50 -07004956{
Eric Laurentd8365c52017-07-16 15:27:05 -07004957 // clear possible suspended state before parking the chain so that it starts in default state
4958 // when attached to a new record thread
4959 chain->setEffectSuspended_l(FX_IID_AEC, false);
4960 chain->setEffectSuspended_l(FX_IID_NS, false);
4961
Glenn Kastend848eb42016-03-08 13:42:11 -08004962 audio_session_t session = chain->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004963 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004964 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004965 if (index >= 0) {
4966 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
4967 return ALREADY_EXISTS;
4968 }
4969 mOrphanEffectChains.add(session, chain);
4970 return NO_ERROR;
4971}
4972
Andy Hung6ac17eb2023-06-20 18:56:17 -07004973sp<IAfEffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
Eric Laurentaaa44472014-09-12 17:41:50 -07004974{
Andy Hung6ac17eb2023-06-20 18:56:17 -07004975 sp<IAfEffectChain> chain;
Eric Laurentaaa44472014-09-12 17:41:50 -07004976 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004977 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004978 if (index >= 0) {
4979 chain = mOrphanEffectChains.valueAt(index);
4980 mOrphanEffectChains.removeItemsAt(index);
4981 }
4982 return chain;
4983}
4984
Andy Hung6ac17eb2023-06-20 18:56:17 -07004985bool AudioFlinger::updateOrphanEffectChains(const sp<IAfEffectModule>& effect)
Eric Laurentaaa44472014-09-12 17:41:50 -07004986{
Andy Hung954b9712023-08-28 18:36:53 -07004987 audio_utils::lock_guard _l(mutex());
François Gaffie1b4753e2023-02-06 10:36:33 +01004988 return updateOrphanEffectChains_l(effect);
4989}
4990
4991bool AudioFlinger::updateOrphanEffectChains_l(const sp<IAfEffectModule>& effect)
4992{
Glenn Kastend848eb42016-03-08 13:42:11 -08004993 audio_session_t session = effect->sessionId();
Eric Laurentaaa44472014-09-12 17:41:50 -07004994 ssize_t index = mOrphanEffectChains.indexOfKey(session);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004995 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
Eric Laurentaaa44472014-09-12 17:41:50 -07004996 if (index >= 0) {
Andy Hung6ac17eb2023-06-20 18:56:17 -07004997 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
Shunkai Yao29d10572024-03-19 04:31:47 +00004998 if (chain->removeEffect(effect, true) == 0) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004999 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
Eric Laurentaaa44472014-09-12 17:41:50 -07005000 mOrphanEffectChains.removeItemsAt(index);
5001 }
5002 return true;
5003 }
5004 return false;
5005}
5006
Andy Hung00b9aea2023-07-18 18:43:08 -07005007// ----------------------------------------------------------------------------
5008// from PatchPanel
5009
5010/* List connected audio ports and their attributes */
5011status_t AudioFlinger::listAudioPorts(unsigned int* num_ports,
5012 struct audio_port* ports) const
5013{
Andy Hung954b9712023-08-28 18:36:53 -07005014 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005015 return mPatchPanel->listAudioPorts_l(num_ports, ports);
Andy Hung00b9aea2023-07-18 18:43:08 -07005016}
5017
5018/* Get supported attributes for a given audio port */
5019status_t AudioFlinger::getAudioPort(struct audio_port_v7* port) const {
5020 const status_t status = AudioValidator::validateAudioPort(*port);
5021 if (status != NO_ERROR) {
5022 return status;
5023 }
5024
Andy Hung954b9712023-08-28 18:36:53 -07005025 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005026 return mPatchPanel->getAudioPort_l(port);
Andy Hung00b9aea2023-07-18 18:43:08 -07005027}
5028
5029/* Connect a patch between several source and sink ports */
5030status_t AudioFlinger::createAudioPatch(
5031 const struct audio_patch* patch, audio_patch_handle_t* handle)
5032{
5033 const status_t status = AudioValidator::validateAudioPatch(*patch);
5034 if (status != NO_ERROR) {
5035 return status;
5036 }
5037
Andy Hung954b9712023-08-28 18:36:53 -07005038 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005039 return mPatchPanel->createAudioPatch_l(patch, handle);
Andy Hung00b9aea2023-07-18 18:43:08 -07005040}
5041
5042/* Disconnect a patch */
5043status_t AudioFlinger::releaseAudioPatch(audio_patch_handle_t handle)
5044{
Andy Hung954b9712023-08-28 18:36:53 -07005045 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005046 return mPatchPanel->releaseAudioPatch_l(handle);
Andy Hung00b9aea2023-07-18 18:43:08 -07005047}
5048
5049/* List connected audio ports and they attributes */
5050status_t AudioFlinger::listAudioPatches(
5051 unsigned int* num_patches, struct audio_patch* patches) const
5052{
Andy Hung954b9712023-08-28 18:36:53 -07005053 audio_utils::lock_guard _l(mutex());
Andy Hung37006372023-08-31 15:24:24 -07005054 return mPatchPanel->listAudioPatches_l(num_patches, patches);
Andy Hung00b9aea2023-07-18 18:43:08 -07005055}
Eric Laurentaaa44472014-09-12 17:41:50 -07005056
jiabin12537fc2023-10-12 17:56:08 +00005057/**
5058 * Get the attributes of the mix port when connecting to the given device port.
5059 */
5060status_t AudioFlinger::getAudioMixPort(const struct audio_port_v7 *devicePort,
5061 struct audio_port_v7 *mixPort) const {
5062 if (status_t status = AudioValidator::validateAudioPort(*devicePort); status != NO_ERROR) {
5063 ALOGE("%s, invalid device port, status=%d", __func__, status);
5064 return status;
5065 }
5066 if (status_t status = AudioValidator::validateAudioPort(*mixPort); status != NO_ERROR) {
5067 ALOGE("%s, invalid mix port, status=%d", __func__, status);
5068 return status;
5069 }
5070
5071 audio_utils::lock_guard _l(mutex());
5072 return mPatchPanel->getAudioMixPort_l(devicePort, mixPort);
5073}
5074
jiabin220eea12024-05-17 17:55:20 +00005075status_t AudioFlinger::setTracksInternalMute(
5076 const std::vector<media::TrackInternalMuteInfo>& tracksInternalMute) {
5077 audio_utils::lock_guard _l(mutex());
5078 ALOGV("%s", __func__);
5079
5080 std::map<audio_port_handle_t, bool> tracksInternalMuteMap;
5081 for (const auto& trackInternalMute : tracksInternalMute) {
5082 audio_port_handle_t portId = VALUE_OR_RETURN_STATUS(
5083 aidl2legacy_int32_t_audio_port_handle_t(trackInternalMute.portId));
5084 tracksInternalMuteMap.emplace(portId, trackInternalMute.muted);
5085 }
5086 for (size_t i = 0; i < mPlaybackThreads.size() && !tracksInternalMuteMap.empty(); i++) {
5087 mPlaybackThreads.valueAt(i)->setTracksInternalMute(&tracksInternalMuteMap);
5088 }
5089 return NO_ERROR;
5090}
5091
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092// ----------------------------------------------------------------------------
5093
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005094status_t AudioFlinger::onTransactWrapper(TransactionCode code,
Jing Mike537412f2023-03-12 11:01:47 +08005095 [[maybe_unused]] const Parcel& data,
5096 [[maybe_unused]] uint32_t flags,
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005097 const std::function<status_t()>& delegate) {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005098 // make sure transactions reserved to AudioPolicyManager do not come from other processes
5099 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005100 case TransactionCode::SET_STREAM_VOLUME:
5101 case TransactionCode::SET_STREAM_MUTE:
5102 case TransactionCode::OPEN_OUTPUT:
5103 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
5104 case TransactionCode::CLOSE_OUTPUT:
5105 case TransactionCode::SUSPEND_OUTPUT:
5106 case TransactionCode::RESTORE_OUTPUT:
5107 case TransactionCode::OPEN_INPUT:
5108 case TransactionCode::CLOSE_INPUT:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005109 case TransactionCode::SET_VOICE_VOLUME:
5110 case TransactionCode::MOVE_EFFECTS:
5111 case TransactionCode::SET_EFFECT_SUSPENDED:
5112 case TransactionCode::LOAD_HW_MODULE:
5113 case TransactionCode::GET_AUDIO_PORT:
5114 case TransactionCode::CREATE_AUDIO_PATCH:
5115 case TransactionCode::RELEASE_AUDIO_PATCH:
5116 case TransactionCode::LIST_AUDIO_PATCHES:
5117 case TransactionCode::SET_AUDIO_PORT_CONFIG:
5118 case TransactionCode::SET_RECORD_SILENCED:
Eric Laurentd66d7a12021-07-13 13:35:32 +02005119 case TransactionCode::AUDIO_POLICY_READY:
Mikhail Naganov516d3982022-02-01 23:53:59 +00005120 case TransactionCode::SET_DEVICE_CONNECTED_STATE:
Eric Laurent076e7c72022-05-03 18:12:28 +02005121 case TransactionCode::SET_REQUESTED_LATENCY_MODE:
5122 case TransactionCode::GET_SUPPORTED_LATENCY_MODES:
jiabinc44b3462022-12-08 12:52:31 -08005123 case TransactionCode::INVALIDATE_TRACKS:
Mikhail Naganovffd97712023-05-03 17:45:36 -07005124 case TransactionCode::GET_AUDIO_POLICY_CONFIG:
jiabin12537fc2023-10-12 17:56:08 +00005125 case TransactionCode::GET_AUDIO_MIX_PORT:
jiabin220eea12024-05-17 17:55:20 +00005126 case TransactionCode::SET_TRACKS_INTERNAL_MUTE:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005127 ALOGW("%s: transaction %d received from PID %d",
Andy Hungf7786a42024-02-08 21:19:47 -08005128 __func__, static_cast<int>(code), IPCThreadState::self()->getCallingPid());
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005129 // return status only for non void methods
5130 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005131 case TransactionCode::SET_RECORD_SILENCED:
5132 case TransactionCode::SET_EFFECT_SUSPENDED:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005133 break;
5134 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005135 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005136 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005137 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005138 return OK;
5139 default:
5140 break;
5141 }
5142
5143 // make sure the following transactions come from system components
5144 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005145 case TransactionCode::SET_MASTER_VOLUME:
5146 case TransactionCode::SET_MASTER_MUTE:
Jean-Michel Trivie4f113b2020-11-16 11:50:33 -08005147 case TransactionCode::MASTER_MUTE:
Vlad Popae3fd1c22022-11-07 21:03:18 +01005148 case TransactionCode::GET_SOUND_DOSE_INTERFACE:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005149 case TransactionCode::SET_MODE:
5150 case TransactionCode::SET_MIC_MUTE:
5151 case TransactionCode::SET_LOW_RAM_DEVICE:
5152 case TransactionCode::SYSTEM_READY:
jiabin1319f5a2021-03-30 22:21:24 +00005153 case TransactionCode::SET_AUDIO_HAL_PIDS:
jiabinf042b9b2021-05-07 23:46:28 +00005154 case TransactionCode::SET_VIBRATOR_INFOS:
Eric Laurent52057642022-12-16 11:45:07 +01005155 case TransactionCode::UPDATE_SECONDARY_OUTPUTS:
Eric Laurent50d72582022-12-20 20:20:23 +01005156 case TransactionCode::SET_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5157 case TransactionCode::IS_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5158 case TransactionCode::SUPPORTS_BLUETOOTH_VARIABLE_LATENCY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005159 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
5160 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
Andy Hungf7786a42024-02-08 21:19:47 -08005161 __func__, static_cast<int>(code),
5162 IPCThreadState::self()->getCallingPid(),
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005163 IPCThreadState::self()->getCallingUid());
Vlad Popa63f047e2022-11-05 14:09:19 +01005164 // return status only for non-void methods
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005165 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005166 case TransactionCode::SYSTEM_READY:
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005167 break;
5168 default:
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005169 return INVALID_OPERATION;
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005170 }
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005171 // Fail silently in these cases.
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005172 return OK;
5173 }
5174 } break;
5175 default:
5176 break;
5177 }
5178
5179 // List of relevant events that trigger log merging.
5180 // Log merging should activate during audio activity of any kind. This are considered the
5181 // most relevant events.
5182 // TODO should select more wisely the items from the list
5183 switch (code) {
Ytai Ben-Tsvi50b8ccb2020-11-24 13:47:54 -08005184 case TransactionCode::CREATE_TRACK:
5185 case TransactionCode::CREATE_RECORD:
5186 case TransactionCode::SET_MASTER_VOLUME:
5187 case TransactionCode::SET_MASTER_MUTE:
5188 case TransactionCode::SET_MIC_MUTE:
5189 case TransactionCode::SET_PARAMETERS:
5190 case TransactionCode::CREATE_EFFECT:
5191 case TransactionCode::SYSTEM_READY: {
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005192 requestLogMerge();
5193 break;
5194 }
5195 default:
5196 break;
5197 }
5198
Andy Hungc747c532022-03-07 21:41:14 -08005199 const std::string methodName = getIAudioFlingerStatistics().getMethodForCode(code);
5200 mediautils::TimeCheck check(
5201 std::string("IAudioFlinger::").append(methodName),
5202 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
5203 if (timeout) {
5204 mediametrics::LogItem(mMetricsId)
5205 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
5206 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
5207 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
5208 .record();
5209 } else {
5210 getIAudioFlingerStatistics().event(code, elapsedMs);
5211 }
Andy Hungf8ab0932022-06-13 19:49:43 -07005212 }, mediautils::TimeCheck::kDefaultTimeoutDuration,
5213 mediautils::TimeCheck::kDefaultSecondChanceDuration,
5214 true /* crashOnTimeout */);
Ytai Ben-Tsvi53858472020-11-30 11:04:46 -08005215
Ytai Ben-Tsvi24b33fc2021-05-10 13:08:11 -07005216 return delegate();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217}
5218
Glenn Kasten63238ef2015-03-02 15:50:29 -08005219} // namespace android