1 /*
2 **
3 ** Copyright 2007, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #define LOG_TAG "AudioFlinger"
19 //#define LOG_NDEBUG 0
20 #define ATRACE_TAG ATRACE_TAG_AUDIO
21 #include <utils/Trace.h>
22
23 // Define AUDIO_ARRAYS_STATIC_CHECK to check all audio arrays are correct
24 #define AUDIO_ARRAYS_STATIC_CHECK 1
25
26 #include "Configuration.h"
27 #include "AudioFlinger.h"
28
29 #include <afutils/FallibleLockGuard.h>
30 #include <afutils/NBAIO_Tee.h>
31 #include <afutils/Permission.h>
32 #include <afutils/PropertyUtils.h>
33 #include <afutils/TypedLogger.h>
34 #include <android-base/errors.h>
35 #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>
42 #include <com_android_media_audio.h>
43 #include <com_android_media_audioserver.h>
44 #include <media/AidlConversion.h>
45 #include <media/AudioParameter.h>
46 #include <media/AudioValidator.h>
47 #include <media/IMediaLogService.h>
48 #include <media/IPermissionProvider.h>
49 #include <media/MediaMetricsItem.h>
50 #include <media/NativePermissionController.h>
51 #include <media/TypeConverter.h>
52 #include <media/ValidatedAttributionSourceState.h>
53 #include <mediautils/BatteryNotifier.h>
54 #include <mediautils/MemoryLeakTrackUtil.h>
55 #include <mediautils/MethodStatistics.h>
56 #include <mediautils/ServiceUtilities.h>
57 #include <mediautils/TimeCheck.h>
58 #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>
65
66 // not needed with the includes above, added to prevent transitive include dependency.
67 #include <chrono>
68 #include <thread>
69 #include <string_view>
70
71 // ----------------------------------------------------------------------------
72
73 // Note: the following macro is used for extremely verbose logging message. In
74 // order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
75 // 0; but one side effect of this is to turn all LOGV's as well. Some messages
76 // are so verbose that we want to suppress them even when we have ALOG_ASSERT
77 // turned on. Do not uncomment the #def below unless you really know what you
78 // are doing and want to see all of the extremely verbose messages.
79 //#define VERY_VERY_VERBOSE_LOGGING
80 #ifdef VERY_VERY_VERBOSE_LOGGING
81 #define ALOGVV ALOGV
82 #else
83 #define ALOGVV(a...) do { } while(0)
84 #endif
85
86 namespace android {
87
88 using namespace std::string_view_literals;
89
90 using ::android::base::StringPrintf;
91 using aidl_utils::statusTFromBinderStatus;
92 using media::IEffectClient;
93 using media::audio::common::AudioMMapPolicyInfo;
94 using media::audio::common::AudioMMapPolicyType;
95 using media::audio::common::AudioMode;
96 using android::content::AttributionSourceState;
97 using android::detail::AudioHalVersionInfo;
98 using com::android::media::permission::INativePermissionController;
99 using com::android::media::permission::IPermissionProvider;
100 using com::android::media::permission::NativePermissionController;
101 using com::android::media::permission::ValidatedAttributionSourceState;
102
103 static const AudioHalVersionInfo kMaxAAudioPropertyDeviceHalVersion =
104 AudioHalVersionInfo(AudioHalVersionInfo::Type::HIDL, 7, 1);
105
106 constexpr auto kDeadlockedString = "AudioFlinger may be deadlocked\n"sv;
107 constexpr auto kHardwareLockedString = "Hardware lock is taken\n"sv;
108 constexpr auto kClientLockedString = "Client lock is taken\n"sv;
109 constexpr auto kNoEffectsFactory = "Effects Factory is absent\n"sv;
110
111 static constexpr char kAudioServiceName[] = "audio";
112
113 // Keep a strong reference to media.log service around forever.
114 // The service is within our parent process so it can never die in a way that we could observe.
115 // These two variables are const after initialization.
116 static sp<IMediaLogService> sMediaLogService;
117
118 static pthread_once_t sMediaLogOnce = PTHREAD_ONCE_INIT;
119
sMediaLogInit()120 static void sMediaLogInit()
121 {
122 auto sMediaLogServiceAsBinder = defaultServiceManager()->getService(String16("media.log"));
123 if (sMediaLogServiceAsBinder != 0) {
124 sMediaLogService = interface_cast<IMediaLogService>(sMediaLogServiceAsBinder);
125 }
126 }
127
writeStr(int fd,std::string_view s)128 static int writeStr(int fd, std::string_view s) {
129 return write(fd, s.data(), s.size());
130 }
131
writeStr(int fd,const String8 & s)132 static int writeStr(int fd, const String8& s) {
133 return write(fd, s.c_str(), s.size());
134 }
135
136 static error::BinderResult<ValidatedAttributionSourceState>
validateAttributionFromContextOrTrustedCaller(AttributionSourceState attr,const IPermissionProvider & provider)137 validateAttributionFromContextOrTrustedCaller(AttributionSourceState attr,
138 const IPermissionProvider& provider) {
139 const auto callingUid = IPCThreadState::self()->getCallingUid();
140 // We trust the following UIDs to appropriate validated identities above us
141 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
142 // Legacy paths may not properly populate package name, so we attempt to handle.
143 if (!attr.packageName.has_value() || attr.packageName.value() == "") {
144 ALOGW("Trusted client %d provided attr with missing package name" , callingUid);
145 attr.packageName = VALUE_OR_RETURN(provider.getPackagesForUid(callingUid))[0];
146 }
147 // Behavior change: In the case of delegation, if pid is invalid,
148 // filling it in with the callingPid will cause a mismatch between the
149 // pid and the uid in the attribution, which is error-prone.
150 // Instead, assert that the pid from a trusted source is valid
151 if (attr.pid == -1) {
152 if (callingUid != static_cast<uid_t>(attr.uid)) {
153 return error::unexpectedExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
154 "validateAttribution: Invalid pid from delegating trusted source");
155 } else {
156 // Legacy handling for trusted clients which may not fill pid correctly
157 attr.pid = IPCThreadState::self()->getCallingPid();
158 }
159 }
160 return ValidatedAttributionSourceState::createFromTrustedSource(std::move(attr));
161 } else {
162 // Behavior change: Populate pid with callingPid unconditionally. Previously, we
163 // allowed caller provided pid, if uid matched calling context, but this is error-prone
164 // since it allows mismatching uid/pid
165 return ValidatedAttributionSourceState::createFromBinderContext(std::move(attr), provider);
166 }
167 }
168
169 #define VALUE_OR_RETURN_CONVERTED(exp) \
170 ({ \
171 auto _tmp = (exp); \
172 if (!_tmp.ok()) { \
173 ALOGE("Function: %s Line: %d Failed result (%s)", __FUNCTION__, __LINE__, \
174 errorToString(_tmp.error()).c_str()); \
175 return statusTFromBinderStatus(_tmp.error()); \
176 } \
177 std::move(_tmp.value()); \
178 })
179
180
181
182 // Creates association between Binder code to name for IAudioFlinger.
183 #define IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST \
184 BINDER_METHOD_ENTRY(createTrack) \
185 BINDER_METHOD_ENTRY(createRecord) \
186 BINDER_METHOD_ENTRY(sampleRate) \
187 BINDER_METHOD_ENTRY(format) \
188 BINDER_METHOD_ENTRY(frameCount) \
189 BINDER_METHOD_ENTRY(latency) \
190 BINDER_METHOD_ENTRY(setMasterVolume) \
191 BINDER_METHOD_ENTRY(setMasterMute) \
192 BINDER_METHOD_ENTRY(masterVolume) \
193 BINDER_METHOD_ENTRY(masterMute) \
194 BINDER_METHOD_ENTRY(setStreamVolume) \
195 BINDER_METHOD_ENTRY(setStreamMute) \
196 BINDER_METHOD_ENTRY(setPortsVolume) \
197 BINDER_METHOD_ENTRY(setMode) \
198 BINDER_METHOD_ENTRY(setMicMute) \
199 BINDER_METHOD_ENTRY(getMicMute) \
200 BINDER_METHOD_ENTRY(setRecordSilenced) \
201 BINDER_METHOD_ENTRY(setParameters) \
202 BINDER_METHOD_ENTRY(getParameters) \
203 BINDER_METHOD_ENTRY(registerClient) \
204 BINDER_METHOD_ENTRY(getInputBufferSize) \
205 BINDER_METHOD_ENTRY(openOutput) \
206 BINDER_METHOD_ENTRY(openDuplicateOutput) \
207 BINDER_METHOD_ENTRY(closeOutput) \
208 BINDER_METHOD_ENTRY(suspendOutput) \
209 BINDER_METHOD_ENTRY(restoreOutput) \
210 BINDER_METHOD_ENTRY(openInput) \
211 BINDER_METHOD_ENTRY(closeInput) \
212 BINDER_METHOD_ENTRY(setVoiceVolume) \
213 BINDER_METHOD_ENTRY(getRenderPosition) \
214 BINDER_METHOD_ENTRY(getInputFramesLost) \
215 BINDER_METHOD_ENTRY(newAudioUniqueId) \
216 BINDER_METHOD_ENTRY(acquireAudioSessionId) \
217 BINDER_METHOD_ENTRY(releaseAudioSessionId) \
218 BINDER_METHOD_ENTRY(queryNumberEffects) \
219 BINDER_METHOD_ENTRY(queryEffect) \
220 BINDER_METHOD_ENTRY(getEffectDescriptor) \
221 BINDER_METHOD_ENTRY(createEffect) \
222 BINDER_METHOD_ENTRY(moveEffects) \
223 BINDER_METHOD_ENTRY(loadHwModule) \
224 BINDER_METHOD_ENTRY(getPrimaryOutputSamplingRate) \
225 BINDER_METHOD_ENTRY(getPrimaryOutputFrameCount) \
226 BINDER_METHOD_ENTRY(setLowRamDevice) \
227 BINDER_METHOD_ENTRY(getAudioPort) \
228 BINDER_METHOD_ENTRY(createAudioPatch) \
229 BINDER_METHOD_ENTRY(releaseAudioPatch) \
230 BINDER_METHOD_ENTRY(listAudioPatches) \
231 BINDER_METHOD_ENTRY(setAudioPortConfig) \
232 BINDER_METHOD_ENTRY(getAudioHwSyncForSession) \
233 BINDER_METHOD_ENTRY(systemReady) \
234 BINDER_METHOD_ENTRY(audioPolicyReady) \
235 BINDER_METHOD_ENTRY(frameCountHAL) \
236 BINDER_METHOD_ENTRY(getMicrophones) \
237 BINDER_METHOD_ENTRY(setMasterBalance) \
238 BINDER_METHOD_ENTRY(getMasterBalance) \
239 BINDER_METHOD_ENTRY(setEffectSuspended) \
240 BINDER_METHOD_ENTRY(setAudioHalPids) \
241 BINDER_METHOD_ENTRY(setVibratorInfos) \
242 BINDER_METHOD_ENTRY(updateSecondaryOutputs) \
243 BINDER_METHOD_ENTRY(getMmapPolicyInfos) \
244 BINDER_METHOD_ENTRY(getAAudioMixerBurstCount) \
245 BINDER_METHOD_ENTRY(getAAudioHardwareBurstMinUsec) \
246 BINDER_METHOD_ENTRY(setDeviceConnectedState) \
247 BINDER_METHOD_ENTRY(setSimulateDeviceConnections) \
248 BINDER_METHOD_ENTRY(setRequestedLatencyMode) \
249 BINDER_METHOD_ENTRY(getSupportedLatencyModes) \
250 BINDER_METHOD_ENTRY(setBluetoothVariableLatencyEnabled) \
251 BINDER_METHOD_ENTRY(isBluetoothVariableLatencyEnabled) \
252 BINDER_METHOD_ENTRY(supportsBluetoothVariableLatency) \
253 BINDER_METHOD_ENTRY(getSoundDoseInterface) \
254 BINDER_METHOD_ENTRY(getAudioPolicyConfig) \
255 BINDER_METHOD_ENTRY(getAudioMixPort) \
256 BINDER_METHOD_ENTRY(resetReferencesForTest) \
257
258 // singleton for Binder Method Statistics for IAudioFlinger
getIAudioFlingerStatistics()259 static auto& getIAudioFlingerStatistics() {
260 using Code = android::AudioFlingerServerAdapter::Delegate::TransactionCode;
261
262 #pragma push_macro("BINDER_METHOD_ENTRY")
263 #undef BINDER_METHOD_ENTRY
264 #define BINDER_METHOD_ENTRY(ENTRY) \
265 {(Code)media::BnAudioFlingerService::TRANSACTION_##ENTRY, #ENTRY},
266
267 static mediautils::MethodStatistics<Code> methodStatistics{
268 IAUDIOFLINGER_BINDER_METHOD_MACRO_LIST
269 METHOD_STATISTICS_BINDER_CODE_NAMES(Code)
270 };
271 #pragma pop_macro("BINDER_METHOD_ENTRY")
272
273 return methodStatistics;
274 }
275
276 namespace base {
277 template <typename T>
278 struct OkOrFail<std::optional<T>> {
279 using opt_t = std::optional<T>;
280 OkOrFail() = delete;
281 OkOrFail(const opt_t&) = delete;
282
IsOkandroid::base::OkOrFail283 static bool IsOk(const opt_t& opt) { return opt.has_value(); }
Unwrapandroid::base::OkOrFail284 static T Unwrap(opt_t&& opt) { return std::move(opt.value()); }
ErrorMessageandroid::base::OkOrFail285 static std::string ErrorMessage(const opt_t&) { return "Empty optional"; }
Failandroid::base::OkOrFail286 static void Fail(opt_t&&) {}
287 };
288 }
289
290 class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback {
291 public:
onNewDevicesAvailable()292 void onNewDevicesAvailable() override {
293 // Start a detached thread to execute notification in parallel.
294 // This is done to prevent mutual blocking of audio_flinger and
295 // audio_policy services during system initialization.
296 std::thread notifier([]() {
297 AudioSystem::onNewAudioModulesAvailable();
298 });
299 notifier.detach();
300 }
301 };
302
303 // ----------------------------------------------------------------------------
304
instantiate()305 void AudioFlinger::instantiate() {
306 sp<IServiceManager> sm(defaultServiceManager());
307 sm->addService(String16(IAudioFlinger::DEFAULT_SERVICE_NAME),
308 new AudioFlingerServerAdapter(new AudioFlinger()), false,
309 IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
310 }
311
AudioFlinger()312 AudioFlinger::AudioFlinger()
313 {
314 // Move the audio session unique ID generator start base as time passes to limit risk of
315 // generating the same ID again after an audioserver restart.
316 // This is important because clients will reuse previously allocated audio session IDs
317 // when reconnecting after an audioserver restart and newly allocated IDs may conflict with
318 // active clients.
319 // Moving the base by 1 for each elapsed second is a good compromise between avoiding overlap
320 // between allocation ranges and not reaching wrap around too soon.
321 timespec ts{};
322 clock_gettime(CLOCK_MONOTONIC, &ts);
323 // zero ID has a special meaning, so start allocation at least at AUDIO_UNIQUE_ID_USE_MAX
324 uint32_t movingBase = (uint32_t)std::max((long)1, ts.tv_sec);
325 // unsigned instead of audio_unique_id_use_t, because ++ operator is unavailable for enum
326 for (unsigned use = AUDIO_UNIQUE_ID_USE_UNSPECIFIED; use < AUDIO_UNIQUE_ID_USE_MAX; use++) {
327 mNextUniqueIds[use] =
328 ((use == AUDIO_UNIQUE_ID_USE_SESSION || use == AUDIO_UNIQUE_ID_USE_CLIENT) ?
329 movingBase : 1) * AUDIO_UNIQUE_ID_USE_MAX;
330 }
331
332 #if 1
333 // FIXME See bug 165702394 and bug 168511485
334 const bool doLog = false;
335 #else
336 const bool doLog = property_get_bool("ro.test_harness", false);
337 #endif
338 if (doLog) {
339 mLogMemoryDealer = new MemoryDealer(kLogMemorySize, "LogWriters",
340 MemoryHeapBase::READ_ONLY);
341 (void) pthread_once(&sMediaLogOnce, sMediaLogInit);
342 }
343
344 // reset battery stats.
345 // if the audio service has crashed, battery stats could be left
346 // in bad state, reset the state upon service start.
347 BatteryNotifier::getInstance().noteResetAudio();
348
349 mMediaLogNotifier->run("MediaLogNotifier");
350
351 // Notify that we have started (also called when audioserver service restarts)
352 mediametrics::LogItem(mMetricsId)
353 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_CTOR)
354 .record();
355 }
356
onFirstRef()357 void AudioFlinger::onFirstRef()
358 {
359 audio_utils::lock_guard _l(mutex());
360
361 mMode = AUDIO_MODE_NORMAL;
362
363 gAudioFlinger = this; // we are already refcounted, store into atomic pointer.
364 mDeviceEffectManager = sp<DeviceEffectManager>::make(
365 sp<IAfDeviceEffectManagerCallback>::fromExisting(this)),
366 mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl;
367 mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback);
368
369 if (mDevicesFactoryHal->getHalVersion() <= kMaxAAudioPropertyDeviceHalVersion) {
370 mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty();
371 mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty();
372 }
373
374 mPatchPanel = IAfPatchPanel::create(sp<IAfPatchPanelCallback>::fromExisting(this));
375 mMelReporter = sp<MelReporter>::make(sp<IAfMelReporterCallback>::fromExisting(this),
376 mPatchPanel);
377 }
378
setAudioHalPids(const std::vector<pid_t> & pids)379 status_t AudioFlinger::setAudioHalPids(const std::vector<pid_t>& pids) {
380 mediautils::TimeCheck::setAudioHalPids(pids);
381 return NO_ERROR;
382 }
383
setVibratorInfos(const std::vector<media::AudioVibratorInfo> & vibratorInfos)384 status_t AudioFlinger::setVibratorInfos(
385 const std::vector<media::AudioVibratorInfo>& vibratorInfos) {
386 audio_utils::lock_guard _l(mutex());
387 mAudioVibratorInfos = vibratorInfos;
388 return NO_ERROR;
389 }
390
updateSecondaryOutputs(const TrackSecondaryOutputsMap & trackSecondaryOutputs)391 status_t AudioFlinger::updateSecondaryOutputs(
392 const TrackSecondaryOutputsMap& trackSecondaryOutputs) {
393 audio_utils::lock_guard _l(mutex());
394 for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) {
395 size_t i = 0;
396 for (; i < mPlaybackThreads.size(); ++i) {
397 IAfPlaybackThread* thread = mPlaybackThreads.valueAt(i).get();
398 audio_utils::lock_guard _tl(thread->mutex());
399 sp<IAfTrack> track = thread->getTrackById_l(trackId);
400 if (track != nullptr) {
401 ALOGD("%s trackId: %u", __func__, trackId);
402 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
403 break;
404 }
405 }
406 ALOGW_IF(i >= mPlaybackThreads.size(),
407 "%s cannot find track with id %u", __func__, trackId);
408 }
409 return NO_ERROR;
410 }
411
getMmapPolicyInfos(AudioMMapPolicyType policyType,std::vector<AudioMMapPolicyInfo> * policyInfos)412 status_t AudioFlinger::getMmapPolicyInfos(
413 AudioMMapPolicyType policyType, std::vector<AudioMMapPolicyInfo> *policyInfos) {
414 audio_utils::lock_guard _l(mutex());
415 if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) {
416 *policyInfos = it->second;
417 return NO_ERROR;
418 }
419 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
420 audio_utils::lock_guard lock(hardwareMutex());
421 for (size_t i = 0; i < mAudioHwDevs.size(); ++i) {
422 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
423 std::vector<AudioMMapPolicyInfo> infos;
424 status_t status = dev->getMmapPolicyInfos(policyType, &infos);
425 if (status != NO_ERROR) {
426 ALOGE("Failed to query mmap policy info of %d, error %d",
427 mAudioHwDevs.keyAt(i), status);
428 continue;
429 }
430 policyInfos->insert(policyInfos->end(), infos.begin(), infos.end());
431 }
432 mPolicyInfos[policyType] = *policyInfos;
433 } else {
434 getMmapPolicyInfosFromSystemProperty(policyType, policyInfos);
435 mPolicyInfos[policyType] = *policyInfos;
436 }
437 return NO_ERROR;
438 }
439
getAAudioMixerBurstCount() const440 int32_t AudioFlinger::getAAudioMixerBurstCount() const {
441 audio_utils::lock_guard _l(mutex());
442 return mAAudioBurstsPerBuffer;
443 }
444
getAAudioHardwareBurstMinUsec() const445 int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() const {
446 audio_utils::lock_guard _l(mutex());
447 return mAAudioHwBurstMinMicros;
448 }
449
setDeviceConnectedState(const struct audio_port_v7 * port,media::DeviceConnectedState state)450 status_t AudioFlinger::setDeviceConnectedState(const struct audio_port_v7 *port,
451 media::DeviceConnectedState state) {
452 status_t final_result = NO_INIT;
453 audio_utils::lock_guard _l(mutex());
454 audio_utils::lock_guard lock(hardwareMutex());
455 mHardwareStatus = AUDIO_HW_SET_CONNECTED_STATE;
456 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
457 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
458 status_t result = state == media::DeviceConnectedState::PREPARE_TO_DISCONNECT
459 ? dev->prepareToDisconnectExternalDevice(port)
460 : dev->setConnectedState(port, state == media::DeviceConnectedState::CONNECTED);
461 // Same logic as with setParameter: it's a success if at least one
462 // HAL module accepts the update.
463 if (final_result != NO_ERROR) {
464 final_result = result;
465 }
466 }
467 mHardwareStatus = AUDIO_HW_IDLE;
468 return final_result;
469 }
470
setSimulateDeviceConnections(bool enabled)471 status_t AudioFlinger::setSimulateDeviceConnections(bool enabled) {
472 bool at_least_one_succeeded = false;
473 status_t last_error = INVALID_OPERATION;
474 audio_utils::lock_guard _l(mutex());
475 audio_utils::lock_guard lock(hardwareMutex());
476 mHardwareStatus = AUDIO_HW_SET_SIMULATE_CONNECTIONS;
477 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
478 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
479 status_t result = dev->setSimulateDeviceConnections(enabled);
480 if (result == OK) {
481 at_least_one_succeeded = true;
482 } else {
483 last_error = result;
484 }
485 }
486 mHardwareStatus = AUDIO_HW_IDLE;
487 return at_least_one_succeeded ? OK : last_error;
488 }
489
490 // getDefaultVibratorInfo_l must be called with AudioFlinger lock held.
getDefaultVibratorInfo_l() const491 std::optional<media::AudioVibratorInfo> AudioFlinger::getDefaultVibratorInfo_l() const {
492 if (mAudioVibratorInfos.empty()) {
493 return {};
494 }
495 return mAudioVibratorInfos.front();
496 }
497
~AudioFlinger()498 AudioFlinger::~AudioFlinger()
499 {
500 while (!mRecordThreads.isEmpty()) {
501 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
502 closeInput_nonvirtual(mRecordThreads.keyAt(0));
503 }
504 while (!mPlaybackThreads.isEmpty()) {
505 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
506 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
507 }
508 while (!mMmapThreads.isEmpty()) {
509 const audio_io_handle_t io = mMmapThreads.keyAt(0);
510 if (mMmapThreads.valueAt(0)->isOutput()) {
511 closeOutput_nonvirtual(io); // removes entry from mMmapThreads
512 } else {
513 closeInput_nonvirtual(io); // removes entry from mMmapThreads
514 }
515 }
516
517 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
518 // no hardwareMutex() needed, as there are no other references to this
519 delete mAudioHwDevs.valueAt(i);
520 }
521
522 // Tell media.log service about any old writers that still need to be unregistered
523 if (sMediaLogService != 0) {
524 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
525 sp<IMemory> iMemory(mUnregisteredWriters.top()->getIMemory());
526 mUnregisteredWriters.pop();
527 sMediaLogService->unregisterWriter(iMemory);
528 }
529 }
530 mMediaLogNotifier->requestExit();
531 mPatchCommandThread->exit();
532 }
533
534 //static
535 __attribute__ ((visibility ("default")))
openMmapStream(MmapStreamInterface::stream_direction_t direction,const audio_attributes_t * attr,audio_config_base_t * config,const AudioClient & client,DeviceIdVector * deviceIds,audio_session_t * sessionId,const sp<MmapStreamCallback> & callback,sp<MmapStreamInterface> & interface,audio_port_handle_t * handle)536 status_t MmapStreamInterface::openMmapStream(MmapStreamInterface::stream_direction_t direction,
537 const audio_attributes_t *attr,
538 audio_config_base_t *config,
539 const AudioClient& client,
540 DeviceIdVector *deviceIds,
541 audio_session_t *sessionId,
542 const sp<MmapStreamCallback>& callback,
543 sp<MmapStreamInterface>& interface,
544 audio_port_handle_t *handle)
545 {
546 // TODO(b/292281786): Use ServiceManager to get IAudioFlinger instead of by atomic pointer.
547 // This allows moving oboeservice (AAudio) to a separate process in the future.
548 sp<AudioFlinger> af = AudioFlinger::gAudioFlinger.load(); // either nullptr or singleton AF.
549 status_t ret = NO_INIT;
550 if (af != 0) {
551 ret = af->openMmapStream(
552 direction, attr, config, client, deviceIds,
553 sessionId, callback, interface, handle);
554 }
555 return ret;
556 }
557
openMmapStream(MmapStreamInterface::stream_direction_t direction,const audio_attributes_t * attr,audio_config_base_t * config,const AudioClient & client,DeviceIdVector * deviceIds,audio_session_t * sessionId,const sp<MmapStreamCallback> & callback,sp<MmapStreamInterface> & interface,audio_port_handle_t * handle)558 status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t direction,
559 const audio_attributes_t *attr,
560 audio_config_base_t *config,
561 const AudioClient& client,
562 DeviceIdVector *deviceIds,
563 audio_session_t *sessionId,
564 const sp<MmapStreamCallback>& callback,
565 sp<MmapStreamInterface>& interface,
566 audio_port_handle_t *handle)
567 {
568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
572 audio_session_t actualSessionId = *sessionId;
573 if (actualSessionId == AUDIO_SESSION_ALLOCATE) {
574 actualSessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
575 }
576 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT;
577 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE;
578 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
579 audio_attributes_t localAttr = *attr;
580
581 // TODO b/182392553: refactor or make clearer
582 AttributionSourceState adjAttributionSource;
583 if (!com::android::media::audio::audioserver_permissions()) {
584 pid_t clientPid =
585 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(client.attributionSource.pid));
586 bool updatePid = (clientPid == (pid_t)-1);
587 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
588
589 adjAttributionSource = client.attributionSource;
590 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
591 uid_t clientUid =
592 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(client.attributionSource.uid));
593 ALOGW_IF(clientUid != callingUid,
594 "%s uid %d tried to pass itself off as %d",
595 __FUNCTION__, callingUid, clientUid);
596 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
597 legacy2aidl_uid_t_int32_t(callingUid));
598 updatePid = true;
599 }
600 if (updatePid) {
601 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
602 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
603 "%s uid %d pid %d tried to pass itself off as pid %d",
604 __func__, callingUid, callingPid, clientPid);
605 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
606 legacy2aidl_pid_t_int32_t(callingPid));
607 }
608 adjAttributionSource = afutils::checkAttributionSourcePackage(
609 adjAttributionSource);
610 } else {
611 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
612 validateAttributionFromContextOrTrustedCaller(client.attributionSource,
613 getPermissionProvider()
614 ));
615 // TODO pass wrapped object around
616 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
617 }
618
619 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
620 audio_config_t fullConfig = AUDIO_CONFIG_INITIALIZER;
621 fullConfig.sample_rate = config->sample_rate;
622 fullConfig.channel_mask = config->channel_mask;
623 fullConfig.format = config->format;
624 std::vector<audio_io_handle_t> secondaryOutputs;
625 bool isSpatialized;
626 bool isBitPerfect;
627 float volume;
628 bool muted;
629 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
630 actualSessionId,
631 &streamType, adjAttributionSource,
632 &fullConfig,
633 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ |
634 AUDIO_OUTPUT_FLAG_DIRECT),
635 deviceIds, &portId, &secondaryOutputs,
636 &isSpatialized,
637 &isBitPerfect,
638 &volume,
639 &muted);
640 if (ret != NO_ERROR) {
641 config->sample_rate = fullConfig.sample_rate;
642 config->channel_mask = fullConfig.channel_mask;
643 config->format = fullConfig.format;
644 }
645 ALOGW_IF(!secondaryOutputs.empty(),
646 "%s does not support secondary outputs, ignoring them", __func__);
647 } else {
648 audio_port_handle_t deviceId = getFirstDeviceId(*deviceIds);
649 ret = AudioSystem::getInputForAttr(&localAttr, &io,
650 RECORD_RIID_INVALID,
651 actualSessionId,
652 adjAttributionSource,
653 config,
654 AUDIO_INPUT_FLAG_MMAP_NOIRQ, &deviceId, &portId);
655 deviceIds->clear();
656 if (deviceId != AUDIO_PORT_HANDLE_NONE) {
657 deviceIds->push_back(deviceId);
658 }
659 }
660 if (ret != NO_ERROR) {
661 return ret;
662 }
663
664 // use unique_lock as we may selectively unlock.
665 audio_utils::unique_lock l(mutex());
666
667 // at this stage, a MmapThread was created when openOutput() or openInput() was called by
668 // audio policy manager and we can retrieve it
669 const sp<IAfMmapThread> thread = mMmapThreads.valueFor(io);
670 if (thread != 0) {
671 interface = IAfMmapThread::createMmapStreamInterfaceAdapter(thread);
672 thread->configure(&localAttr, streamType, actualSessionId, callback, *deviceIds, portId);
673 *handle = portId;
674 *sessionId = actualSessionId;
675 config->sample_rate = thread->sampleRate();
676 config->channel_mask = thread->channelMask();
677 config->format = thread->format();
678 } else {
679 l.unlock();
680 if (direction == MmapStreamInterface::DIRECTION_OUTPUT) {
681 AudioSystem::releaseOutput(portId);
682 } else {
683 AudioSystem::releaseInput(portId);
684 }
685 ret = NO_INIT;
686 // we don't reacquire the lock here as nothing left to do.
687 }
688
689 ALOGV("%s done status %d portId %d", __FUNCTION__, ret, portId);
690
691 return ret;
692 }
693
addEffectToHal(const struct audio_port_config * device,const sp<EffectHalInterface> & effect)694 status_t AudioFlinger::addEffectToHal(
695 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
696 audio_utils::lock_guard lock(hardwareMutex());
697 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
698 if (audioHwDevice == nullptr) {
699 return NO_INIT;
700 }
701 return audioHwDevice->hwDevice()->addDeviceEffect(device, effect);
702 }
703
removeEffectFromHal(const struct audio_port_config * device,const sp<EffectHalInterface> & effect)704 status_t AudioFlinger::removeEffectFromHal(
705 const struct audio_port_config *device, const sp<EffectHalInterface>& effect) {
706 audio_utils::lock_guard lock(hardwareMutex());
707 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(device->ext.device.hw_module);
708 if (audioHwDevice == nullptr) {
709 return NO_INIT;
710 }
711 return audioHwDevice->hwDevice()->removeDeviceEffect(device, effect);
712 }
713
714 static const char * const audio_interfaces[] = {
715 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
716 AUDIO_HARDWARE_MODULE_ID_A2DP,
717 AUDIO_HARDWARE_MODULE_ID_USB,
718 };
719
findSuitableHwDev_l(audio_module_handle_t module,audio_devices_t deviceType)720 AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
721 audio_module_handle_t module,
722 audio_devices_t deviceType)
723 {
724 // if module is 0, the request comes from an old policy manager and we should load
725 // well known modules
726 audio_utils::lock_guard lock(hardwareMutex());
727 if (module == 0) {
728 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
729 for (size_t i = 0; i < arraysize(audio_interfaces); i++) {
730 loadHwModule_ll(audio_interfaces[i]);
731 }
732 // then try to find a module supporting the requested device.
733 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
734 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
735 sp<DeviceHalInterface> dev = audioHwDevice->hwDevice();
736 uint32_t supportedDevices;
737 if (dev->getSupportedDevices(&supportedDevices) == OK &&
738 (supportedDevices & deviceType) == deviceType) {
739 return audioHwDevice;
740 }
741 }
742 } else {
743 // check a match for the requested module handle
744 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
745 if (audioHwDevice != NULL) {
746 return audioHwDevice;
747 }
748 }
749
750 return NULL;
751 }
752
dumpClients_ll(int fd,bool dumpAllocators)753 void AudioFlinger::dumpClients_ll(int fd, bool dumpAllocators) {
754 String8 result;
755
756 if (dumpAllocators) {
757 result.append("Client Allocators:\n");
758 for (size_t i = 0; i < mClients.size(); ++i) {
759 sp<Client> client = mClients.valueAt(i).promote();
760 if (client != 0) {
761 result.appendFormat("Client: %d\n", client->pid());
762 result.append(client->allocator().dump().c_str());
763 }
764 }
765 }
766
767 result.append("Notification Clients:\n");
768 result.append(" pid uid name\n");
769 for (const auto& [ _, client ] : mNotificationClients) {
770 const uid_t uid = client->getUid();
771 const std::shared_ptr<const mediautils::UidInfo::Info> info =
772 mediautils::UidInfo::getInfo(uid);
773 result.appendFormat("%6d %6u %s\n",
774 client->getPid(), uid, info->package.c_str());
775 }
776
777 result.append("Global session refs:\n");
778 result.append(" session cnt pid uid name\n");
779 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
780 AudioSessionRef *r = mAudioSessionRefs[i];
781 const std::shared_ptr<const mediautils::UidInfo::Info> info =
782 mediautils::UidInfo::getInfo(r->mUid);
783 result.appendFormat(" %7d %4d %7d %6u %s\n", r->mSessionid, r->mCnt, r->mPid,
784 r->mUid, info->package.c_str());
785 }
786 writeStr(fd, result);
787 }
788
789
dumpInternals_l(int fd)790 void AudioFlinger::dumpInternals_l(int fd) {
791 const size_t SIZE = 256;
792 char buffer[SIZE];
793 String8 result;
794 hardware_call_state hardwareStatus = mHardwareStatus;
795
796 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
797 result.append(buffer);
798 writeStr(fd, result);
799
800 dprintf(fd, "Vibrator infos(size=%zu):\n", mAudioVibratorInfos.size());
801 for (const auto& vibratorInfo : mAudioVibratorInfos) {
802 dprintf(fd, " - %s\n", vibratorInfo.toString().c_str());
803 }
804 dprintf(fd, "Bluetooth latency modes are %senabled\n",
805 mBluetoothLatencyModesEnabled ? "" : "not ");
806 }
807
dumpStats(int fd)808 void AudioFlinger::dumpStats(int fd) {
809 // Dump binder stats
810 dprintf(fd, "\nIAudioFlinger binder call profile:\n");
811 writeStr(fd, getIAudioFlingerStatistics().dump());
812
813 extern mediautils::MethodStatistics<int>& getIEffectStatistics();
814 dprintf(fd, "\nIEffect binder call profile:\n");
815 writeStr(fd, getIEffectStatistics().dump());
816
817 // Automatically fetch HIDL or AIDL statistics.
818 const std::string_view halType = (mDevicesFactoryHal->getHalVersion().getType() ==
819 AudioHalVersionInfo::Type::HIDL)
820 ? METHOD_STATISTICS_MODULE_NAME_AUDIO_HIDL
821 : METHOD_STATISTICS_MODULE_NAME_AUDIO_AIDL;
822 const std::shared_ptr<std::vector<std::string>> halClassNames =
823 mediautils::getStatisticsClassesForModule(halType);
824 if (halClassNames) {
825 for (const auto& className : *halClassNames) {
826 auto stats = mediautils::getStatisticsForClass(className);
827 if (stats) {
828 dprintf(fd, "\n%s binder call profile:\n", className.c_str());
829 writeStr(fd, stats->dump());
830 }
831 }
832 }
833
834 dprintf(fd, "\nTimeCheck:\n");
835 writeStr(fd, mediautils::TimeCheck::toString());
836 dprintf(fd, "\n");
837 // dump mutex stats
838 writeStr(fd, audio_utils::mutex::all_stats_to_string());
839 // dump held mutexes
840 writeStr(fd, audio_utils::mutex::all_threads_to_string());
841
842 }
843
dumpPermissionDenial(int fd)844 void AudioFlinger::dumpPermissionDenial(int fd) {
845 const size_t SIZE = 256;
846 char buffer[SIZE];
847 String8 result;
848 snprintf(buffer, SIZE, "Permission Denial: "
849 "can't dump AudioFlinger from pid=%d, uid=%d\n",
850 IPCThreadState::self()->getCallingPid(),
851 IPCThreadState::self()->getCallingUid());
852 result.append(buffer);
853 writeStr(fd, result);
854 }
855
dump_printHelp(int fd)856 static void dump_printHelp(int fd) {
857 constexpr static auto helpStr =
858 "AudioFlinger dumpsys help options\n"
859 " -h/--help: Print this help text\n"
860 " --hal: Include dump of audio hal\n"
861 " --stats: Include call/lock/watchdog stats\n"
862 " --effects: Include effect definitions\n"
863 " --memory: Include memory dump\n"
864 " -a/--all: Print all except --memory\n"sv;
865
866 write(fd, helpStr.data(), helpStr.length());
867 }
868
dump(int fd,const Vector<String16> & args)869 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
870 {
871 using afutils::FallibleLockGuard;
872 if (!dumpAllowed()) {
873 dumpPermissionDenial(fd);
874 return NO_ERROR;
875 }
876 // Arg parsing
877 struct {
878 bool shouldDumpMem, shouldDumpStats, shouldDumpHal, shouldDumpEffects;
879 } parsedArgs {}; // zero-init
880
881 for (const auto& arg : args) {
882 const String8 utf8arg{arg};
883 if (utf8arg == "-h" || utf8arg == "--help") {
884 dump_printHelp(fd);
885 return NO_ERROR;
886 }
887 if (utf8arg == "-a" || utf8arg == "--all") {
888 parsedArgs.shouldDumpStats = true;
889 parsedArgs.shouldDumpHal = true;
890 parsedArgs.shouldDumpEffects = true;
891 continue;
892 }
893 if (utf8arg == "--hal") {
894 parsedArgs.shouldDumpHal = true;
895 continue;
896 }
897 if (utf8arg == "--stats") {
898 parsedArgs.shouldDumpStats = true;
899 continue;
900 }
901 if (utf8arg == "--effects") {
902 parsedArgs.shouldDumpEffects = true;
903 continue;
904 }
905 if (utf8arg == "--memory") {
906 parsedArgs.shouldDumpMem = true;
907 continue;
908 }
909 // Unknown arg silently ignored
910 }
911
912 {
913 std::string res;
914 res.reserve(100);
915 res += "Start begin: ";
916 const auto startTimeStr = audio_utils_time_string_from_ns(mStartTime);
917 res += startTimeStr.time;
918 const auto startFinishedTime = getStartupFinishedTime();
919 if (startFinishedTime != 0) {
920 res += "\nStart end: ";
921 const auto startEndStr = audio_utils_time_string_from_ns(startFinishedTime);
922 res += startEndStr.time;
923 } else {
924 res += "\nStartup not yet finished!";
925 }
926 const auto nowTimeStr = audio_utils_time_string_from_ns(audio_utils_get_real_time_ns());
927 res += "\nNow: ";
928 res += nowTimeStr.time;
929 res += "\n";
930 writeStr(fd, res);
931 }
932 // get state of hardware lock
933 {
934 FallibleLockGuard l{hardwareMutex()};
935 if (!l) writeStr(fd, kHardwareLockedString);
936 }
937 {
938 FallibleLockGuard l{mutex()};
939 if (!l) writeStr(fd, kDeadlockedString);
940 {
941 FallibleLockGuard ll{clientMutex()};
942 if (!ll) writeStr(fd, kClientLockedString);
943 dumpClients_ll(fd, parsedArgs.shouldDumpMem);
944 }
945
946 dumpInternals_l(fd);
947
948 dprintf(fd, "\n ## BEGIN thread dump \n");
949 // dump playback threads
950 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
951 mPlaybackThreads.valueAt(i)->dump(fd, args);
952 }
953
954 // dump record threads
955 for (size_t i = 0; i < mRecordThreads.size(); i++) {
956 mRecordThreads.valueAt(i)->dump(fd, args);
957 }
958
959 // dump mmap threads
960 for (size_t i = 0; i < mMmapThreads.size(); i++) {
961 mMmapThreads.valueAt(i)->dump(fd, args);
962 }
963
964 // dump orphan effect chains
965 if (mOrphanEffectChains.size() != 0) {
966 writeStr(fd, " Orphan Effect Chains\n");
967 for (size_t i = 0; i < mOrphanEffectChains.size(); i++) {
968 mOrphanEffectChains.valueAt(i)->dump(fd, args);
969 }
970 }
971 // dump historical threads in the last 10 seconds
972 writeStr(fd, mThreadLog.dumpToString(
973 "Historical Thread Log ", 0 /* lines */,
974 audio_utils_get_real_time_ns() - 10 * 60 * NANOS_PER_SECOND));
975
976 // dump external setParameters
977 dprintf(fd, "\n ## BEGIN setParameters dump \n");
978 auto dumpLogger = [fd](SimpleLog& logger, const char* name) {
979 dprintf(fd, "\n %s setParameters:\n", name);
980 logger.dump(fd, " " /* prefix */);
981 };
982 dumpLogger(mRejectedSetParameterLog, "Rejected");
983 dumpLogger(mAppSetParameterLog, "App");
984 dumpLogger(mSystemSetParameterLog, "System");
985
986
987 dprintf(fd, "\n ## BEGIN misc af dump \n");
988 mPatchPanel->dump(fd);
989 mDeviceEffectManager->dump(fd);
990 writeStr(fd, mMelReporter->dump());
991
992 if (media::psh_utils::AudioPowerManager::enabled()) {
993 char value[PROPERTY_VALUE_MAX];
994 property_get("ro.build.display.id", value, "Unknown build");
995 std::string build(value);
996 writeStr(fd, build + "\n");
997 writeStr(fd, media::psh_utils::AudioPowerManager::getAudioPowerManager().toString());
998 }
999
1000 if (parsedArgs.shouldDumpEffects) {
1001 dprintf(fd, "\n ## BEGIN effects dump \n");
1002 if (mEffectsFactoryHal != 0) {
1003 mEffectsFactoryHal->dumpEffects(fd);
1004 } else {
1005 writeStr(fd, kNoEffectsFactory);
1006 }
1007 }
1008
1009 if (parsedArgs.shouldDumpHal) {
1010 dprintf(fd, "\n ## BEGIN HAL dump \n");
1011 FallibleLockGuard ll{hardwareMutex()};
1012 // dump all hardware devs
1013 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1014 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1015 dev->dump(fd, args);
1016 }
1017 }
1018 } // end af lock
1019
1020 if (parsedArgs.shouldDumpStats) {
1021 dprintf(fd, "\n ## BEGIN stats dump \n");
1022 dumpStats(fd);
1023 }
1024
1025 if (parsedArgs.shouldDumpMem) {
1026 dprintf(fd, "\n ## BEGIN memory dump \n");
1027 writeStr(fd, dumpMemoryAddresses(100 /* limit */));
1028 dprintf(fd, "\nDumping unreachable memory:\n");
1029 // TODO - should limit be an argument parameter?
1030 writeStr(fd, GetUnreachableMemoryString(true /* contents */, 100 /* limit */));
1031 }
1032
1033 return NO_ERROR;
1034 }
1035
registerClient(pid_t pid,uid_t uid)1036 sp<Client> AudioFlinger::registerClient(pid_t pid, uid_t uid)
1037 {
1038 audio_utils::lock_guard _cl(clientMutex());
1039 // If pid is already in the mClients wp<> map, then use that entry
1040 // (for which promote() is always != 0), otherwise create a new entry and Client.
1041 sp<Client> client = mClients.valueFor(pid).promote();
1042 if (client == 0) {
1043 client = sp<Client>::make(sp<IAfClientCallback>::fromExisting(this), pid, uid);
1044 mClients.add(pid, client);
1045 }
1046
1047 return client;
1048 }
1049
newWriter_l(size_t size,const char * name)1050 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
1051 {
1052 // If there is no memory allocated for logs, return a no-op writer that does nothing.
1053 // Similarly if we can't contact the media.log service, also return a no-op writer.
1054 if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
1055 return new NBLog::Writer();
1056 }
1057 sp<IMemory> shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1058 // If allocation fails, consult the vector of previously unregistered writers
1059 // and garbage-collect one or more them until an allocation succeeds
1060 if (shared == 0) {
1061 audio_utils::lock_guard _l(unregisteredWritersMutex());
1062 for (size_t count = mUnregisteredWriters.size(); count > 0; count--) {
1063 {
1064 // Pick the oldest stale writer to garbage-collect
1065 sp<IMemory> iMemory(mUnregisteredWriters[0]->getIMemory());
1066 mUnregisteredWriters.removeAt(0);
1067 sMediaLogService->unregisterWriter(iMemory);
1068 // Now the media.log remote reference to IMemory is gone. When our last local
1069 // reference to IMemory also drops to zero at end of this block,
1070 // the IMemory destructor will deallocate the region from mLogMemoryDealer.
1071 }
1072 // Re-attempt the allocation
1073 shared = mLogMemoryDealer->allocate(NBLog::Timeline::sharedSize(size));
1074 if (shared != 0) {
1075 goto success;
1076 }
1077 }
1078 // Even after garbage-collecting all old writers, there is still not enough memory,
1079 // so return a no-op writer
1080 return new NBLog::Writer();
1081 }
1082 success:
1083 NBLog::Shared *sharedRawPtr = (NBLog::Shared *) shared->unsecurePointer();
1084 new((void *) sharedRawPtr) NBLog::Shared(); // placement new here, but the corresponding
1085 // explicit destructor not needed since it is POD
1086 sMediaLogService->registerWriter(shared, size, name);
1087 return new NBLog::Writer(shared, size);
1088 }
1089
unregisterWriter(const sp<NBLog::Writer> & writer)1090 void AudioFlinger::unregisterWriter(const sp<NBLog::Writer>& writer)
1091 {
1092 if (writer == 0) {
1093 return;
1094 }
1095 sp<IMemory> iMemory(writer->getIMemory());
1096 if (iMemory == 0) {
1097 return;
1098 }
1099 // Rather than removing the writer immediately, append it to a queue of old writers to
1100 // be garbage-collected later. This allows us to continue to view old logs for a while.
1101 audio_utils::lock_guard _l(unregisteredWritersMutex());
1102 mUnregisteredWriters.push(writer);
1103 }
1104
1105 // IAudioFlinger interface
1106
createTrack(const media::CreateTrackRequest & _input,media::CreateTrackResponse & _output)1107 status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input,
1108 media::CreateTrackResponse& _output)
1109 {
1110 ATRACE_CALL();
1111 // Local version of VALUE_OR_RETURN, specific to this method's calling conventions.
1112 CreateTrackInput input = VALUE_OR_RETURN_STATUS(CreateTrackInput::fromAidl(_input));
1113 CreateTrackOutput output;
1114
1115 sp<IAfTrack> track;
1116 sp<Client> client;
1117 status_t lStatus;
1118 audio_stream_type_t streamType;
1119 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
1120 std::vector<audio_io_handle_t> secondaryOutputs;
1121 bool isSpatialized = false;
1122 bool isBitPerfect = false;
1123 float volume;
1124 bool muted;
1125
1126 audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE;
1127 std::vector<int> effectIds;
1128 audio_attributes_t localAttr = input.attr;
1129
1130 AttributionSourceState adjAttributionSource;
1131 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1132 if (!com::android::media::audio::audioserver_permissions()) {
1133 adjAttributionSource = input.clientInfo.attributionSource;
1134 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
1135 uid_t clientUid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(
1136 input.clientInfo.attributionSource.uid));
1137 pid_t clientPid =
1138 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
1139 input.clientInfo.attributionSource.pid));
1140 bool updatePid = (clientPid == (pid_t)-1);
1141
1142 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
1143 ALOGW_IF(clientUid != callingUid,
1144 "%s uid %d tried to pass itself off as %d",
1145 __FUNCTION__, callingUid, clientUid);
1146 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
1147 legacy2aidl_uid_t_int32_t(callingUid));
1148 clientUid = callingUid;
1149 updatePid = true;
1150 }
1151 if (updatePid) {
1152 ALOGW_IF(clientPid != (pid_t)-1 && clientPid != callingPid,
1153 "%s uid %d pid %d tried to pass itself off as pid %d",
1154 __func__, callingUid, callingPid, clientPid);
1155 clientPid = callingPid;
1156 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
1157 legacy2aidl_pid_t_int32_t(callingPid));
1158 }
1159 adjAttributionSource = afutils::checkAttributionSourcePackage(
1160 adjAttributionSource);
1161
1162 } else {
1163 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
1164 validateAttributionFromContextOrTrustedCaller(input.clientInfo.attributionSource,
1165 getPermissionProvider()
1166 ));
1167 // TODO pass wrapped object around
1168 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
1169 }
1170
1171 DeviceIdVector selectedDeviceIds;
1172 audio_session_t sessionId = input.sessionId;
1173 if (sessionId == AUDIO_SESSION_ALLOCATE) {
1174 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
1175 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
1176 lStatus = BAD_VALUE;
1177 goto Exit;
1178 }
1179
1180 output.sessionId = sessionId;
1181 output.outputId = AUDIO_IO_HANDLE_NONE;
1182 if (input.selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1183 selectedDeviceIds.push_back(input.selectedDeviceId);
1184 }
1185 lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType,
1186 adjAttributionSource, &input.config, input.flags,
1187 &selectedDeviceIds, &portId, &secondaryOutputs,
1188 &isSpatialized, &isBitPerfect, &volume, &muted);
1189 output.selectedDeviceIds = selectedDeviceIds;
1190
1191 if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) {
1192 ALOGE("createTrack() getOutputForAttr() return error %d or invalid output handle", lStatus);
1193 goto Exit;
1194 }
1195 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
1196 // but if someone uses binder directly they could bypass that and cause us to crash
1197 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
1198 ALOGE("createTrack() invalid stream type %d", streamType);
1199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
1202
1203 // further channel mask checks are performed by createTrack_l() depending on the thread type
1204 if (!audio_is_output_channel(input.config.channel_mask)) {
1205 ALOGE("createTrack() invalid channel mask %#x", input.config.channel_mask);
1206 lStatus = BAD_VALUE;
1207 goto Exit;
1208 }
1209
1210 // further format checks are performed by createTrack_l() depending on the thread type
1211 if (!audio_is_valid_format(input.config.format)) {
1212 ALOGE("createTrack() invalid format %#x", input.config.format);
1213 lStatus = BAD_VALUE;
1214 goto Exit;
1215 }
1216
1217 {
1218 audio_utils::lock_guard _l(mutex());
1219 IAfPlaybackThread* thread = checkPlaybackThread_l(output.outputId);
1220 if (thread == NULL) {
1221 ALOGE("no playback thread found for output handle %d", output.outputId);
1222 lStatus = BAD_VALUE;
1223 goto Exit;
1224 }
1225
1226 client = registerClient(adjAttributionSource.pid, adjAttributionSource.uid);
1227
1228 IAfPlaybackThread* effectThread = nullptr;
1229 sp<IAfEffectChain> effectChain = nullptr;
1230 // check if an effect chain with the same session ID is present on another
1231 // output thread and move it here.
1232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1233 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
1234 if (mPlaybackThreads.keyAt(i) != output.outputId) {
1235 uint32_t sessions = t->hasAudioSession(sessionId);
1236 if (sessions & IAfThreadBase::EFFECT_SESSION) {
1237 effectThread = t.get();
1238 break;
1239 }
1240 }
1241 }
1242 // Check if an orphan effect chain exists for this session
1243 if (effectThread == nullptr) {
1244 effectChain = getOrphanEffectChain_l(sessionId);
1245 }
1246 ALOGV("createTrack() sessionId: %d volume: %f muted %d", sessionId, volume, muted);
1247
1248 output.sampleRate = input.config.sample_rate;
1249 output.frameCount = input.frameCount;
1250 output.notificationFrameCount = input.notificationFrameCount;
1251 output.flags = input.flags;
1252 output.streamType = streamType;
1253
1254 track = thread->createTrack_l(client, streamType, localAttr, &output.sampleRate,
1255 input.config.format, input.config.channel_mask,
1256 &output.frameCount, &output.notificationFrameCount,
1257 input.notificationsPerBuffer, input.speed,
1258 input.sharedBuffer, sessionId, &output.flags,
1259 callingPid, adjAttributionSource, input.clientInfo.clientTid,
1260 &lStatus, portId, input.audioTrackCallback, isSpatialized,
1261 isBitPerfect, &output.afTrackFlags, volume, muted);
1262 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0));
1263 // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless
1264
1265 output.afFrameCount = thread->frameCount();
1266 output.afSampleRate = thread->sampleRate();
1267 output.afChannelMask = static_cast<audio_channel_mask_t>(thread->channelMask() |
1268 thread->hapticChannelMask());
1269 output.afFormat = thread->format();
1270 output.afLatencyMs = thread->latency();
1271 output.portId = portId;
1272
1273 if (lStatus == NO_ERROR) {
1274 // no risk of deadlock because AudioFlinger::mutex() is held
1275 audio_utils::lock_guard _dl(thread->mutex());
1276 // Connect secondary outputs. Failure on a secondary output must not imped the primary
1277 // Any secondary output setup failure will lead to a desync between the AP and AF until
1278 // the track is destroyed.
1279 updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs);
1280 // move effect chain to this output thread if an effect on same session was waiting
1281 // for a track to be created
1282 if (effectThread != nullptr) {
1283 // No thread safety analysis: double lock on a thread capability.
1284 audio_utils::lock_guard_no_thread_safety_analysis _sl(effectThread->mutex());
1285 if (moveEffectChain_ll(sessionId, effectThread, thread) == NO_ERROR) {
1286 effectThreadId = thread->id();
1287 effectIds = thread->getEffectIds_l(sessionId);
1288 }
1289 }
1290 if (effectChain != nullptr) {
1291 if (moveEffectChain_ll(sessionId, nullptr, thread, effectChain.get())
1292 == NO_ERROR) {
1293 effectThreadId = thread->id();
1294 effectIds = thread->getEffectIds_l(sessionId);
1295 }
1296 }
1297 }
1298
1299 // Look for sync events awaiting for a session to be used.
1300 for (auto it = mPendingSyncEvents.begin(); it != mPendingSyncEvents.end();) {
1301 if ((*it)->triggerSession() == sessionId) {
1302 if (thread->isValidSyncEvent(*it)) {
1303 if (lStatus == NO_ERROR) {
1304 (void) track->setSyncEvent(*it);
1305 } else {
1306 (*it)->cancel();
1307 }
1308 it = mPendingSyncEvents.erase(it);
1309 continue;
1310 }
1311 }
1312 ++it;
1313 }
1314 if ((output.flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) == AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
1315 setAudioHwSyncForSession_l(thread, sessionId);
1316 }
1317 }
1318
1319 if (lStatus != NO_ERROR) {
1320 // remove local strong reference to Client before deleting the Track so that the
1321 // Client destructor is called by the TrackBase destructor with clientMutex() held
1322 // Don't hold clientMutex() when releasing the reference on the track as the
1323 // destructor will acquire it.
1324 {
1325 audio_utils::lock_guard _cl(clientMutex());
1326 client.clear();
1327 }
1328 track.clear();
1329 goto Exit;
1330 }
1331
1332 // effectThreadId is not NONE if an effect chain corresponding to the track session
1333 // was found on another thread and must be moved on this thread
1334 if (effectThreadId != AUDIO_IO_HANDLE_NONE) {
1335 AudioSystem::moveEffectsToIo(effectIds, effectThreadId);
1336 }
1337
1338 output.audioTrack = IAfTrack::createIAudioTrackAdapter(track);
1339 _output = VALUE_OR_FATAL(output.toAidl());
1340
1341 Exit:
1342 if (lStatus != NO_ERROR && output.outputId != AUDIO_IO_HANDLE_NONE) {
1343 AudioSystem::releaseOutput(portId);
1344 }
1345 return lStatus;
1346 }
1347
sampleRate(audio_io_handle_t ioHandle) const1348 uint32_t AudioFlinger::sampleRate(audio_io_handle_t ioHandle) const
1349 {
1350 audio_utils::lock_guard _l(mutex());
1351 IAfThreadBase* const thread = checkThread_l(ioHandle);
1352 if (thread == NULL) {
1353 ALOGW("sampleRate() unknown thread %d", ioHandle);
1354 return 0;
1355 }
1356 return thread->sampleRate();
1357 }
1358
format(audio_io_handle_t output) const1359 audio_format_t AudioFlinger::format(audio_io_handle_t output) const
1360 {
1361 audio_utils::lock_guard _l(mutex());
1362 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
1363 if (thread == NULL) {
1364 ALOGW("format() unknown thread %d", output);
1365 return AUDIO_FORMAT_INVALID;
1366 }
1367 return thread->format();
1368 }
1369
frameCount(audio_io_handle_t ioHandle) const1370 size_t AudioFlinger::frameCount(audio_io_handle_t ioHandle) const
1371 {
1372 audio_utils::lock_guard _l(mutex());
1373 IAfThreadBase* const thread = checkThread_l(ioHandle);
1374 if (thread == NULL) {
1375 ALOGW("frameCount() unknown thread %d", ioHandle);
1376 return 0;
1377 }
1378 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
1379 // should examine all callers and fix them to handle smaller counts
1380 return thread->frameCount();
1381 }
1382
frameCountHAL(audio_io_handle_t ioHandle) const1383 size_t AudioFlinger::frameCountHAL(audio_io_handle_t ioHandle) const
1384 {
1385 audio_utils::lock_guard _l(mutex());
1386 IAfThreadBase* const thread = checkThread_l(ioHandle);
1387 if (thread == NULL) {
1388 ALOGW("frameCountHAL() unknown thread %d", ioHandle);
1389 return 0;
1390 }
1391 return thread->frameCountHAL();
1392 }
1393
latency(audio_io_handle_t output) const1394 uint32_t AudioFlinger::latency(audio_io_handle_t output) const
1395 {
1396 audio_utils::lock_guard _l(mutex());
1397 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
1398 if (thread == NULL) {
1399 ALOGW("latency(): no playback thread found for output handle %d", output);
1400 return 0;
1401 }
1402 return thread->latency();
1403 }
1404
setMasterVolume(float value)1405 status_t AudioFlinger::setMasterVolume(float value)
1406 {
1407 status_t ret = initCheck();
1408 if (ret != NO_ERROR) {
1409 return ret;
1410 }
1411
1412 // check calling permissions
1413 if (!settingsAllowed()) {
1414 return PERMISSION_DENIED;
1415 }
1416
1417 audio_utils::lock_guard _l(mutex());
1418 mMasterVolume = value;
1419
1420 // Set master volume in the HALs which support it.
1421 {
1422 audio_utils::lock_guard lock(hardwareMutex());
1423 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1424 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1425
1426 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
1427 if (dev->canSetMasterVolume()) {
1428 dev->hwDevice()->setMasterVolume(value);
1429 }
1430 mHardwareStatus = AUDIO_HW_IDLE;
1431 }
1432 }
1433 // Now set the master volume in each playback thread. Playback threads
1434 // assigned to HALs which do not have master volume support will apply
1435 // master volume during the mix operation. Threads with HALs which do
1436 // support master volume will simply ignore the setting.
1437 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1438 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1439 continue;
1440 }
1441 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
1442 }
1443
1444 return NO_ERROR;
1445 }
1446
setMasterBalance(float balance)1447 status_t AudioFlinger::setMasterBalance(float balance)
1448 {
1449 status_t ret = initCheck();
1450 if (ret != NO_ERROR) {
1451 return ret;
1452 }
1453
1454 // check calling permissions
1455 if (!settingsAllowed()) {
1456 return PERMISSION_DENIED;
1457 }
1458
1459 // check range
1460 if (isnan(balance) || fabs(balance) > 1.f) {
1461 return BAD_VALUE;
1462 }
1463
1464 audio_utils::lock_guard _l(mutex());
1465
1466 // short cut.
1467 if (mMasterBalance == balance) return NO_ERROR;
1468
1469 mMasterBalance = balance;
1470
1471 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1472 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
1473 continue;
1474 }
1475 mPlaybackThreads.valueAt(i)->setMasterBalance(balance);
1476 }
1477
1478 return NO_ERROR;
1479 }
1480
setMode(audio_mode_t mode)1481 status_t AudioFlinger::setMode(audio_mode_t mode)
1482 {
1483 status_t ret = initCheck();
1484 if (ret != NO_ERROR) {
1485 return ret;
1486 }
1487
1488 // check calling permissions
1489 if (!settingsAllowed()) {
1490 return PERMISSION_DENIED;
1491 }
1492 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
1493 ALOGW("Illegal value: setMode(%d)", mode);
1494 return BAD_VALUE;
1495 }
1496
1497 { // scope for the lock
1498 audio_utils::lock_guard lock(hardwareMutex());
1499 if (mPrimaryHardwareDev == nullptr) {
1500 return INVALID_OPERATION;
1501 }
1502 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
1503 mHardwareStatus = AUDIO_HW_SET_MODE;
1504 ret = dev->setMode(mode);
1505 mHardwareStatus = AUDIO_HW_IDLE;
1506 }
1507
1508 if (NO_ERROR == ret) {
1509 audio_utils::lock_guard _l(mutex());
1510 mMode = mode;
1511 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1512 mPlaybackThreads.valueAt(i)->setMode(mode);
1513 }
1514 }
1515
1516 mediametrics::LogItem(mMetricsId)
1517 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETMODE)
1518 .set(AMEDIAMETRICS_PROP_AUDIOMODE, toString(mode))
1519 .record();
1520 return ret;
1521 }
1522
setMicMute(bool state)1523 status_t AudioFlinger::setMicMute(bool state)
1524 {
1525 status_t ret = initCheck();
1526 if (ret != NO_ERROR) {
1527 return ret;
1528 }
1529
1530 // check calling permissions
1531 if (!settingsAllowed()) {
1532 return PERMISSION_DENIED;
1533 }
1534
1535 audio_utils::lock_guard lock(hardwareMutex());
1536 if (mPrimaryHardwareDev == nullptr) {
1537 return INVALID_OPERATION;
1538 }
1539 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
1540 if (primaryDev == nullptr) {
1541 ALOGW("%s: no primary HAL device", __func__);
1542 return INVALID_OPERATION;
1543 }
1544 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
1545 ret = primaryDev->setMicMute(state);
1546 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1547 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1548 if (dev != primaryDev) {
1549 (void)dev->setMicMute(state);
1550 }
1551 }
1552 mHardwareStatus = AUDIO_HW_IDLE;
1553 ALOGW_IF(ret != NO_ERROR, "%s: error %d setting state to HAL", __func__, ret);
1554 return ret;
1555 }
1556
getMicMute() const1557 bool AudioFlinger::getMicMute() const
1558 {
1559 status_t ret = initCheck();
1560 if (ret != NO_ERROR) {
1561 return false;
1562 }
1563 audio_utils::lock_guard lock(hardwareMutex());
1564 if (mPrimaryHardwareDev == nullptr) {
1565 return false;
1566 }
1567 sp<DeviceHalInterface> primaryDev = mPrimaryHardwareDev.load()->hwDevice();
1568 if (primaryDev == nullptr) {
1569 ALOGW("%s: no primary HAL device", __func__);
1570 return false;
1571 }
1572 bool state;
1573 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
1574 ret = primaryDev->getMicMute(&state);
1575 mHardwareStatus = AUDIO_HW_IDLE;
1576 ALOGE_IF(ret != NO_ERROR, "%s: error %d getting state from HAL", __func__, ret);
1577 return (ret == NO_ERROR) && state;
1578 }
1579
setRecordSilenced(audio_port_handle_t portId,bool silenced)1580 void AudioFlinger::setRecordSilenced(audio_port_handle_t portId, bool silenced)
1581 {
1582 ALOGV("AudioFlinger::setRecordSilenced(portId:%d, silenced:%d)", portId, silenced);
1583
1584 audio_utils::lock_guard lock(mutex());
1585 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1586 mRecordThreads[i]->setRecordSilenced(portId, silenced);
1587 }
1588 for (size_t i = 0; i < mMmapThreads.size(); i++) {
1589 mMmapThreads[i]->setRecordSilenced(portId, silenced);
1590 }
1591 }
1592
setMasterMute(bool muted)1593 status_t AudioFlinger::setMasterMute(bool muted)
1594 {
1595 status_t ret = initCheck();
1596 if (ret != NO_ERROR) {
1597 return ret;
1598 }
1599
1600 // check calling permissions
1601 if (!settingsAllowed()) {
1602 return PERMISSION_DENIED;
1603 }
1604
1605 audio_utils::lock_guard _l(mutex());
1606 mMasterMute = muted;
1607
1608 // Set master mute in the HALs which support it.
1609 {
1610 audio_utils::lock_guard lock(hardwareMutex());
1611 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1612 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
1613
1614 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
1615 if (dev->canSetMasterMute()) {
1616 dev->hwDevice()->setMasterMute(muted);
1617 }
1618 mHardwareStatus = AUDIO_HW_IDLE;
1619 }
1620 }
1621
1622 // Now set the master mute in each playback thread. Playback threads
1623 // assigned to HALs which do not have master mute support will apply master mute
1624 // during the mix operation. Threads with HALs which do support master mute
1625 // will simply ignore the setting.
1626 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
1627 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1628 volumeInterfaces[i]->setMasterMute(muted);
1629 }
1630
1631 return NO_ERROR;
1632 }
1633
masterVolume() const1634 float AudioFlinger::masterVolume() const
1635 {
1636 audio_utils::lock_guard _l(mutex());
1637 return masterVolume_l();
1638 }
1639
getMasterBalance(float * balance) const1640 status_t AudioFlinger::getMasterBalance(float *balance) const
1641 {
1642 audio_utils::lock_guard _l(mutex());
1643 *balance = getMasterBalance_l();
1644 return NO_ERROR; // if called through binder, may return a transactional error
1645 }
1646
masterMute() const1647 bool AudioFlinger::masterMute() const
1648 {
1649 audio_utils::lock_guard _l(mutex());
1650 return masterMute_l();
1651 }
1652
masterVolume_l() const1653 float AudioFlinger::masterVolume_l() const
1654 {
1655 return mMasterVolume;
1656 }
1657
getMasterBalance_l() const1658 float AudioFlinger::getMasterBalance_l() const
1659 {
1660 return mMasterBalance;
1661 }
1662
masterMute_l() const1663 bool AudioFlinger::masterMute_l() const
1664 {
1665 return mMasterMute;
1666 }
1667
1668 /* static */
checkStreamType(audio_stream_type_t stream)1669 status_t AudioFlinger::checkStreamType(audio_stream_type_t stream)
1670 {
1671 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
1672 ALOGW("checkStreamType() invalid stream %d", stream);
1673 return BAD_VALUE;
1674 }
1675 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
1676 if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT && !isAudioServerUid(callerUid)) {
1677 ALOGW("checkStreamType() uid %d cannot use internal stream type %d", callerUid, stream);
1678 return PERMISSION_DENIED;
1679 }
1680
1681 return NO_ERROR;
1682 }
1683
setStreamVolume(audio_stream_type_t stream,float value,bool muted,audio_io_handle_t output)1684 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
1685 bool muted, audio_io_handle_t output)
1686 {
1687 // check calling permissions
1688 if (!settingsAllowed()) {
1689 return PERMISSION_DENIED;
1690 }
1691
1692 status_t status = checkStreamType(stream);
1693 if (status != NO_ERROR) {
1694 return status;
1695 }
1696 if (output == AUDIO_IO_HANDLE_NONE) {
1697 return BAD_VALUE;
1698 }
1699 LOG_ALWAYS_FATAL_IF(stream == AUDIO_STREAM_PATCH && value != 1.0f,
1700 "AUDIO_STREAM_PATCH must have full scale volume");
1701
1702 audio_utils::lock_guard lock(mutex());
1703 sp<VolumeInterface> volumeInterface = getVolumeInterface_l(output);
1704 if (volumeInterface == NULL) {
1705 return BAD_VALUE;
1706 }
1707 volumeInterface->setStreamVolume(stream, value, muted);
1708
1709 return NO_ERROR;
1710 }
1711
setPortsVolume(const std::vector<audio_port_handle_t> & ports,float volume,bool muted,audio_io_handle_t output)1712 status_t AudioFlinger::setPortsVolume(
1713 const std::vector<audio_port_handle_t> &ports, float volume, bool muted,
1714 audio_io_handle_t output) {
1715 for (const auto& port : ports) {
1716 if (port == AUDIO_PORT_HANDLE_NONE) {
1717 return BAD_VALUE;
1718 }
1719 }
1720 if (isnan(volume) || volume > 1.0f || volume < 0.0f) {
1721 return BAD_VALUE;
1722 }
1723 if (output == AUDIO_IO_HANDLE_NONE) {
1724 return BAD_VALUE;
1725 }
1726 audio_utils::lock_guard lock(mutex());
1727 IAfPlaybackThread *thread = checkPlaybackThread_l(output);
1728 if (thread != nullptr) {
1729 return thread->setPortsVolume(ports, volume, muted);
1730 }
1731 const sp<IAfMmapThread> mmapThread = checkMmapThread_l(output);
1732 if (mmapThread != nullptr && mmapThread->isOutput()) {
1733 IAfMmapPlaybackThread *mmapPlaybackThread = mmapThread->asIAfMmapPlaybackThread().get();
1734 return mmapPlaybackThread->setPortsVolume(ports, volume, muted);
1735 }
1736 return BAD_VALUE;
1737 }
1738
setRequestedLatencyMode(audio_io_handle_t output,audio_latency_mode_t mode)1739 status_t AudioFlinger::setRequestedLatencyMode(
1740 audio_io_handle_t output, audio_latency_mode_t mode) {
1741 if (output == AUDIO_IO_HANDLE_NONE) {
1742 return BAD_VALUE;
1743 }
1744 audio_utils::lock_guard lock(mutex());
1745 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
1746 if (thread == nullptr) {
1747 return BAD_VALUE;
1748 }
1749 return thread->setRequestedLatencyMode(mode);
1750 }
1751
getSupportedLatencyModes(audio_io_handle_t output,std::vector<audio_latency_mode_t> * modes) const1752 status_t AudioFlinger::getSupportedLatencyModes(audio_io_handle_t output,
1753 std::vector<audio_latency_mode_t>* modes) const {
1754 if (output == AUDIO_IO_HANDLE_NONE) {
1755 return BAD_VALUE;
1756 }
1757 audio_utils::lock_guard lock(mutex());
1758 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
1759 if (thread == nullptr) {
1760 return BAD_VALUE;
1761 }
1762 return thread->getSupportedLatencyModes(modes);
1763 }
1764
setBluetoothVariableLatencyEnabled(bool enabled)1765 status_t AudioFlinger::setBluetoothVariableLatencyEnabled(bool enabled) {
1766 audio_utils::lock_guard _l(mutex());
1767 status_t status = INVALID_OPERATION;
1768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1769 // Success if at least one PlaybackThread supports Bluetooth latency modes
1770 if (mPlaybackThreads.valueAt(i)->setBluetoothVariableLatencyEnabled(enabled) == NO_ERROR) {
1771 status = NO_ERROR;
1772 }
1773 }
1774 if (status == NO_ERROR) {
1775 mBluetoothLatencyModesEnabled.store(enabled);
1776 }
1777 return status;
1778 }
1779
isBluetoothVariableLatencyEnabled(bool * enabled) const1780 status_t AudioFlinger::isBluetoothVariableLatencyEnabled(bool* enabled) const {
1781 if (enabled == nullptr) {
1782 return BAD_VALUE;
1783 }
1784 *enabled = mBluetoothLatencyModesEnabled.load();
1785 return NO_ERROR;
1786 }
1787
supportsBluetoothVariableLatency(bool * support) const1788 status_t AudioFlinger::supportsBluetoothVariableLatency(bool* support) const {
1789 if (support == nullptr) {
1790 return BAD_VALUE;
1791 }
1792 audio_utils::lock_guard _l(hardwareMutex());
1793 *support = false;
1794 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1795 if (mAudioHwDevs.valueAt(i)->supportsBluetoothVariableLatency()) {
1796 *support = true;
1797 break;
1798 }
1799 }
1800 return NO_ERROR;
1801 }
1802
getSoundDoseInterface(const sp<media::ISoundDoseCallback> & callback,sp<media::ISoundDose> * soundDose) const1803 status_t AudioFlinger::getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback,
1804 sp<media::ISoundDose>* soundDose) const {
1805 if (soundDose == nullptr) {
1806 return BAD_VALUE;
1807 }
1808
1809 *soundDose = mMelReporter->getSoundDoseInterface(callback);
1810 return NO_ERROR;
1811 }
1812
setStreamMute(audio_stream_type_t stream,bool muted)1813 status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
1814 {
1815 // check calling permissions
1816 if (!settingsAllowed()) {
1817 return PERMISSION_DENIED;
1818 }
1819
1820 status_t status = checkStreamType(stream);
1821 if (status != NO_ERROR) {
1822 return status;
1823 }
1824 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH, "attempt to mute AUDIO_STREAM_PATCH");
1825
1826 if (uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
1827 ALOGE("setStreamMute() invalid stream %d", stream);
1828 return BAD_VALUE;
1829 }
1830
1831 audio_utils::lock_guard lock(mutex());
1832 mStreamTypes[stream].mute = muted;
1833 std::vector<sp<VolumeInterface>> volumeInterfaces = getAllVolumeInterfaces_l();
1834 for (size_t i = 0; i < volumeInterfaces.size(); i++) {
1835 volumeInterfaces[i]->setStreamMute(stream, muted);
1836 }
1837
1838 return NO_ERROR;
1839 }
1840
broadcastParametersToRecordThreads_l(const String8 & keyValuePairs)1841 void AudioFlinger::broadcastParametersToRecordThreads_l(const String8& keyValuePairs)
1842 {
1843 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1844 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
1845 }
1846 }
1847
updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector & devices)1848 void AudioFlinger::updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices)
1849 {
1850 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1851 mRecordThreads.valueAt(i)->updateOutDevices(devices);
1852 }
1853 }
1854
1855 // forwardAudioHwSyncToDownstreamPatches_l() must be called with AudioFlinger::mutex() held
forwardParametersToDownstreamPatches_l(audio_io_handle_t upStream,const String8 & keyValuePairs,const std::function<bool (const sp<IAfPlaybackThread> &)> & useThread)1856 void AudioFlinger::forwardParametersToDownstreamPatches_l(
1857 audio_io_handle_t upStream, const String8& keyValuePairs,
1858 const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread)
1859 {
1860 std::vector<SoftwarePatch> swPatches;
1861 if (mPatchPanel->getDownstreamSoftwarePatches(upStream, &swPatches) != OK) return;
1862 ALOGV_IF(!swPatches.empty(), "%s found %zu downstream patches for stream ID %d",
1863 __func__, swPatches.size(), upStream);
1864 for (const auto& swPatch : swPatches) {
1865 const sp<IAfPlaybackThread> downStream =
1866 checkPlaybackThread_l(swPatch.getPlaybackThreadHandle());
1867 if (downStream != NULL && (useThread == nullptr || useThread(downStream))) {
1868 downStream->setParameters(keyValuePairs);
1869 }
1870 }
1871 }
1872
1873 // Update downstream patches for all playback threads attached to an MSD module
updateDownStreamPatches_l(const struct audio_patch * patch,const std::set<audio_io_handle_t> & streams)1874 void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
1875 const std::set<audio_io_handle_t>& streams)
1876 {
1877 for (const audio_io_handle_t stream : streams) {
1878 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(stream);
1879 if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
1880 continue;
1881 }
1882 playbackThread->setDownStreamPatch(patch);
1883 playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
1884 }
1885 }
1886
1887 // Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
1888 // Some keys are used for audio routing and audio path configuration and should be reserved for use
1889 // by audio policy and audio flinger for functional, privacy and security reasons.
filterReservedParameters(String8 & keyValuePairs,uid_t callingUid)1890 void AudioFlinger::filterReservedParameters(String8& keyValuePairs, uid_t callingUid)
1891 {
1892 static const String8 kReservedParameters[] = {
1893 String8(AudioParameter::keyRouting),
1894 String8(AudioParameter::keySamplingRate),
1895 String8(AudioParameter::keyFormat),
1896 String8(AudioParameter::keyChannels),
1897 String8(AudioParameter::keyFrameCount),
1898 String8(AudioParameter::keyInputSource),
1899 String8(AudioParameter::keyMonoOutput),
1900 String8(AudioParameter::keyDeviceConnect),
1901 String8(AudioParameter::keyDeviceDisconnect),
1902 String8(AudioParameter::keyStreamSupportedFormats),
1903 String8(AudioParameter::keyStreamSupportedChannels),
1904 String8(AudioParameter::keyStreamSupportedSamplingRates),
1905 String8(AudioParameter::keyClosing),
1906 String8(AudioParameter::keyExiting),
1907 };
1908
1909 if (isAudioServerUid(callingUid)) {
1910 return; // no need to filter if audioserver.
1911 }
1912
1913 AudioParameter param = AudioParameter(keyValuePairs);
1914 String8 value;
1915 AudioParameter rejectedParam;
1916 for (auto& key : kReservedParameters) {
1917 if (param.get(key, value) == NO_ERROR) {
1918 rejectedParam.add(key, value);
1919 param.remove(key);
1920 }
1921 }
1922 logFilteredParameters(param.size() + rejectedParam.size(), keyValuePairs,
1923 rejectedParam.size(), rejectedParam.toString(), callingUid);
1924 keyValuePairs = param.toString();
1925 }
1926
logFilteredParameters(size_t originalKVPSize,const String8 & originalKVPs,size_t rejectedKVPSize,const String8 & rejectedKVPs,uid_t callingUid)1927 void AudioFlinger::logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs,
1928 size_t rejectedKVPSize, const String8& rejectedKVPs,
1929 uid_t callingUid) {
1930 auto prefix = String8::format("UID %5d", callingUid);
1931 auto suffix = String8::format("%zu KVP received: %s", originalKVPSize, originalKVPs.c_str());
1932 if (rejectedKVPSize != 0) {
1933 auto error = String8::format("%zu KVP rejected: %s", rejectedKVPSize, rejectedKVPs.c_str());
1934 ALOGW("%s: %s, %s, %s", __func__, prefix.c_str(), error.c_str(), suffix.c_str());
1935 mRejectedSetParameterLog.log("%s, %s, %s", prefix.c_str(), error.c_str(), suffix.c_str());
1936 } else {
1937 auto& logger = (isServiceUid(callingUid) ? mSystemSetParameterLog : mAppSetParameterLog);
1938 logger.log("%s, %s", prefix.c_str(), suffix.c_str());
1939 }
1940 }
1941
setParameters(audio_io_handle_t ioHandle,const String8 & keyValuePairs)1942 status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
1943 {
1944 ALOGV("setParameters(): io %d, keyvalue %s, calling pid %d calling uid %d",
1945 ioHandle, keyValuePairs.c_str(),
1946 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1947
1948 // check calling permissions
1949 if (!settingsAllowed()) {
1950 return PERMISSION_DENIED;
1951 }
1952
1953 String8 filteredKeyValuePairs = keyValuePairs;
1954 filterReservedParameters(filteredKeyValuePairs, IPCThreadState::self()->getCallingUid());
1955
1956 ALOGV("%s: filtered keyvalue %s", __func__, filteredKeyValuePairs.c_str());
1957
1958 // AUDIO_IO_HANDLE_NONE means the parameters are global to the audio hardware interface
1959 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
1960 audio_utils::lock_guard _l(mutex());
1961 // result will remain NO_INIT if no audio device is present
1962 status_t final_result = NO_INIT;
1963 {
1964 audio_utils::lock_guard lock(hardwareMutex());
1965 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
1966 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
1967 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
1968 status_t result = dev->setParameters(filteredKeyValuePairs);
1969 // return success if at least one audio device accepts the parameters as not all
1970 // HALs are requested to support all parameters. If no audio device supports the
1971 // requested parameters, the last error is reported.
1972 if (final_result != NO_ERROR) {
1973 final_result = result;
1974 }
1975 }
1976 mHardwareStatus = AUDIO_HW_IDLE;
1977 }
1978 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
1979 AudioParameter param = AudioParameter(filteredKeyValuePairs);
1980 String8 value;
1981 if (param.get(String8(AudioParameter::keyBtNrec), value) == NO_ERROR) {
1982 bool btNrecIsOff = (value == AudioParameter::valueOff);
1983 if (mBtNrecIsOff.exchange(btNrecIsOff) != btNrecIsOff) {
1984 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1985 mRecordThreads.valueAt(i)->checkBtNrec();
1986 }
1987 }
1988 }
1989 String8 screenState;
1990 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
1991 bool isOff = (screenState == AudioParameter::valueOff);
1992 if (isOff != (mScreenState & 1)) {
1993 mScreenState = ((mScreenState & ~1) + 2) | isOff;
1994 }
1995 }
1996 return final_result;
1997 }
1998
1999 // hold a strong ref on thread in case closeOutput() or closeInput() is called
2000 // and the thread is exited once the lock is released
2001 sp<IAfThreadBase> thread;
2002 {
2003 audio_utils::lock_guard _l(mutex());
2004 thread = checkPlaybackThread_l(ioHandle);
2005 if (thread == 0) {
2006 thread = checkRecordThread_l(ioHandle);
2007 if (thread == 0) {
2008 thread = checkMmapThread_l(ioHandle);
2009 }
2010 } else if (thread == primaryPlaybackThread_l()) {
2011 // indicate output device change to all input threads for pre processing
2012 AudioParameter param = AudioParameter(filteredKeyValuePairs);
2013 int value;
2014 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
2015 (value != 0)) {
2016 broadcastParametersToRecordThreads_l(filteredKeyValuePairs);
2017 }
2018 }
2019 }
2020 if (thread != 0) {
2021 status_t result = thread->setParameters(filteredKeyValuePairs);
2022 audio_utils::lock_guard _l(mutex());
2023 forwardParametersToDownstreamPatches_l(thread->id(), filteredKeyValuePairs);
2024 return result;
2025 }
2026 return BAD_VALUE;
2027 }
2028
getParameters(audio_io_handle_t ioHandle,const String8 & keys) const2029 String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
2030 {
2031 ALOGVV("getParameters() io %d, keys %s, calling pid %d",
2032 ioHandle, keys.c_str(), IPCThreadState::self()->getCallingPid());
2033
2034 audio_utils::lock_guard _l(mutex());
2035
2036 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
2037 String8 out_s8;
2038
2039 audio_utils::lock_guard lock(hardwareMutex());
2040 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2041 String8 s;
2042 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
2043 sp<DeviceHalInterface> dev = mAudioHwDevs.valueAt(i)->hwDevice();
2044 status_t result = dev->getParameters(keys, &s);
2045 mHardwareStatus = AUDIO_HW_IDLE;
2046 if (result == OK) out_s8 += s;
2047 }
2048 return out_s8;
2049 }
2050
2051 IAfThreadBase* thread = checkPlaybackThread_l(ioHandle);
2052 if (thread == NULL) {
2053 thread = checkRecordThread_l(ioHandle);
2054 if (thread == NULL) {
2055 thread = checkMmapThread_l(ioHandle);
2056 if (thread == NULL) {
2057 return String8("");
2058 }
2059 }
2060 }
2061 return thread->getParameters(keys);
2062 }
2063
getInputBufferSize(uint32_t sampleRate,audio_format_t format,audio_channel_mask_t channelMask) const2064 size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
2065 audio_channel_mask_t channelMask) const
2066 {
2067 status_t ret = initCheck();
2068 if (ret != NO_ERROR) {
2069 return 0;
2070 }
2071 if ((sampleRate == 0) ||
2072 !audio_is_valid_format(format) ||
2073 !audio_is_input_channel(channelMask)) {
2074 return 0;
2075 }
2076
2077 audio_utils::lock_guard lock(hardwareMutex());
2078 if (mPrimaryHardwareDev == nullptr) {
2079 return 0;
2080 }
2081 if (mInputBufferSizeOrderedDevs.empty()) {
2082 return 0;
2083 }
2084 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
2085
2086 std::vector<audio_channel_mask_t> channelMasks = {channelMask};
2087 if (channelMask != AUDIO_CHANNEL_IN_MONO) {
2088 channelMasks.push_back(AUDIO_CHANNEL_IN_MONO);
2089 }
2090 if (channelMask != AUDIO_CHANNEL_IN_STEREO) {
2091 channelMasks.push_back(AUDIO_CHANNEL_IN_STEREO);
2092 }
2093
2094 std::vector<audio_format_t> formats = {format};
2095 if (format != AUDIO_FORMAT_PCM_16_BIT) {
2096 // For compressed format, buffer size may be queried using PCM. Allow this for compatibility
2097 // in cases the primary hw dev does not support the format.
2098 // TODO: replace with a table of formats and nominal buffer sizes (based on nominal bitrate
2099 // and codec frame size).
2100 formats.push_back(AUDIO_FORMAT_PCM_16_BIT);
2101 }
2102
2103 std::vector<uint32_t> sampleRates = {sampleRate};
2104 static const uint32_t SR_44100 = 44100;
2105 static const uint32_t SR_48000 = 48000;
2106 if (sampleRate != SR_48000) {
2107 sampleRates.push_back(SR_48000);
2108 }
2109 if (sampleRate != SR_44100) {
2110 sampleRates.push_back(SR_44100);
2111 }
2112
2113 mHardwareStatus = AUDIO_HW_IDLE;
2114
2115 auto getInputBufferSize = [](const sp<DeviceHalInterface>& dev, audio_config_t config,
2116 size_t* bytes) -> status_t {
2117 if (!dev) {
2118 return BAD_VALUE;
2119 }
2120 status_t result = dev->getInputBufferSize(&config, bytes);
2121 if (result == BAD_VALUE) {
2122 // Retry with the config suggested by the HAL.
2123 result = dev->getInputBufferSize(&config, bytes);
2124 }
2125 if (result != OK || *bytes == 0) {
2126 return BAD_VALUE;
2127 }
2128 return result;
2129 };
2130
2131 // Change parameters of the configuration each iteration until we find a
2132 // configuration that the device will support, or HAL suggests what it supports.
2133 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2134 for (auto testChannelMask : channelMasks) {
2135 config.channel_mask = testChannelMask;
2136 for (auto testFormat : formats) {
2137 config.format = testFormat;
2138 for (auto testSampleRate : sampleRates) {
2139 config.sample_rate = testSampleRate;
2140
2141 size_t bytes = 0;
2142 ret = BAD_VALUE;
2143 for (const AudioHwDevice* dev : mInputBufferSizeOrderedDevs) {
2144 ret = getInputBufferSize(dev->hwDevice(), config, &bytes);
2145 if (ret == OK) {
2146 break;
2147 }
2148 }
2149 if (ret == BAD_VALUE) continue;
2150
2151 if (config.sample_rate != sampleRate || config.channel_mask != channelMask ||
2152 config.format != format) {
2153 uint32_t dstChannelCount = audio_channel_count_from_in_mask(channelMask);
2154 uint32_t srcChannelCount =
2155 audio_channel_count_from_in_mask(config.channel_mask);
2156 size_t srcFrames =
2157 bytes / audio_bytes_per_frame(srcChannelCount, config.format);
2158 size_t dstFrames = destinationFramesPossible(
2159 srcFrames, config.sample_rate, sampleRate);
2160 bytes = dstFrames * audio_bytes_per_frame(dstChannelCount, format);
2161 }
2162 return bytes;
2163 }
2164 }
2165 }
2166
2167 ALOGW("getInputBufferSize failed with minimum buffer size sampleRate %u, "
2168 "format %#x, channelMask %#x",sampleRate, format, channelMask);
2169 return 0;
2170 }
2171
getInputFramesLost(audio_io_handle_t ioHandle) const2172 uint32_t AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
2173 {
2174 audio_utils::lock_guard _l(mutex());
2175
2176 IAfRecordThread* const recordThread = checkRecordThread_l(ioHandle);
2177 if (recordThread != NULL) {
2178 return recordThread->getInputFramesLost();
2179 }
2180 return 0;
2181 }
2182
setVoiceVolume(float value)2183 status_t AudioFlinger::setVoiceVolume(float value)
2184 {
2185 status_t ret = initCheck();
2186 if (ret != NO_ERROR) {
2187 return ret;
2188 }
2189
2190 // check calling permissions
2191 if (!settingsAllowed()) {
2192 return PERMISSION_DENIED;
2193 }
2194
2195 audio_utils::lock_guard lock(hardwareMutex());
2196 if (mPrimaryHardwareDev == nullptr) {
2197 return INVALID_OPERATION;
2198 }
2199 sp<DeviceHalInterface> dev = mPrimaryHardwareDev.load()->hwDevice();
2200 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
2201 ret = dev->setVoiceVolume(value);
2202 mHardwareStatus = AUDIO_HW_IDLE;
2203
2204 mediametrics::LogItem(mMetricsId)
2205 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_SETVOICEVOLUME)
2206 .set(AMEDIAMETRICS_PROP_VOICEVOLUME, (double)value)
2207 .record();
2208 return ret;
2209 }
2210
getRenderPosition(uint32_t * halFrames,uint32_t * dspFrames,audio_io_handle_t output) const2211 status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
2212 audio_io_handle_t output) const
2213 {
2214 audio_utils::lock_guard _l(mutex());
2215
2216 IAfPlaybackThread* const playbackThread = checkPlaybackThread_l(output);
2217 if (playbackThread != NULL) {
2218 return playbackThread->getRenderPosition(halFrames, dspFrames);
2219 }
2220
2221 return BAD_VALUE;
2222 }
2223
registerClient(const sp<media::IAudioFlingerClient> & client)2224 void AudioFlinger::registerClient(const sp<media::IAudioFlingerClient>& client)
2225 {
2226 if (client == 0) {
2227 return;
2228 }
2229 const pid_t pid = IPCThreadState::self()->getCallingPid();
2230 const uid_t uid = IPCThreadState::self()->getCallingUid();
2231
2232 audio_utils::lock_guard _l(mutex());
2233 {
2234 audio_utils::lock_guard _cl(clientMutex());
2235 if (mNotificationClients.count(pid) == 0) {
2236 auto notificationClient = sp<NotificationClient>::make(
2237 this, client, pid, uid);
2238 ALOGV("registerClient() client %p, pid %d, uid %u",
2239 notificationClient.get(), pid, uid);
2240
2241 mNotificationClients[pid] = notificationClient;
2242 sp<IBinder> binder = IInterface::asBinder(client);
2243 binder->linkToDeath(notificationClient);
2244 }
2245 }
2246
2247 // clientMutex() should not be held here because ThreadBase::sendIoConfigEvent()
2248 // will lock the ThreadBase::mutex() and the locking order is
2249 // ThreadBase::mutex() then AudioFlinger::clientMutex().
2250 // The config change is always sent from playback or record threads to avoid deadlock
2251 // with AudioSystem::gLock
2252 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2253 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AUDIO_OUTPUT_REGISTERED, pid);
2254 }
2255
2256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2257 mRecordThreads.valueAt(i)->sendIoConfigEvent(AUDIO_INPUT_REGISTERED, pid);
2258 }
2259 }
2260
removeNotificationClient(pid_t pid)2261 void AudioFlinger::removeNotificationClient(pid_t pid)
2262 {
2263 std::vector<sp<IAfEffectModule>> removedEffects;
2264 {
2265 audio_utils::lock_guard _l(mutex());
2266 {
2267 audio_utils::lock_guard _cl(clientMutex());
2268 mNotificationClients.erase(pid);
2269 }
2270
2271 ALOGV("%d died, releasing its sessions", pid);
2272 size_t num = mAudioSessionRefs.size();
2273 bool removed = false;
2274 for (size_t i = 0; i < num; ) {
2275 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
2276 ALOGV(" pid %d @ %zu", ref->mPid, i);
2277 if (ref->mPid == pid) {
2278 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
2279 mAudioSessionRefs.removeAt(i);
2280 delete ref;
2281 removed = true;
2282 num--;
2283 } else {
2284 i++;
2285 }
2286 }
2287 if (removed) {
2288 removedEffects = purgeStaleEffects_l();
2289 std::vector< sp<IAfEffectModule> > removedOrphanEffects = purgeOrphanEffectChains_l();
2290 removedEffects.insert(removedEffects.end(), removedOrphanEffects.begin(),
2291 removedOrphanEffects.end());
2292 }
2293 }
2294 for (auto& effect : removedEffects) {
2295 effect->updatePolicyState();
2296 }
2297 }
2298
2299 // Hold either AudioFlinger::mutex or ThreadBase::mutex
ioConfigChanged_l(audio_io_config_event_t event,const sp<AudioIoDescriptor> & ioDesc,pid_t pid)2300 void AudioFlinger::ioConfigChanged_l(audio_io_config_event_t event,
2301 const sp<AudioIoDescriptor>& ioDesc,
2302 pid_t pid) {
2303 media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL(
2304 legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event));
2305 media::AudioIoDescriptor descAidl = VALUE_OR_FATAL(
2306 legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc));
2307
2308 audio_utils::lock_guard _l(clientMutex());
2309 if (pid != 0) {
2310 if (auto it = mNotificationClients.find(pid); it != mNotificationClients.end()) {
2311 it->second->audioFlingerClient()->ioConfigChanged(eventAidl, descAidl);
2312 }
2313 } else {
2314 for (const auto& [ client_pid, client] : mNotificationClients) {
2315 client->audioFlingerClient()->ioConfigChanged(eventAidl, descAidl);
2316 }
2317 }
2318 }
2319
onSupportedLatencyModesChanged(audio_io_handle_t output,const std::vector<audio_latency_mode_t> & modes)2320 void AudioFlinger::onSupportedLatencyModesChanged(
2321 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) {
2322 int32_t outputAidl = VALUE_OR_FATAL(legacy2aidl_audio_io_handle_t_int32_t(output));
2323 std::vector<media::audio::common::AudioLatencyMode> modesAidl = VALUE_OR_FATAL(
2324 convertContainer<std::vector<media::audio::common::AudioLatencyMode>>(
2325 modes, legacy2aidl_audio_latency_mode_t_AudioLatencyMode));
2326
2327 audio_utils::lock_guard _l(clientMutex());
2328 size_t size = mNotificationClients.size();
2329 for (const auto& [_, client] : mNotificationClients) {
2330 client->audioFlingerClient()->onSupportedLatencyModesChanged(outputAidl, modesAidl);
2331 }
2332 }
2333
onHardError(std::set<audio_port_handle_t> & trackPortIds)2334 void AudioFlinger::onHardError(std::set<audio_port_handle_t>& trackPortIds) {
2335 ALOGI("releasing tracks due to a hard error occurred on an I/O thread");
2336 for (const auto portId : trackPortIds) {
2337 AudioSystem::releaseOutput(portId);
2338 }
2339 }
2340
getPermissionProvider()2341 const IPermissionProvider& AudioFlinger::getPermissionProvider() {
2342 // This is inited as part of service construction, prior to binder registration,
2343 // so it should always be non-null.
2344 return mAudioPolicyServiceLocal.load()->getPermissionProvider();
2345 }
2346
2347 // removeClient_l() must be called with AudioFlinger::clientMutex() held
removeClient_l(pid_t pid)2348 void AudioFlinger::removeClient_l(pid_t pid)
2349 {
2350 ALOGV("removeClient_l() pid %d, calling pid %d", pid,
2351 IPCThreadState::self()->getCallingPid());
2352 mClients.removeItem(pid);
2353 }
2354
2355 // getEffectThread_l() must be called with AudioFlinger::mutex() held
getEffectThread_l(audio_session_t sessionId,int effectId)2356 sp<IAfThreadBase> AudioFlinger::getEffectThread_l(audio_session_t sessionId,
2357 int effectId)
2358 {
2359 sp<IAfThreadBase> thread;
2360
2361 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2362 thread = mPlaybackThreads.valueAt(i);
2363 if (thread->getEffect(sessionId, effectId) != 0) {
2364 return thread;
2365 }
2366 }
2367 for (size_t i = 0; i < mRecordThreads.size(); i++) {
2368 thread = mRecordThreads.valueAt(i);
2369 if (thread->getEffect(sessionId, effectId) != 0) {
2370 return thread;
2371 }
2372 }
2373 for (size_t i = 0; i < mMmapThreads.size(); i++) {
2374 thread = mMmapThreads.valueAt(i);
2375 if (thread->getEffect(sessionId, effectId) != 0) {
2376 return thread;
2377 }
2378 }
2379 return nullptr;
2380 }
2381
2382 // ----------------------------------------------------------------------------
2383
NotificationClient(const sp<AudioFlinger> & audioFlinger,const sp<media::IAudioFlingerClient> & client,pid_t pid,uid_t uid)2384 AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
2385 const sp<media::IAudioFlingerClient>& client,
2386 pid_t pid,
2387 uid_t uid)
2388 : mAudioFlinger(audioFlinger), mPid(pid), mUid(uid), mAudioFlingerClient(client)
2389 , mClientToken(media::psh_utils::AudioPowerManager::enabled()
2390 ? media::psh_utils::createAudioClientToken(pid, uid)
2391 : nullptr)
2392 {
2393 }
2394
~NotificationClient()2395 AudioFlinger::NotificationClient::~NotificationClient()
2396 {
2397 }
2398
binderDied(const wp<IBinder> & who __unused)2399 void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who __unused)
2400 {
2401 const auto keep = sp<NotificationClient>::fromExisting(this);
2402 mAudioFlinger->removeNotificationClient(mPid);
2403 }
2404
2405 // ----------------------------------------------------------------------------
MediaLogNotifier()2406 AudioFlinger::MediaLogNotifier::MediaLogNotifier()
2407 : mPendingRequests(false) {}
2408
2409
requestMerge()2410 void AudioFlinger::MediaLogNotifier::requestMerge() {
2411 audio_utils::lock_guard _l(mMutex);
2412 mPendingRequests = true;
2413 mCondition.notify_one();
2414 }
2415
threadLoop()2416 bool AudioFlinger::MediaLogNotifier::threadLoop() {
2417 // Should already have been checked, but just in case
2418 if (sMediaLogService == 0) {
2419 return false;
2420 }
2421 // Wait until there are pending requests
2422 {
2423 audio_utils::unique_lock _l(mMutex);
2424 mPendingRequests = false; // to ignore past requests
2425 while (!mPendingRequests) {
2426 mCondition.wait(_l);
2427 // TODO may also need an exitPending check
2428 }
2429 mPendingRequests = false;
2430 }
2431 // Execute the actual MediaLogService binder call and ignore extra requests for a while
2432 sMediaLogService->requestMergeWakeup();
2433 usleep(kPostTriggerSleepPeriod);
2434 return true;
2435 }
2436
requestLogMerge()2437 void AudioFlinger::requestLogMerge() {
2438 mMediaLogNotifier->requestMerge();
2439 }
2440
2441 // ----------------------------------------------------------------------------
2442
createRecord(const media::CreateRecordRequest & _input,media::CreateRecordResponse & _output)2443 status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input,
2444 media::CreateRecordResponse& _output)
2445 {
2446 CreateRecordInput input = VALUE_OR_RETURN_STATUS(CreateRecordInput::fromAidl(_input));
2447 CreateRecordOutput output;
2448
2449 sp<IAfRecordTrack> recordTrack;
2450 sp<Client> client;
2451 status_t lStatus;
2452 audio_session_t sessionId = input.sessionId;
2453 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
2454
2455 output.cblk.clear();
2456 output.buffers.clear();
2457 output.inputId = AUDIO_IO_HANDLE_NONE;
2458
2459 AttributionSourceState adjAttributionSource;
2460 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2461 if (!com::android::media::audio::audioserver_permissions()) {
2462 adjAttributionSource = input.clientInfo.attributionSource;
2463 bool updatePid = (adjAttributionSource.pid == -1);
2464 const uid_t callingUid = IPCThreadState::self()->getCallingUid();
2465 const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(
2466 adjAttributionSource.uid));
2467 if (!isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
2468 ALOGW_IF(currentUid != callingUid,
2469 "%s uid %d tried to pass itself off as %d",
2470 __FUNCTION__, callingUid, currentUid);
2471 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(
2472 legacy2aidl_uid_t_int32_t(callingUid));
2473 updatePid = true;
2474 }
2475 const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(
2476 adjAttributionSource.pid));
2477 if (updatePid) {
2478 ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid,
2479 "%s uid %d pid %d tried to pass itself off as pid %d",
2480 __func__, callingUid, callingPid, currentPid);
2481 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
2482 legacy2aidl_pid_t_int32_t(callingPid));
2483 }
2484 adjAttributionSource = afutils::checkAttributionSourcePackage(
2485 adjAttributionSource);
2486 } else {
2487 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
2488 validateAttributionFromContextOrTrustedCaller(
2489 input.clientInfo.attributionSource,
2490 getPermissionProvider()
2491 ));
2492 // TODO pass wrapped object around
2493 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
2494 }
2495
2496 // further format checks are performed by createRecordTrack_l()
2497 if (!audio_is_valid_format(input.config.format)) {
2498 ALOGE("createRecord() invalid format %#x", input.config.format);
2499 lStatus = BAD_VALUE;
2500 goto Exit;
2501 }
2502
2503 // further channel mask checks are performed by createRecordTrack_l()
2504 if (!audio_is_input_channel(input.config.channel_mask)) {
2505 ALOGE("createRecord() invalid channel mask %#x", input.config.channel_mask);
2506 lStatus = BAD_VALUE;
2507 goto Exit;
2508 }
2509
2510 if (sessionId == AUDIO_SESSION_ALLOCATE) {
2511 sessionId = (audio_session_t) newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2512 } else if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
2513 lStatus = BAD_VALUE;
2514 goto Exit;
2515 }
2516
2517 output.sessionId = sessionId;
2518 output.selectedDeviceId = input.selectedDeviceId;
2519 output.flags = input.flags;
2520
2521 client = registerClient(adjAttributionSource.pid, adjAttributionSource.uid);
2522
2523 // Not a conventional loop, but a retry loop for at most two iterations total.
2524 // Try first maybe with FAST flag then try again without FAST flag if that fails.
2525 // Exits loop via break on no error of got exit on error
2526 // The sp<> references will be dropped when re-entering scope.
2527 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2528 for (;;) {
2529 // release previously opened input if retrying.
2530 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2531 recordTrack.clear();
2532 AudioSystem::releaseInput(portId);
2533 output.inputId = AUDIO_IO_HANDLE_NONE;
2534 output.selectedDeviceId = input.selectedDeviceId;
2535 portId = AUDIO_PORT_HANDLE_NONE;
2536 }
2537 lStatus = AudioSystem::getInputForAttr(&input.attr, &output.inputId,
2538 input.riid,
2539 sessionId,
2540 // FIXME compare to AudioTrack
2541 adjAttributionSource,
2542 &input.config,
2543 output.flags, &output.selectedDeviceId, &portId);
2544 if (lStatus != NO_ERROR) {
2545 ALOGE("createRecord() getInputForAttr return error %d", lStatus);
2546 goto Exit;
2547 }
2548
2549 {
2550 audio_utils::lock_guard _l(mutex());
2551 IAfRecordThread* const thread = checkRecordThread_l(output.inputId);
2552 if (thread == NULL) {
2553 ALOGW("createRecord() checkRecordThread_l failed, input handle %d", output.inputId);
2554 lStatus = FAILED_TRANSACTION;
2555 goto Exit;
2556 }
2557
2558 ALOGV("createRecord() lSessionId: %d input %d", sessionId, output.inputId);
2559
2560 output.sampleRate = input.config.sample_rate;
2561 output.frameCount = input.frameCount;
2562 output.notificationFrameCount = input.notificationFrameCount;
2563
2564 recordTrack = thread->createRecordTrack_l(client, input.attr, &output.sampleRate,
2565 input.config.format, input.config.channel_mask,
2566 &output.frameCount, sessionId,
2567 &output.notificationFrameCount,
2568 callingPid, adjAttributionSource, &output.flags,
2569 input.clientInfo.clientTid,
2570 &lStatus, portId, input.maxSharedAudioHistoryMs);
2571 LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0));
2572
2573 // lStatus == BAD_TYPE means FAST flag was rejected: request a new input from
2574 // audio policy manager without FAST constraint
2575 if (lStatus == BAD_TYPE) {
2576 continue;
2577 }
2578
2579 if (lStatus != NO_ERROR) {
2580 goto Exit;
2581 }
2582
2583 if (recordTrack->isFastTrack()) {
2584 output.serverConfig = {
2585 thread->sampleRate(),
2586 thread->channelMask(),
2587 thread->format()
2588 };
2589 } else {
2590 output.serverConfig = {
2591 recordTrack->sampleRate(),
2592 recordTrack->channelMask(),
2593 recordTrack->format()
2594 };
2595 }
2596
2597 output.halConfig = {
2598 thread->sampleRate(),
2599 thread->channelMask(),
2600 thread->format()
2601 };
2602
2603 // Check if one effect chain was awaiting for an AudioRecord to be created on this
2604 // session and move it to this thread.
2605 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
2606 if (chain != 0) {
2607 audio_utils::lock_guard _l2(thread->mutex());
2608 thread->addEffectChain_l(chain);
2609 }
2610 break;
2611 }
2612 // End of retry loop.
2613 // The lack of indentation is deliberate, to reduce code churn and ease merges.
2614 }
2615
2616 output.cblk = recordTrack->getCblk();
2617 output.buffers = recordTrack->getBuffers();
2618 output.portId = portId;
2619
2620 output.audioRecord = IAfRecordTrack::createIAudioRecordAdapter(recordTrack);
2621 _output = VALUE_OR_FATAL(output.toAidl());
2622
2623 Exit:
2624 if (lStatus != NO_ERROR) {
2625 // remove local strong reference to Client before deleting the RecordTrack so that the
2626 // Client destructor is called by the TrackBase destructor with clientMutex() held
2627 // Don't hold clientMutex() when releasing the reference on the track as the
2628 // destructor will acquire it.
2629 {
2630 audio_utils::lock_guard _cl(clientMutex());
2631 client.clear();
2632 }
2633 recordTrack.clear();
2634 if (output.inputId != AUDIO_IO_HANDLE_NONE) {
2635 AudioSystem::releaseInput(portId);
2636 }
2637 }
2638
2639 return lStatus;
2640 }
2641
2642
2643
2644 // ----------------------------------------------------------------------------
2645
getAudioPolicyConfig(media::AudioPolicyConfig * config)2646 status_t AudioFlinger::getAudioPolicyConfig(media::AudioPolicyConfig *config)
2647 {
2648 if (config == nullptr) {
2649 return BAD_VALUE;
2650 }
2651 audio_utils::lock_guard _l(mutex());
2652 audio_utils::lock_guard lock(hardwareMutex());
2653 RETURN_STATUS_IF_ERROR(
2654 mDevicesFactoryHal->getSurroundSoundConfig(&config->surroundSoundConfig));
2655 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getEngineConfig(&config->engineConfig));
2656 std::vector<std::string> hwModuleNames;
2657 RETURN_STATUS_IF_ERROR(mDevicesFactoryHal->getDeviceNames(&hwModuleNames));
2658 std::set<AudioMode> allSupportedModes;
2659 for (const auto& name : hwModuleNames) {
2660 AudioHwDevice* module = loadHwModule_ll(name.c_str());
2661 if (module == nullptr) continue;
2662 media::AudioHwModule aidlModule;
2663 if (module->hwDevice()->getAudioPorts(&aidlModule.ports) == OK &&
2664 module->hwDevice()->getAudioRoutes(&aidlModule.routes) == OK) {
2665 aidlModule.handle = module->handle();
2666 aidlModule.name = module->moduleName();
2667 config->modules.push_back(std::move(aidlModule));
2668 }
2669 std::vector<AudioMode> supportedModes;
2670 if (module->hwDevice()->getSupportedModes(&supportedModes) == OK) {
2671 allSupportedModes.insert(supportedModes.begin(), supportedModes.end());
2672 }
2673 }
2674 if (!allSupportedModes.empty()) {
2675 config->supportedModes.insert(config->supportedModes.end(),
2676 allSupportedModes.begin(), allSupportedModes.end());
2677 } else {
2678 ALOGW("%s: The HAL does not provide telephony functionality", __func__);
2679 config->supportedModes = { media::audio::common::AudioMode::NORMAL,
2680 media::audio::common::AudioMode::RINGTONE,
2681 media::audio::common::AudioMode::IN_CALL,
2682 media::audio::common::AudioMode::IN_COMMUNICATION };
2683 }
2684 return OK;
2685 }
2686
loadHwModule(const char * name)2687 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
2688 {
2689 if (name == NULL) {
2690 return AUDIO_MODULE_HANDLE_NONE;
2691 }
2692 if (!settingsAllowed()) {
2693 return AUDIO_MODULE_HANDLE_NONE;
2694 }
2695 audio_utils::lock_guard _l(mutex());
2696 audio_utils::lock_guard lock(hardwareMutex());
2697 AudioHwDevice* module = loadHwModule_ll(name);
2698 return module != nullptr ? module->handle() : AUDIO_MODULE_HANDLE_NONE;
2699 }
2700
2701 // loadHwModule_l() must be called with AudioFlinger::mutex()
2702 // and AudioFlinger::hardwareMutex() held
loadHwModule_ll(const char * name)2703 AudioHwDevice* AudioFlinger::loadHwModule_ll(const char *name)
2704 {
2705 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
2706 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
2707 ALOGW("loadHwModule() module %s already loaded", name);
2708 return mAudioHwDevs.valueAt(i);
2709 }
2710 }
2711
2712 sp<DeviceHalInterface> dev;
2713
2714 int rc = mDevicesFactoryHal->openDevice(name, &dev);
2715 if (rc) {
2716 ALOGE("loadHwModule() error %d loading module %s", rc, name);
2717 return nullptr;
2718 }
2719 if (!mMelReporter->activateHalSoundDoseComputation(name, dev)) {
2720 ALOGW("loadHwModule() sound dose reporting is not available");
2721 }
2722
2723 mHardwareStatus = AUDIO_HW_INIT;
2724 rc = dev->initCheck();
2725 mHardwareStatus = AUDIO_HW_IDLE;
2726 if (rc) {
2727 ALOGE("loadHwModule() init check error %d for module %s", rc, name);
2728 return nullptr;
2729 }
2730
2731 // Check and cache this HAL's level of support for master mute and master
2732 // volume. If this is the first HAL opened, and it supports the get
2733 // methods, use the initial values provided by the HAL as the current
2734 // master mute and volume settings.
2735
2736 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
2737 if (0 == mAudioHwDevs.size()) {
2738 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
2739 float mv;
2740 if (OK == dev->getMasterVolume(&mv)) {
2741 mMasterVolume = mv;
2742 }
2743
2744 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
2745 bool mm;
2746 if (OK == dev->getMasterMute(&mm)) {
2747 mMasterMute = mm;
2748 ALOGI_IF(mMasterMute, "%s: applying mute from HAL %s", __func__, name);
2749 }
2750 }
2751
2752 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
2753 if (OK == dev->setMasterVolume(mMasterVolume)) {
2754 flags = static_cast<AudioHwDevice::Flags>(flags |
2755 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
2756 }
2757
2758 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
2759 if (OK == dev->setMasterMute(mMasterMute)) {
2760 flags = static_cast<AudioHwDevice::Flags>(flags |
2761 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
2762 }
2763
2764 mHardwareStatus = AUDIO_HW_IDLE;
2765
2766 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
2767 // An MSD module is inserted before hardware modules in order to mix encoded streams.
2768 flags = static_cast<AudioHwDevice::Flags>(flags | AudioHwDevice::AHWD_IS_INSERT);
2769 }
2770
2771
2772 if (bool supports = false;
2773 dev->supportsBluetoothVariableLatency(&supports) == NO_ERROR && supports) {
2774 flags = static_cast<AudioHwDevice::Flags>(flags |
2775 AudioHwDevice::AHWD_SUPPORTS_BT_LATENCY_MODES);
2776 }
2777
2778 audio_module_handle_t handle = (audio_module_handle_t) nextUniqueId(AUDIO_UNIQUE_ID_USE_MODULE);
2779 AudioHwDevice *audioDevice = new AudioHwDevice(handle, name, dev, flags);
2780 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_PRIMARY) == 0) {
2781 mPrimaryHardwareDev = audioDevice;
2782 mHardwareStatus = AUDIO_HW_SET_MODE;
2783 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
2784 mHardwareStatus = AUDIO_HW_IDLE;
2785 }
2786
2787 if (mDevicesFactoryHal->getHalVersion() > kMaxAAudioPropertyDeviceHalVersion) {
2788 if (int32_t mixerBursts = dev->getAAudioMixerBurstCount();
2789 mixerBursts > 0 && mixerBursts > mAAudioBurstsPerBuffer) {
2790 mAAudioBurstsPerBuffer = mixerBursts;
2791 }
2792 if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec();
2793 hwBurstMinMicros > 0
2794 && (hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0)) {
2795 mAAudioHwBurstMinMicros = hwBurstMinMicros;
2796 }
2797 }
2798
2799 mAudioHwDevs.add(handle, audioDevice);
2800 if (strcmp(name, AUDIO_HARDWARE_MODULE_ID_STUB) != 0) {
2801 mInputBufferSizeOrderedDevs.insert(audioDevice);
2802 }
2803
2804 ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle);
2805
2806 return audioDevice;
2807 }
2808
2809 // Sort AudioHwDevice to be traversed in the getInputBufferSize call in the following order:
2810 // Primary, Usb, Bluetooth, A2DP, other modules, remote submix.
2811 /* static */
inputBufferSizeDevsCmp(const AudioHwDevice * lhs,const AudioHwDevice * rhs)2812 bool AudioFlinger::inputBufferSizeDevsCmp(const AudioHwDevice* lhs, const AudioHwDevice* rhs) {
2813 static const std::map<std::string_view, int> kPriorities = {
2814 { AUDIO_HARDWARE_MODULE_ID_PRIMARY, 0 }, { AUDIO_HARDWARE_MODULE_ID_USB, 1 },
2815 { AUDIO_HARDWARE_MODULE_ID_BLUETOOTH, 2 }, { AUDIO_HARDWARE_MODULE_ID_A2DP, 3 },
2816 { AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, std::numeric_limits<int>::max() }
2817 };
2818
2819 const std::string_view lhsName = lhs->moduleName();
2820 const std::string_view rhsName = rhs->moduleName();
2821
2822 auto lhsPriority = std::numeric_limits<int>::max() - 1;
2823 if (const auto lhsIt = kPriorities.find(lhsName); lhsIt != kPriorities.end()) {
2824 lhsPriority = lhsIt->second;
2825 }
2826 auto rhsPriority = std::numeric_limits<int>::max() - 1;
2827 if (const auto rhsIt = kPriorities.find(rhsName); rhsIt != kPriorities.end()) {
2828 rhsPriority = rhsIt->second;
2829 }
2830
2831 if (lhsPriority != rhsPriority) {
2832 return lhsPriority < rhsPriority;
2833 }
2834 return lhsName < rhsName;
2835 }
2836
2837 // ----------------------------------------------------------------------------
2838
getPrimaryOutputSamplingRate() const2839 uint32_t AudioFlinger::getPrimaryOutputSamplingRate() const
2840 {
2841 audio_utils::lock_guard _l(mutex());
2842 IAfPlaybackThread* const thread = fastPlaybackThread_l();
2843 return thread != NULL ? thread->sampleRate() : 0;
2844 }
2845
getPrimaryOutputFrameCount() const2846 size_t AudioFlinger::getPrimaryOutputFrameCount() const
2847 {
2848 audio_utils::lock_guard _l(mutex());
2849 IAfPlaybackThread* const thread = fastPlaybackThread_l();
2850 return thread != NULL ? thread->frameCountHAL() : 0;
2851 }
2852
2853 // ----------------------------------------------------------------------------
2854
setLowRamDevice(bool isLowRamDevice,int64_t totalMemory)2855 status_t AudioFlinger::setLowRamDevice(bool isLowRamDevice, int64_t totalMemory)
2856 {
2857 uid_t uid = IPCThreadState::self()->getCallingUid();
2858 if (!isAudioServerOrSystemServerUid(uid)) {
2859 return PERMISSION_DENIED;
2860 }
2861 audio_utils::lock_guard _l(mutex());
2862 if (mIsDeviceTypeKnown) {
2863 return INVALID_OPERATION;
2864 }
2865 mIsLowRamDevice = isLowRamDevice;
2866 mTotalMemory = totalMemory;
2867 // mIsLowRamDevice and mTotalMemory are obtained through ActivityManager;
2868 // see ActivityManager.isLowRamDevice() and ActivityManager.getMemoryInfo().
2869 // mIsLowRamDevice generally represent devices with less than 1GB of memory,
2870 // though actual setting is determined through device configuration.
2871 constexpr int64_t GB = 1024 * 1024 * 1024;
2872 mClientSharedHeapSize =
2873 isLowRamDevice ? kMinimumClientSharedHeapSizeBytes
2874 : mTotalMemory < 2 * GB ? 4 * kMinimumClientSharedHeapSizeBytes
2875 : mTotalMemory < 3 * GB ? 8 * kMinimumClientSharedHeapSizeBytes
2876 : mTotalMemory < 4 * GB ? 16 * kMinimumClientSharedHeapSizeBytes
2877 : 32 * kMinimumClientSharedHeapSizeBytes;
2878 mIsDeviceTypeKnown = true;
2879
2880 // TODO: Cache the client shared heap size in a persistent property.
2881 // It's possible that a native process or Java service or app accesses audioserver
2882 // after it is registered by system server, but before AudioService updates
2883 // the memory info. This would occur immediately after boot or an audioserver
2884 // crash and restore. Before update from AudioService, the client would get the
2885 // minimum heap size.
2886
2887 ALOGD("isLowRamDevice:%s totalMemory:%lld mClientSharedHeapSize:%zu",
2888 (isLowRamDevice ? "true" : "false"),
2889 (long long)mTotalMemory,
2890 mClientSharedHeapSize.load());
2891 return NO_ERROR;
2892 }
2893
getClientSharedHeapSize() const2894 size_t AudioFlinger::getClientSharedHeapSize() const
2895 {
2896 size_t heapSizeInBytes = property_get_int32("ro.af.client_heap_size_kbyte", 0) * 1024;
2897 if (heapSizeInBytes != 0) { // read-only property overrides all.
2898 return heapSizeInBytes;
2899 }
2900 return mClientSharedHeapSize;
2901 }
2902
setAudioPortConfig(const struct audio_port_config * config)2903 status_t AudioFlinger::setAudioPortConfig(const struct audio_port_config *config)
2904 {
2905 ALOGV(__func__);
2906
2907 status_t status = AudioValidator::validateAudioPortConfig(*config);
2908 if (status != NO_ERROR) {
2909 return status;
2910 }
2911
2912 audio_module_handle_t module;
2913 if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2914 module = config->ext.device.hw_module;
2915 } else {
2916 module = config->ext.mix.hw_module;
2917 }
2918
2919 audio_utils::lock_guard _l(mutex());
2920 audio_utils::lock_guard lock(hardwareMutex());
2921 ssize_t index = mAudioHwDevs.indexOfKey(module);
2922 if (index < 0) {
2923 ALOGW("%s() bad hw module %d", __func__, module);
2924 return BAD_VALUE;
2925 }
2926
2927 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(index);
2928 return audioHwDevice->hwDevice()->setAudioPortConfig(config);
2929 }
2930
getAudioHwSyncForSession(audio_session_t sessionId)2931 audio_hw_sync_t AudioFlinger::getAudioHwSyncForSession(audio_session_t sessionId)
2932 {
2933 audio_utils::lock_guard _l(mutex());
2934
2935 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
2936 if (index >= 0) {
2937 ALOGV("getAudioHwSyncForSession found ID %d for session %d",
2938 mHwAvSyncIds.valueAt(index), sessionId);
2939 return mHwAvSyncIds.valueAt(index);
2940 }
2941
2942 sp<DeviceHalInterface> dev;
2943 {
2944 audio_utils::lock_guard lock(hardwareMutex());
2945 if (mPrimaryHardwareDev == nullptr) {
2946 return AUDIO_HW_SYNC_INVALID;
2947 }
2948 dev = mPrimaryHardwareDev.load()->hwDevice();
2949 }
2950 if (dev == nullptr) {
2951 return AUDIO_HW_SYNC_INVALID;
2952 }
2953
2954 error::Result<audio_hw_sync_t> result = dev->getHwAvSync();
2955 if (!result.ok()) {
2956 ALOGW("getAudioHwSyncForSession error getting sync for session %d", sessionId);
2957 return AUDIO_HW_SYNC_INVALID;
2958 }
2959 audio_hw_sync_t value = VALUE_OR_FATAL(result);
2960
2961 // allow only one session for a given HW A/V sync ID.
2962 for (size_t i = 0; i < mHwAvSyncIds.size(); i++) {
2963 if (mHwAvSyncIds.valueAt(i) == value) {
2964 ALOGV("getAudioHwSyncForSession removing ID %d for session %d",
2965 value, mHwAvSyncIds.keyAt(i));
2966 mHwAvSyncIds.removeItemsAt(i);
2967 break;
2968 }
2969 }
2970
2971 mHwAvSyncIds.add(sessionId, value);
2972
2973 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
2974 const sp<IAfPlaybackThread> thread = mPlaybackThreads.valueAt(i);
2975 uint32_t sessions = thread->hasAudioSession(sessionId);
2976 if (sessions & IAfThreadBase::TRACK_SESSION) {
2977 AudioParameter param = AudioParameter();
2978 param.addInt(String8(AudioParameter::keyStreamHwAvSync), value);
2979 String8 keyValuePairs = param.toString();
2980 thread->setParameters(keyValuePairs);
2981 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
2982 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
2983 break;
2984 }
2985 }
2986
2987 ALOGV("getAudioHwSyncForSession adding ID %d for session %d", value, sessionId);
2988 return (audio_hw_sync_t)value;
2989 }
2990
systemReady()2991 status_t AudioFlinger::systemReady()
2992 {
2993 audio_utils::lock_guard _l(mutex());
2994 ALOGI("%s", __FUNCTION__);
2995 if (mSystemReady) {
2996 ALOGW("%s called twice", __FUNCTION__);
2997 return NO_ERROR;
2998 }
2999 mSystemReady = true;
3000 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3001 IAfThreadBase* const thread = mPlaybackThreads.valueAt(i).get();
3002 thread->systemReady();
3003 }
3004 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3005 IAfThreadBase* const thread = mRecordThreads.valueAt(i).get();
3006 thread->systemReady();
3007 }
3008 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3009 IAfThreadBase* const thread = mMmapThreads.valueAt(i).get();
3010 thread->systemReady();
3011 }
3012
3013 // Java services are ready, so we can create a reference to AudioService
3014 getOrCreateAudioManager();
3015
3016 return NO_ERROR;
3017 }
3018
getOrCreateAudioManager()3019 sp<IAudioManager> AudioFlinger::getOrCreateAudioManager()
3020 {
3021 if (mAudioManager.load() == nullptr) {
3022 // use checkService() to avoid blocking
3023 sp<IBinder> binder =
3024 defaultServiceManager()->checkService(String16(kAudioServiceName));
3025 if (binder != nullptr) {
3026 mAudioManager = interface_cast<IAudioManager>(binder);
3027 } else {
3028 ALOGE("%s(): binding to audio service failed.", __func__);
3029 }
3030 }
3031 return mAudioManager.load();
3032 }
3033
getMicrophones(std::vector<media::MicrophoneInfoFw> * microphones) const3034 status_t AudioFlinger::getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const
3035 {
3036 audio_utils::lock_guard lock(hardwareMutex());
3037 status_t status = INVALID_OPERATION;
3038
3039 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
3040 std::vector<audio_microphone_characteristic_t> mics;
3041 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
3042 mHardwareStatus = AUDIO_HW_GET_MICROPHONES;
3043 status_t devStatus = dev->hwDevice()->getMicrophones(&mics);
3044 mHardwareStatus = AUDIO_HW_IDLE;
3045 if (devStatus == NO_ERROR) {
3046 // report success if at least one HW module supports the function.
3047 std::transform(mics.begin(), mics.end(), std::back_inserter(*microphones), [](auto& mic)
3048 {
3049 auto microphone =
3050 legacy2aidl_audio_microphone_characteristic_t_MicrophoneInfoFw(mic);
3051 return microphone.ok() ? microphone.value() : media::MicrophoneInfoFw{};
3052 });
3053 status = NO_ERROR;
3054 }
3055 }
3056
3057 return status;
3058 }
3059
3060 // setAudioHwSyncForSession_l() must be called with AudioFlinger::mutex() held
setAudioHwSyncForSession_l(IAfPlaybackThread * const thread,audio_session_t sessionId)3061 void AudioFlinger::setAudioHwSyncForSession_l(
3062 IAfPlaybackThread* const thread, audio_session_t sessionId)
3063 {
3064 ssize_t index = mHwAvSyncIds.indexOfKey(sessionId);
3065 if (index >= 0) {
3066 audio_hw_sync_t syncId = mHwAvSyncIds.valueAt(index);
3067 ALOGV("setAudioHwSyncForSession_l found ID %d for session %d", syncId, sessionId);
3068 AudioParameter param = AudioParameter();
3069 param.addInt(String8(AudioParameter::keyStreamHwAvSync), syncId);
3070 String8 keyValuePairs = param.toString();
3071 thread->setParameters(keyValuePairs);
3072 forwardParametersToDownstreamPatches_l(thread->id(), keyValuePairs,
3073 [](const sp<IAfPlaybackThread>& thread) { return thread->usesHwAvSync(); });
3074 }
3075 }
3076
3077
3078 // ----------------------------------------------------------------------------
3079
3080
openOutput_l(audio_module_handle_t module,audio_io_handle_t * output,audio_config_t * halConfig,audio_config_base_t * mixerConfig,audio_devices_t deviceType,const String8 & address,audio_output_flags_t * flags,const audio_attributes_t attributes)3081 sp<IAfThreadBase> AudioFlinger::openOutput_l(audio_module_handle_t module,
3082 audio_io_handle_t *output,
3083 audio_config_t *halConfig,
3084 audio_config_base_t *mixerConfig,
3085 audio_devices_t deviceType,
3086 const String8& address,
3087 audio_output_flags_t *flags,
3088 const audio_attributes_t attributes)
3089 {
3090 AudioHwDevice *outHwDev = findSuitableHwDev_l(module, deviceType);
3091 if (outHwDev == NULL) {
3092 return nullptr;
3093 }
3094
3095 if (*output == AUDIO_IO_HANDLE_NONE) {
3096 *output = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
3097 } else {
3098 // Audio Policy does not currently request a specific output handle.
3099 // If this is ever needed, see openInput_l() for example code.
3100 ALOGE("openOutput_l requested output handle %d is not AUDIO_IO_HANDLE_NONE", *output);
3101 return nullptr;
3102 }
3103
3104 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3105 AudioStreamOut *outputStream = NULL;
3106
3107 playback_track_metadata_v7_t trackMetadata;
3108 trackMetadata.base.usage = attributes.usage;
3109
3110 status_t status = outHwDev->openOutputStream(
3111 &outputStream,
3112 *output,
3113 deviceType,
3114 flags,
3115 halConfig,
3116 address.c_str(),
3117 {trackMetadata});
3118
3119 mHardwareStatus = AUDIO_HW_IDLE;
3120
3121 if (status == NO_ERROR) {
3122 if (*flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
3123 const sp<IAfMmapPlaybackThread> thread = IAfMmapPlaybackThread::create(
3124 this, *output, outHwDev, outputStream, mSystemReady);
3125 mMmapThreads.add(*output, thread);
3126 ALOGV("openOutput_l() created mmap playback thread: ID %d thread %p",
3127 *output, thread.get());
3128 return thread;
3129 } else {
3130 sp<IAfPlaybackThread> thread;
3131 if (*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
3132 thread = IAfPlaybackThread::createBitPerfectThread(
3133 this, outputStream, *output, mSystemReady);
3134 ALOGV("%s() created bit-perfect output: ID %d thread %p",
3135 __func__, *output, thread.get());
3136 } else if (*flags & AUDIO_OUTPUT_FLAG_SPATIALIZER) {
3137 thread = IAfPlaybackThread::createSpatializerThread(this, outputStream, *output,
3138 mSystemReady, mixerConfig);
3139 ALOGV("openOutput_l() created spatializer output: ID %d thread %p",
3140 *output, thread.get());
3141 } else if (*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3142 thread = IAfPlaybackThread::createOffloadThread(this, outputStream, *output,
3143 mSystemReady, halConfig->offload_info);
3144 ALOGV("openOutput_l() created offload output: ID %d thread %p",
3145 *output, thread.get());
3146 } else if ((*flags & AUDIO_OUTPUT_FLAG_DIRECT)
3147 || !IAfThreadBase::isValidPcmSinkFormat(halConfig->format)
3148 || !IAfThreadBase::isValidPcmSinkChannelMask(halConfig->channel_mask)) {
3149 thread = IAfPlaybackThread::createDirectOutputThread(this, outputStream, *output,
3150 mSystemReady, halConfig->offload_info);
3151 ALOGV("openOutput_l() created direct output: ID %d thread %p",
3152 *output, thread.get());
3153 } else {
3154 thread = IAfPlaybackThread::createMixerThread(
3155 this, outputStream, *output, mSystemReady);
3156 ALOGV("openOutput_l() created mixer output: ID %d thread %p",
3157 *output, thread.get());
3158 }
3159 mPlaybackThreads.add(*output, thread);
3160 struct audio_patch patch;
3161 mPatchPanel->notifyStreamOpened(outHwDev, *output, &patch);
3162 if (thread->isMsdDevice()) {
3163 thread->setDownStreamPatch(&patch);
3164 }
3165 thread->setBluetoothVariableLatencyEnabled(mBluetoothLatencyModesEnabled.load());
3166 return thread;
3167 }
3168 }
3169
3170 return nullptr;
3171 }
3172
openOutput(const media::OpenOutputRequest & request,media::OpenOutputResponse * response)3173 status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request,
3174 media::OpenOutputResponse* response)
3175 {
3176 audio_module_handle_t module = VALUE_OR_RETURN_STATUS(
3177 aidl2legacy_int32_t_audio_module_handle_t(request.module));
3178 audio_config_t halConfig = VALUE_OR_RETURN_STATUS(
3179 aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/));
3180 audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS(
3181 aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/));
3182 sp<DeviceDescriptorBase> device = VALUE_OR_RETURN_STATUS(
3183 aidl2legacy_DeviceDescriptorBase(request.device));
3184 audio_output_flags_t flags = VALUE_OR_RETURN_STATUS(
3185 aidl2legacy_int32_t_audio_output_flags_t_mask(request.flags));
3186 audio_attributes_t attributes = VALUE_OR_RETURN_STATUS(
3187 aidl2legacy_AudioAttributes_audio_attributes_t(request.attributes));
3188
3189 audio_io_handle_t output;
3190
3191 ALOGI("openOutput() this %p, module %d Device %s, SamplingRate %d, Format %#08x, "
3192 "Channels %#x, flags %#x",
3193 this, module,
3194 device->toString().c_str(),
3195 halConfig.sample_rate,
3196 halConfig.format,
3197 halConfig.channel_mask,
3198 flags);
3199
3200 audio_devices_t deviceType = device->type();
3201 const String8 address = String8(device->address().c_str());
3202
3203 if (deviceType == AUDIO_DEVICE_NONE) {
3204 return BAD_VALUE;
3205 }
3206
3207 audio_utils::lock_guard _l(mutex());
3208
3209 const sp<IAfThreadBase> thread = openOutput_l(module, &output, &halConfig,
3210 &mixerConfig, deviceType, address, &flags, attributes);
3211 if (thread != 0) {
3212 uint32_t latencyMs = 0;
3213 if ((flags & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == 0) {
3214 const auto playbackThread = thread->asIAfPlaybackThread();
3215 latencyMs = playbackThread->latency();
3216
3217 // notify client processes of the new output creation
3218 playbackThread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
3219
3220 // the first primary output opened designates the primary hw device if no HW module
3221 // named "primary" was already loaded.
3222 audio_utils::lock_guard lock(hardwareMutex());
3223 if ((mPrimaryHardwareDev == nullptr) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
3224 ALOGI("Using module %d as the primary audio interface", module);
3225 mPrimaryHardwareDev = playbackThread->getOutput()->audioHwDev;
3226
3227 mHardwareStatus = AUDIO_HW_SET_MODE;
3228 mPrimaryHardwareDev.load()->hwDevice()->setMode(mMode);
3229 mHardwareStatus = AUDIO_HW_IDLE;
3230 }
3231 } else {
3232 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
3233 }
3234 response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output));
3235 response->config = VALUE_OR_RETURN_STATUS(
3236 legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/));
3237 response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral<int32_t>(latencyMs));
3238 response->flags = VALUE_OR_RETURN_STATUS(
3239 legacy2aidl_audio_output_flags_t_int32_t_mask(flags));
3240 return NO_ERROR;
3241 }
3242
3243 return NO_INIT;
3244 }
3245
openDuplicateOutput(audio_io_handle_t output1,audio_io_handle_t output2)3246 audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
3247 audio_io_handle_t output2)
3248 {
3249 audio_utils::lock_guard _l(mutex());
3250 IAfPlaybackThread* const thread1 = checkMixerThread_l(output1);
3251 IAfPlaybackThread* const thread2 = checkMixerThread_l(output2);
3252
3253 if (thread1 == NULL || thread2 == NULL) {
3254 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
3255 output2);
3256 return AUDIO_IO_HANDLE_NONE;
3257 }
3258
3259 audio_io_handle_t id = nextUniqueId(AUDIO_UNIQUE_ID_USE_OUTPUT);
3260 const sp<IAfDuplicatingThread> thread = IAfDuplicatingThread::create(
3261 this, thread1, id, mSystemReady);
3262 thread->addOutputTrack(thread2);
3263 mPlaybackThreads.add(id, thread);
3264 // notify client processes of the new output creation
3265 thread->ioConfigChanged_l(AUDIO_OUTPUT_OPENED);
3266 return id;
3267 }
3268
closeOutput(audio_io_handle_t output)3269 status_t AudioFlinger::closeOutput(audio_io_handle_t output)
3270 {
3271 return closeOutput_nonvirtual(output);
3272 }
3273
closeOutput_nonvirtual(audio_io_handle_t output)3274 status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
3275 {
3276 // keep strong reference on the playback thread so that
3277 // it is not destroyed while exit() is executed
3278 sp<IAfPlaybackThread> playbackThread;
3279 sp<IAfMmapPlaybackThread> mmapThread;
3280 {
3281 audio_utils::lock_guard _l(mutex());
3282 playbackThread = checkPlaybackThread_l(output);
3283 if (playbackThread != NULL) {
3284 ALOGV("closeOutput() %d", output);
3285
3286 dumpToThreadLog_l(playbackThread);
3287
3288 if (playbackThread->type() == IAfThreadBase::MIXER) {
3289 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3290 if (mPlaybackThreads.valueAt(i)->isDuplicating()) {
3291 IAfDuplicatingThread* const dupThread =
3292 mPlaybackThreads.valueAt(i)->asIAfDuplicatingThread().get();
3293 dupThread->removeOutputTrack(playbackThread.get());
3294 }
3295 }
3296 }
3297
3298
3299 mPlaybackThreads.removeItem(output);
3300 // Save AUDIO_SESSION_OUTPUT_MIX effect to orphan chains
3301 // Output Mix Effect session is used to manage Music Effect by AudioPolicy Manager.
3302 // It exists across all playback threads.
3303 if (playbackThread->type() == IAfThreadBase::MIXER
3304 || playbackThread->type() == IAfThreadBase::OFFLOAD
3305 || playbackThread->type() == IAfThreadBase::SPATIALIZER) {
3306 sp<IAfEffectChain> mixChain;
3307 {
3308 audio_utils::scoped_lock sl(playbackThread->mutex());
3309 mixChain = playbackThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3310 if (mixChain != nullptr) {
3311 ALOGW("%s() output %d moving mix session to orphans", __func__, output);
3312 playbackThread->removeEffectChain_l(mixChain);
3313 }
3314 }
3315 if (mixChain != nullptr) {
3316 putOrphanEffectChain_l(mixChain);
3317 }
3318 }
3319 // save all effects to the default thread
3320 if (mPlaybackThreads.size()) {
3321 IAfPlaybackThread* const dstThread =
3322 checkPlaybackThread_l(mPlaybackThreads.keyAt(0));
3323 if (dstThread != NULL) {
3324 // audioflinger lock is held so order of thread lock acquisition doesn't matter
3325 // Use scoped_lock to avoid deadlock order issues with duplicating threads.
3326 audio_utils::scoped_lock sl(dstThread->mutex(), playbackThread->mutex());
3327 Vector<sp<IAfEffectChain>> effectChains = playbackThread->getEffectChains_l();
3328 for (size_t i = 0; i < effectChains.size(); i ++) {
3329 moveEffectChain_ll(effectChains[i]->sessionId(), playbackThread.get(),
3330 dstThread);
3331 }
3332 }
3333 }
3334 } else {
3335 const sp<IAfMmapThread> mt = checkMmapThread_l(output);
3336 mmapThread = mt ? mt->asIAfMmapPlaybackThread().get() : nullptr;
3337 if (mmapThread == 0) {
3338 return BAD_VALUE;
3339 }
3340 dumpToThreadLog_l(mmapThread);
3341 mMmapThreads.removeItem(output);
3342 ALOGD("closing mmapThread %p", mmapThread.get());
3343 }
3344 ioConfigChanged_l(AUDIO_OUTPUT_CLOSED, sp<AudioIoDescriptor>::make(output));
3345 mPatchPanel->notifyStreamClosed(output);
3346 }
3347 // The thread entity (active unit of execution) is no longer running here,
3348 // but the IAfThreadBase container still exists.
3349
3350 if (playbackThread != 0) {
3351 playbackThread->exit();
3352 if (!playbackThread->isDuplicating()) {
3353 closeOutputFinish(playbackThread);
3354 }
3355 } else if (mmapThread != 0) {
3356 ALOGD("mmapThread exit()");
3357 mmapThread->exit();
3358 AudioStreamOut *out = mmapThread->clearOutput();
3359 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3360 // from now on thread->mOutput is NULL
3361 delete out;
3362 }
3363 return NO_ERROR;
3364 }
3365
3366 /* static */
closeOutputFinish(const sp<IAfPlaybackThread> & thread)3367 void AudioFlinger::closeOutputFinish(const sp<IAfPlaybackThread>& thread)
3368 {
3369 AudioStreamOut *out = thread->clearOutput();
3370 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
3371 // from now on thread->mOutput is NULL
3372 delete out;
3373 }
3374
closeThreadInternal_l(const sp<IAfPlaybackThread> & thread)3375 void AudioFlinger::closeThreadInternal_l(const sp<IAfPlaybackThread>& thread)
3376 {
3377 mPlaybackThreads.removeItem(thread->id());
3378 thread->exit();
3379 closeOutputFinish(thread);
3380 }
3381
suspendOutput(audio_io_handle_t output)3382 status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
3383 {
3384 audio_utils::lock_guard _l(mutex());
3385 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
3386
3387 if (thread == NULL) {
3388 return BAD_VALUE;
3389 }
3390
3391 ALOGV("suspendOutput() %d", output);
3392 thread->suspend();
3393
3394 return NO_ERROR;
3395 }
3396
restoreOutput(audio_io_handle_t output)3397 status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
3398 {
3399 audio_utils::lock_guard _l(mutex());
3400 IAfPlaybackThread* const thread = checkPlaybackThread_l(output);
3401
3402 if (thread == NULL) {
3403 return BAD_VALUE;
3404 }
3405
3406 ALOGV("restoreOutput() %d", output);
3407
3408 thread->restore();
3409
3410 return NO_ERROR;
3411 }
3412
openInput(const media::OpenInputRequest & request,media::OpenInputResponse * response)3413 status_t AudioFlinger::openInput(const media::OpenInputRequest& request,
3414 media::OpenInputResponse* response)
3415 {
3416 audio_utils::lock_guard _l(mutex());
3417
3418 AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
3419 aidl2legacy_AudioDeviceTypeAddress(request.device));
3420 if (device.mType == AUDIO_DEVICE_NONE) {
3421 return BAD_VALUE;
3422 }
3423
3424 audio_io_handle_t input = VALUE_OR_RETURN_STATUS(
3425 aidl2legacy_int32_t_audio_io_handle_t(request.input));
3426 audio_config_t config = VALUE_OR_RETURN_STATUS(
3427 aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/));
3428
3429 const sp<IAfThreadBase> thread = openInput_l(
3430 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)),
3431 &input,
3432 &config,
3433 device.mType,
3434 device.address().c_str(),
3435 VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)),
3436 VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)),
3437 AUDIO_DEVICE_NONE,
3438 String8{});
3439
3440 response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input));
3441 response->config = VALUE_OR_RETURN_STATUS(
3442 legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/));
3443 response->device = request.device;
3444
3445 if (thread != 0) {
3446 // notify client processes of the new input creation
3447 thread->ioConfigChanged_l(AUDIO_INPUT_OPENED);
3448 return NO_ERROR;
3449 }
3450 return NO_INIT;
3451 }
3452
openInput_l(audio_module_handle_t module,audio_io_handle_t * input,audio_config_t * config,audio_devices_t devices,const char * address,audio_source_t source,audio_input_flags_t flags,audio_devices_t outputDevice,const String8 & outputDeviceAddress)3453 sp<IAfThreadBase> AudioFlinger::openInput_l(audio_module_handle_t module,
3454 audio_io_handle_t *input,
3455 audio_config_t *config,
3456 audio_devices_t devices,
3457 const char* address,
3458 audio_source_t source,
3459 audio_input_flags_t flags,
3460 audio_devices_t outputDevice,
3461 const String8& outputDeviceAddress)
3462 {
3463 AudioHwDevice *inHwDev = findSuitableHwDev_l(module, devices);
3464 if (inHwDev == NULL) {
3465 *input = AUDIO_IO_HANDLE_NONE;
3466 return 0;
3467 }
3468
3469 // Audio Policy can request a specific handle for hardware hotword.
3470 // The goal here is not to re-open an already opened input.
3471 // It is to use a pre-assigned I/O handle.
3472 if (*input == AUDIO_IO_HANDLE_NONE) {
3473 *input = nextUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3474 } else if (audio_unique_id_get_use(*input) != AUDIO_UNIQUE_ID_USE_INPUT) {
3475 ALOGE("openInput_l() requested input handle %d is invalid", *input);
3476 return 0;
3477 } else if (mRecordThreads.indexOfKey(*input) >= 0) {
3478 // This should not happen in a transient state with current design.
3479 ALOGE("openInput_l() requested input handle %d is already assigned", *input);
3480 return 0;
3481 }
3482
3483 AudioStreamIn *inputStream = nullptr;
3484 status_t status = inHwDev->openInputStream(
3485 &inputStream,
3486 *input,
3487 devices,
3488 flags,
3489 config,
3490 address,
3491 source,
3492 outputDevice,
3493 outputDeviceAddress.c_str());
3494
3495 if (status == NO_ERROR) {
3496 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
3497 const sp<IAfMmapCaptureThread> thread =
3498 IAfMmapCaptureThread::create(this, *input, inHwDev, inputStream, mSystemReady);
3499 mMmapThreads.add(*input, thread);
3500 ALOGV("openInput_l() created mmap capture thread: ID %d thread %p", *input,
3501 thread.get());
3502 return thread;
3503 } else {
3504 // Start record thread
3505 // IAfRecordThread requires both input and output device indication
3506 // to forward to audio pre processing modules
3507 const sp<IAfRecordThread> thread =
3508 IAfRecordThread::create(this, inputStream, *input, mSystemReady);
3509 mRecordThreads.add(*input, thread);
3510 ALOGV("openInput_l() created record thread: ID %d thread %p", *input, thread.get());
3511 return thread;
3512 }
3513 }
3514
3515 *input = AUDIO_IO_HANDLE_NONE;
3516 return 0;
3517 }
3518
closeInput(audio_io_handle_t input)3519 status_t AudioFlinger::closeInput(audio_io_handle_t input)
3520 {
3521 return closeInput_nonvirtual(input);
3522 }
3523
closeInput_nonvirtual(audio_io_handle_t input)3524 status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
3525 {
3526 // keep strong reference on the record thread so that
3527 // it is not destroyed while exit() is executed
3528 sp<IAfRecordThread> recordThread;
3529 sp<IAfMmapCaptureThread> mmapThread;
3530 {
3531 audio_utils::lock_guard _l(mutex());
3532 recordThread = checkRecordThread_l(input);
3533 if (recordThread != 0) {
3534 ALOGV("closeInput() %d", input);
3535
3536 dumpToThreadLog_l(recordThread);
3537
3538 // If we still have effect chains, it means that a client still holds a handle
3539 // on at least one effect. We must either move the chain to an existing thread with the
3540 // same session ID or put it aside in case a new record thread is opened for a
3541 // new capture on the same session
3542 sp<IAfEffectChain> chain;
3543 {
3544 audio_utils::lock_guard _sl(recordThread->mutex());
3545 const Vector<sp<IAfEffectChain>> effectChains = recordThread->getEffectChains_l();
3546 // Note: maximum one chain per record thread
3547 if (effectChains.size() != 0) {
3548 chain = effectChains[0];
3549 }
3550 }
3551 if (chain != 0) {
3552 // first check if a record thread is already opened with a client on same session.
3553 // This should only happen in case of overlap between one thread tear down and the
3554 // creation of its replacement
3555 size_t i;
3556 for (i = 0; i < mRecordThreads.size(); i++) {
3557 const sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
3558 if (t == recordThread) {
3559 continue;
3560 }
3561 if (t->hasAudioSession(chain->sessionId()) != 0) {
3562 audio_utils::lock_guard _l2(t->mutex());
3563 ALOGV("closeInput() found thread %d for effect session %d",
3564 t->id(), chain->sessionId());
3565 t->addEffectChain_l(chain);
3566 break;
3567 }
3568 }
3569 // put the chain aside if we could not find a record thread with the same session id
3570 if (i == mRecordThreads.size()) {
3571 putOrphanEffectChain_l(chain);
3572 }
3573 }
3574 mRecordThreads.removeItem(input);
3575 } else {
3576 const sp<IAfMmapThread> mt = checkMmapThread_l(input);
3577 mmapThread = mt ? mt->asIAfMmapCaptureThread().get() : nullptr;
3578 if (mmapThread == 0) {
3579 return BAD_VALUE;
3580 }
3581 dumpToThreadLog_l(mmapThread);
3582 mMmapThreads.removeItem(input);
3583 }
3584 ioConfigChanged_l(AUDIO_INPUT_CLOSED, sp<AudioIoDescriptor>::make(input));
3585 }
3586 // FIXME: calling thread->exit() without mutex() held should not be needed anymore now that
3587 // we have a different lock for notification client
3588 if (recordThread != 0) {
3589 closeInputFinish(recordThread);
3590 } else if (mmapThread != 0) {
3591 mmapThread->exit();
3592 AudioStreamIn *in = mmapThread->clearInput();
3593 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3594 // from now on thread->mInput is NULL
3595 delete in;
3596 }
3597 return NO_ERROR;
3598 }
3599
closeInputFinish(const sp<IAfRecordThread> & thread)3600 void AudioFlinger::closeInputFinish(const sp<IAfRecordThread>& thread)
3601 {
3602 thread->exit();
3603 AudioStreamIn *in = thread->clearInput();
3604 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
3605 // from now on thread->mInput is NULL
3606 delete in;
3607 }
3608
closeThreadInternal_l(const sp<IAfRecordThread> & thread)3609 void AudioFlinger::closeThreadInternal_l(const sp<IAfRecordThread>& thread)
3610 {
3611 mRecordThreads.removeItem(thread->id());
3612 closeInputFinish(thread);
3613 }
3614
invalidateTracks(const std::vector<audio_port_handle_t> & portIds)3615 status_t AudioFlinger::invalidateTracks(const std::vector<audio_port_handle_t> &portIds) {
3616 audio_utils::lock_guard _l(mutex());
3617 ALOGV("%s", __func__);
3618
3619 std::set<audio_port_handle_t> portIdSet(portIds.begin(), portIds.end());
3620 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3621 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
3622 thread->invalidateTracks(portIdSet);
3623 if (portIdSet.empty()) {
3624 return NO_ERROR;
3625 }
3626 }
3627 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3628 mMmapThreads[i]->invalidateTracks(portIdSet);
3629 if (portIdSet.empty()) {
3630 return NO_ERROR;
3631 }
3632 }
3633 return NO_ERROR;
3634 }
3635
3636
newAudioUniqueId(audio_unique_id_use_t use)3637 audio_unique_id_t AudioFlinger::newAudioUniqueId(audio_unique_id_use_t use)
3638 {
3639 // This is a binder API, so a malicious client could pass in a bad parameter.
3640 // Check for that before calling the internal API nextUniqueId().
3641 if ((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX) {
3642 ALOGE("newAudioUniqueId invalid use %d", use);
3643 return AUDIO_UNIQUE_ID_ALLOCATE;
3644 }
3645 return nextUniqueId(use);
3646 }
3647
acquireAudioSessionId(audio_session_t audioSession,pid_t pid,uid_t uid)3648 void AudioFlinger::acquireAudioSessionId(
3649 audio_session_t audioSession, pid_t pid, uid_t uid)
3650 {
3651 audio_utils::lock_guard _l(mutex());
3652 pid_t caller = IPCThreadState::self()->getCallingPid();
3653 ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
3654 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
3655 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3656 caller = pid; // check must match releaseAudioSessionId()
3657 }
3658 if (uid == (uid_t)-1 || !isAudioServerOrMediaServerUid(callerUid)) {
3659 uid = callerUid;
3660 }
3661
3662 {
3663 audio_utils::lock_guard _cl(clientMutex());
3664 // Ignore requests received from processes not known as notification client. The request
3665 // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
3666 // called from a different pid leaving a stale session reference. Also we don't know how
3667 // to clear this reference if the client process dies.
3668 if (mNotificationClients.count(caller) == 0) {
3669 ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
3670 return;
3671 }
3672 }
3673
3674 size_t num = mAudioSessionRefs.size();
3675 for (size_t i = 0; i < num; i++) {
3676 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
3677 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3678 ref->mCnt++;
3679 ALOGV(" incremented refcount to %d", ref->mCnt);
3680 return;
3681 }
3682 }
3683 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller, uid));
3684 ALOGV(" added new entry for %d", audioSession);
3685 }
3686
releaseAudioSessionId(audio_session_t audioSession,pid_t pid)3687 void AudioFlinger::releaseAudioSessionId(audio_session_t audioSession, pid_t pid)
3688 {
3689 std::vector<sp<IAfEffectModule>> removedEffects;
3690 {
3691 audio_utils::lock_guard _l(mutex());
3692 pid_t caller = IPCThreadState::self()->getCallingPid();
3693 ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
3694 const uid_t callerUid = IPCThreadState::self()->getCallingUid();
3695 if (pid != (pid_t)-1 && isAudioServerOrMediaServerUid(callerUid)) {
3696 caller = pid; // check must match acquireAudioSessionId()
3697 }
3698 size_t num = mAudioSessionRefs.size();
3699 for (size_t i = 0; i < num; i++) {
3700 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3701 if (ref->mSessionid == audioSession && ref->mPid == caller) {
3702 ref->mCnt--;
3703 ALOGV(" decremented refcount to %d", ref->mCnt);
3704 if (ref->mCnt == 0) {
3705 mAudioSessionRefs.removeAt(i);
3706 delete ref;
3707 std::vector<sp<IAfEffectModule>> effects = purgeStaleEffects_l();
3708 removedEffects.insert(removedEffects.end(), effects.begin(), effects.end());
3709 }
3710 goto Exit;
3711 }
3712 }
3713 // If the caller is audioserver it is likely that the session being released was acquired
3714 // on behalf of a process not in notification clients and we ignore the warning.
3715 ALOGW_IF(!isAudioServerUid(callerUid),
3716 "session id %d not found for pid %d", audioSession, caller);
3717 }
3718
3719 Exit:
3720 for (auto& effect : removedEffects) {
3721 effect->updatePolicyState();
3722 }
3723 }
3724
isSessionAcquired_l(audio_session_t audioSession)3725 bool AudioFlinger::isSessionAcquired_l(audio_session_t audioSession)
3726 {
3727 size_t num = mAudioSessionRefs.size();
3728 for (size_t i = 0; i < num; i++) {
3729 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
3730 if (ref->mSessionid == audioSession) {
3731 return true;
3732 }
3733 }
3734 return false;
3735 }
3736
purgeStaleEffects_l()3737 std::vector<sp<IAfEffectModule>> AudioFlinger::purgeStaleEffects_l() {
3738
3739 ALOGV("purging stale effects");
3740
3741 Vector<sp<IAfEffectChain>> chains;
3742 std::vector< sp<IAfEffectModule> > removedEffects;
3743
3744 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3745 sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
3746 audio_utils::lock_guard _l(t->mutex());
3747 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3748 for (size_t j = 0; j < threadChains.size(); j++) {
3749 sp<IAfEffectChain> ec = threadChains[j];
3750 if (!audio_is_global_session(ec->sessionId())) {
3751 chains.push(ec);
3752 }
3753 }
3754 }
3755
3756 for (size_t i = 0; i < mRecordThreads.size(); i++) {
3757 sp<IAfRecordThread> t = mRecordThreads.valueAt(i);
3758 audio_utils::lock_guard _l(t->mutex());
3759 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3760 for (size_t j = 0; j < threadChains.size(); j++) {
3761 sp<IAfEffectChain> ec = threadChains[j];
3762 chains.push(ec);
3763 }
3764 }
3765
3766 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3767 const sp<IAfMmapThread> t = mMmapThreads.valueAt(i);
3768 audio_utils::lock_guard _l(t->mutex());
3769 const Vector<sp<IAfEffectChain>> threadChains = t->getEffectChains_l();
3770 for (size_t j = 0; j < threadChains.size(); j++) {
3771 sp<IAfEffectChain> ec = threadChains[j];
3772 chains.push(ec);
3773 }
3774 }
3775
3776 for (size_t i = 0; i < chains.size(); i++) {
3777 // clang-tidy suggests const ref
3778 sp<IAfEffectChain> ec = chains[i]; // NOLINT(performance-unnecessary-copy-initialization)
3779 int sessionid = ec->sessionId();
3780 const auto t = ec->thread().promote();
3781 if (t == 0) {
3782 continue;
3783 }
3784 size_t numsessionrefs = mAudioSessionRefs.size();
3785 bool found = false;
3786 for (size_t k = 0; k < numsessionrefs; k++) {
3787 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3788 if (ref->mSessionid == sessionid) {
3789 ALOGV(" session %d still exists for %d with %d refs",
3790 sessionid, ref->mPid, ref->mCnt);
3791 found = true;
3792 break;
3793 }
3794 }
3795 if (!found) {
3796 audio_utils::lock_guard _l(t->mutex());
3797 // remove all effects from the chain
3798 while (ec->numberOfEffects()) {
3799 sp<IAfEffectModule> effect = ec->getEffectModule(0);
3800 effect->unPin();
3801 t->removeEffect_l(effect, /*release*/ true);
3802 if (effect->purgeHandles()) {
3803 effect->checkSuspendOnEffectEnabled(false, true /*threadLocked*/);
3804 }
3805 removedEffects.push_back(effect);
3806 }
3807 }
3808 }
3809 return removedEffects;
3810 }
3811
purgeOrphanEffectChains_l()3812 std::vector< sp<IAfEffectModule> > AudioFlinger::purgeOrphanEffectChains_l()
3813 {
3814 ALOGV("purging stale effects from orphan chains");
3815 std::vector< sp<IAfEffectModule> > removedEffects;
3816 for (size_t index = 0; index < mOrphanEffectChains.size(); index++) {
3817 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
3818 audio_session_t session = mOrphanEffectChains.keyAt(index);
3819 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_DEVICE
3820 || session == AUDIO_SESSION_OUTPUT_STAGE) {
3821 continue;
3822 }
3823 size_t numSessionRefs = mAudioSessionRefs.size();
3824 bool found = false;
3825 for (size_t k = 0; k < numSessionRefs; k++) {
3826 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
3827 if (ref->mSessionid == session) {
3828 ALOGV(" session %d still exists for %d with %d refs", session, ref->mPid,
3829 ref->mCnt);
3830 found = true;
3831 break;
3832 }
3833 }
3834 if (!found) {
3835 for (size_t i = 0; i < chain->numberOfEffects(); i++) {
3836 sp<IAfEffectModule> effect = chain->getEffectModule(i);
3837 removedEffects.push_back(effect);
3838 }
3839 }
3840 }
3841 for (auto& effect : removedEffects) {
3842 effect->unPin();
3843 updateOrphanEffectChains_l(effect);
3844 }
3845 return removedEffects;
3846 }
3847
3848 // dumpToThreadLog_l() must be called with AudioFlinger::mutex() held
dumpToThreadLog_l(const sp<IAfThreadBase> & thread)3849 void AudioFlinger::dumpToThreadLog_l(const sp<IAfThreadBase> &thread)
3850 {
3851 constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
3852 constexpr auto PREFIX = "- ";
3853 if (com::android::media::audioserver::fdtostring_timeout_fix()) {
3854 using ::android::audio_utils::FdToString;
3855
3856 auto writer = OR_RETURN(FdToString::createWriter(PREFIX));
3857 thread->dump(writer.borrowFdUnsafe(), {} /* args */);
3858 mThreadLog.logs(-1 /* time */, FdToString::closeWriterAndGetString(std::move(writer)));
3859 } else {
3860 audio_utils::FdToStringOldImpl fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
3861 const int fd = fdToString.borrowFdUnsafe();
3862 if (fd >= 0) {
3863 thread->dump(fd, {} /* args */);
3864 mThreadLog.logs(-1 /* time */, fdToString.closeAndGetString());
3865 }
3866 }
3867 }
3868
3869 // checkThread_l() must be called with AudioFlinger::mutex() held
checkThread_l(audio_io_handle_t ioHandle) const3870 IAfThreadBase* AudioFlinger::checkThread_l(audio_io_handle_t ioHandle) const
3871 {
3872 IAfThreadBase* thread = checkMmapThread_l(ioHandle);
3873 if (thread == 0) {
3874 switch (audio_unique_id_get_use(ioHandle)) {
3875 case AUDIO_UNIQUE_ID_USE_OUTPUT:
3876 thread = checkPlaybackThread_l(ioHandle);
3877 break;
3878 case AUDIO_UNIQUE_ID_USE_INPUT:
3879 thread = checkRecordThread_l(ioHandle);
3880 break;
3881 default:
3882 break;
3883 }
3884 }
3885 return thread;
3886 }
3887
3888 // checkOutputThread_l() must be called with AudioFlinger::mutex() held
checkOutputThread_l(audio_io_handle_t ioHandle) const3889 sp<IAfThreadBase> AudioFlinger::checkOutputThread_l(audio_io_handle_t ioHandle) const
3890 {
3891 if (audio_unique_id_get_use(ioHandle) != AUDIO_UNIQUE_ID_USE_OUTPUT) {
3892 return nullptr;
3893 }
3894
3895 sp<IAfThreadBase> thread = mPlaybackThreads.valueFor(ioHandle);
3896 if (thread == nullptr) {
3897 thread = mMmapThreads.valueFor(ioHandle);
3898 }
3899 return thread;
3900 }
3901
3902 // checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
checkPlaybackThread_l(audio_io_handle_t output) const3903 IAfPlaybackThread* AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
3904 {
3905 return mPlaybackThreads.valueFor(output).get();
3906 }
3907
3908 // checkMixerThread_l() must be called with AudioFlinger::mutex() held
checkMixerThread_l(audio_io_handle_t output) const3909 IAfPlaybackThread* AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
3910 {
3911 IAfPlaybackThread * const thread = checkPlaybackThread_l(output);
3912 return thread != nullptr && thread->type() != IAfThreadBase::DIRECT ? thread : nullptr;
3913 }
3914
3915 // checkRecordThread_l() must be called with AudioFlinger::mutex() held
checkRecordThread_l(audio_io_handle_t input) const3916 IAfRecordThread* AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
3917 {
3918 return mRecordThreads.valueFor(input).get();
3919 }
3920
3921 // checkMmapThread_l() must be called with AudioFlinger::mutex() held
checkMmapThread_l(audio_io_handle_t io) const3922 IAfMmapThread* AudioFlinger::checkMmapThread_l(audio_io_handle_t io) const
3923 {
3924 return mMmapThreads.valueFor(io).get();
3925 }
3926
3927
3928 // checkPlaybackThread_l() must be called with AudioFlinger::mutex() held
getVolumeInterface_l(audio_io_handle_t output) const3929 sp<VolumeInterface> AudioFlinger::getVolumeInterface_l(audio_io_handle_t output) const {
3930 sp<VolumeInterface> volumeInterface = mPlaybackThreads.valueFor(output).get();
3931 if (volumeInterface == nullptr) {
3932 IAfMmapThread* const mmapThread = mMmapThreads.valueFor(output).get();
3933 if (mmapThread != nullptr) {
3934 if (mmapThread->isOutput()) {
3935 IAfMmapPlaybackThread* const mmapPlaybackThread =
3936 mmapThread->asIAfMmapPlaybackThread().get();
3937 volumeInterface = mmapPlaybackThread;
3938 }
3939 }
3940 }
3941 return volumeInterface;
3942 }
3943
getAllVolumeInterfaces_l() const3944 std::vector<sp<VolumeInterface>> AudioFlinger::getAllVolumeInterfaces_l() const
3945 {
3946 std::vector<sp<VolumeInterface>> volumeInterfaces;
3947 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3948 volumeInterfaces.push_back(mPlaybackThreads.valueAt(i).get());
3949 }
3950 for (size_t i = 0; i < mMmapThreads.size(); i++) {
3951 if (mMmapThreads.valueAt(i)->isOutput()) {
3952 IAfMmapPlaybackThread* const mmapPlaybackThread =
3953 mMmapThreads.valueAt(i)->asIAfMmapPlaybackThread().get();
3954 volumeInterfaces.push_back(mmapPlaybackThread);
3955 }
3956 }
3957 return volumeInterfaces;
3958 }
3959
nextUniqueId(audio_unique_id_use_t use)3960 audio_unique_id_t AudioFlinger::nextUniqueId(audio_unique_id_use_t use)
3961 {
3962 // This is the internal API, so it is OK to assert on bad parameter.
3963 LOG_ALWAYS_FATAL_IF((unsigned) use >= (unsigned) AUDIO_UNIQUE_ID_USE_MAX);
3964 const int maxRetries = use == AUDIO_UNIQUE_ID_USE_SESSION ? 3 : 1;
3965 for (int retry = 0; retry < maxRetries; retry++) {
3966 // The cast allows wraparound from max positive to min negative instead of abort
3967 uint32_t base = (uint32_t) atomic_fetch_add_explicit(&mNextUniqueIds[use],
3968 (uint_fast32_t) AUDIO_UNIQUE_ID_USE_MAX, memory_order_acq_rel);
3969 ALOG_ASSERT(audio_unique_id_get_use(base) == AUDIO_UNIQUE_ID_USE_UNSPECIFIED);
3970 // allow wrap by skipping 0 and -1 for session ids
3971 if (!(base == 0 || base == (~0u & ~AUDIO_UNIQUE_ID_USE_MASK))) {
3972 ALOGW_IF(retry != 0, "unique ID overflow for use %d", use);
3973 return (audio_unique_id_t) (base | use);
3974 }
3975 }
3976 // We have no way of recovering from wraparound
3977 LOG_ALWAYS_FATAL("unique ID overflow for use %d", use);
3978 // TODO Use a floor after wraparound. This may need a mutex.
3979 }
3980
primaryPlaybackThread_l() const3981 IAfPlaybackThread* AudioFlinger::primaryPlaybackThread_l() const
3982 {
3983 // The atomic ptr mPrimaryHardwareDev requires both the
3984 // AudioFlinger and the Hardware mutex for modification.
3985 // As we hold the AudioFlinger mutex, we access it
3986 // safely without the Hardware mutex, to avoid mutex order
3987 // inversion with Thread methods and the ThreadBase mutex.
3988 if (mPrimaryHardwareDev == nullptr) {
3989 return nullptr;
3990 }
3991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
3992 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
3993 if(thread->isDuplicating()) {
3994 continue;
3995 }
3996 AudioStreamOut *output = thread->getOutput();
3997 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
3998 return thread;
3999 }
4000 }
4001 return nullptr;
4002 }
4003
primaryOutputDevice_l() const4004 DeviceTypeSet AudioFlinger::primaryOutputDevice_l() const
4005 {
4006 IAfPlaybackThread* const thread = primaryPlaybackThread_l();
4007
4008 if (thread == NULL) {
4009 return {};
4010 }
4011
4012 audio_utils::lock_guard l(thread->mutex());
4013 return thread->outDeviceTypes_l();
4014 }
4015
fastPlaybackThread_l() const4016 IAfPlaybackThread* AudioFlinger::fastPlaybackThread_l() const
4017 {
4018 size_t minFrameCount = 0;
4019 IAfPlaybackThread* minThread = nullptr;
4020 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4021 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
4022 if (!thread->isDuplicating()) {
4023 size_t frameCount = thread->frameCountHAL();
4024 if (frameCount != 0 && (minFrameCount == 0 || frameCount < minFrameCount ||
4025 (frameCount == minFrameCount && thread->hasFastMixer() &&
4026 /*minThread != NULL &&*/ !minThread->hasFastMixer()))) {
4027 minFrameCount = frameCount;
4028 minThread = thread;
4029 }
4030 }
4031 }
4032 return minThread;
4033 }
4034
hapticPlaybackThread_l() const4035 IAfThreadBase* AudioFlinger::hapticPlaybackThread_l() const {
4036 for (size_t i = 0; i < mPlaybackThreads.size(); ++i) {
4037 IAfPlaybackThread* const thread = mPlaybackThreads.valueAt(i).get();
4038 if (thread->hapticChannelMask() != AUDIO_CHANNEL_NONE) {
4039 return thread;
4040 }
4041 }
4042 return nullptr;
4043 }
4044
updateSecondaryOutputsForTrack_l(IAfTrack * track,IAfPlaybackThread * thread,const std::vector<audio_io_handle_t> & secondaryOutputs) const4045 void AudioFlinger::updateSecondaryOutputsForTrack_l(
4046 IAfTrack* track,
4047 IAfPlaybackThread* thread,
4048 const std::vector<audio_io_handle_t> &secondaryOutputs) const {
4049 TeePatches teePatches;
4050 for (audio_io_handle_t secondaryOutput : secondaryOutputs) {
4051 IAfPlaybackThread* const secondaryThread = checkPlaybackThread_l(secondaryOutput);
4052 if (secondaryThread == nullptr) {
4053 ALOGE("no playback thread found for secondary output %d", thread->id());
4054 continue;
4055 }
4056
4057 size_t sourceFrameCount = thread->frameCount() * track->sampleRate()
4058 / thread->sampleRate();
4059 size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate()
4060 / secondaryThread->sampleRate();
4061 // If the secondary output has just been opened, the first secondaryThread write
4062 // will not block as it will fill the empty startup buffer of the HAL,
4063 // so a second sink buffer needs to be ready for the immediate next blocking write.
4064 // Additionally, have a margin of one main thread buffer as the scheduling jitter
4065 // can reorder the writes (eg if thread A&B have the same write intervale,
4066 // the scheduler could schedule AB...BA)
4067 size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount;
4068 // Total secondary output buffer must be at least as the read frames plus
4069 // the margin of a few buffers on both sides in case the
4070 // threads scheduling has some jitter.
4071 // That value should not impact latency as the secondary track is started before
4072 // its buffer is full, see frameCountToBeReady.
4073 size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount);
4074 // The frameCount should also not be smaller than the secondary thread min frame
4075 // count
4076 size_t minFrameCount = AudioSystem::calculateMinFrameCount(
4077 [&] { audio_utils::lock_guard _l(secondaryThread->mutex());
4078 return secondaryThread->latency_l(); }(),
4079 secondaryThread->frameCount(), // normal frame count
4080 secondaryThread->sampleRate(),
4081 track->sampleRate(),
4082 track->getSpeed());
4083 frameCount = std::max(frameCount, minFrameCount);
4084
4085 using namespace std::chrono_literals;
4086 auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask());
4087 if (inChannelMask == AUDIO_CHANNEL_INVALID) {
4088 // The downstream PatchTrack has the proper output channel mask,
4089 // so if there is no input channel mask equivalent, we can just
4090 // use an index mask here to create the PatchRecord.
4091 inChannelMask = audio_channel_mask_out_to_in_index_mask(track->channelMask());
4092 }
4093 sp<IAfPatchRecord> patchRecord = IAfPatchRecord::create(nullptr /* thread */,
4094 track->sampleRate(),
4095 inChannelMask,
4096 track->format(),
4097 frameCount,
4098 nullptr /* buffer */,
4099 (size_t)0 /* bufferSize */,
4100 AUDIO_INPUT_FLAG_DIRECT,
4101 0ns /* timeout */);
4102 status_t status = patchRecord->initCheck();
4103 if (status != NO_ERROR) {
4104 ALOGE("Secondary output patchRecord init failed: %d", status);
4105 continue;
4106 }
4107
4108 // TODO: We could check compatibility of the secondaryThread with the PatchTrack
4109 // for fast usage: thread has fast mixer, sample rate matches, etc.;
4110 // for now, we exclude fast tracks by removing the Fast flag.
4111 constexpr audio_output_flags_t kIncompatiblePatchTrackFlags =
4112 static_cast<audio_output_flags_t>(AUDIO_OUTPUT_FLAG_FAST
4113 | AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
4114
4115 const audio_output_flags_t outputFlags =
4116 (audio_output_flags_t)(track->getOutputFlags() & ~kIncompatiblePatchTrackFlags);
4117 sp<IAfPatchTrack> patchTrack = IAfPatchTrack::create(secondaryThread,
4118 track->streamType(),
4119 track->sampleRate(),
4120 track->channelMask(),
4121 track->format(),
4122 frameCount,
4123 patchRecord->buffer(),
4124 patchRecord->bufferSize(),
4125 outputFlags,
4126 0ns /* timeout */,
4127 frameCountToBeReady,
4128 track->getSpeed(),
4129 1.f /* volume */,
4130 false /* muted */);
4131 status = patchTrack->initCheck();
4132 if (status != NO_ERROR) {
4133 ALOGE("Secondary output patchTrack init failed: %d", status);
4134 continue;
4135 }
4136 teePatches.push_back({patchRecord, patchTrack});
4137 secondaryThread->addPatchTrack(patchTrack);
4138 // In case the downstream patchTrack on the secondaryThread temporarily outlives
4139 // our created track, ensure the corresponding patchRecord is still alive.
4140 patchTrack->setPeerProxy(patchRecord, true /* holdReference */);
4141 patchRecord->setPeerProxy(patchTrack, false /* holdReference */);
4142 }
4143 track->setTeePatchesToUpdate_l(std::move(teePatches));
4144 }
4145
createSyncEvent(AudioSystem::sync_event_t type,audio_session_t triggerSession,audio_session_t listenerSession,const audioflinger::SyncEventCallback & callBack,const wp<IAfTrackBase> & cookie)4146 sp<audioflinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
4147 audio_session_t triggerSession,
4148 audio_session_t listenerSession,
4149 const audioflinger::SyncEventCallback& callBack,
4150 const wp<IAfTrackBase>& cookie)
4151 {
4152 audio_utils::lock_guard _l(mutex());
4153
4154 auto event = sp<audioflinger::SyncEvent>::make(
4155 type, triggerSession, listenerSession, callBack, cookie);
4156 status_t playStatus = NAME_NOT_FOUND;
4157 status_t recStatus = NAME_NOT_FOUND;
4158 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4159 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
4160 if (playStatus == NO_ERROR) {
4161 return event;
4162 }
4163 }
4164 for (size_t i = 0; i < mRecordThreads.size(); i++) {
4165 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
4166 if (recStatus == NO_ERROR) {
4167 return event;
4168 }
4169 }
4170 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
4171 mPendingSyncEvents.emplace_back(event);
4172 } else {
4173 ALOGV("createSyncEvent() invalid event %d", event->type());
4174 event.clear();
4175 }
4176 return event;
4177 }
4178
4179 // ----------------------------------------------------------------------------
4180 // Effect management
4181 // ----------------------------------------------------------------------------
4182
getEffectsFactory()4183 sp<EffectsFactoryHalInterface> AudioFlinger::getEffectsFactory() {
4184 return mEffectsFactoryHal;
4185 }
4186
queryNumberEffects(uint32_t * numEffects) const4187 status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
4188 {
4189 audio_utils::lock_guard _l(mutex());
4190 if (mEffectsFactoryHal.get()) {
4191 return mEffectsFactoryHal->queryNumberEffects(numEffects);
4192 } else {
4193 return -ENODEV;
4194 }
4195 }
4196
queryEffect(uint32_t index,effect_descriptor_t * descriptor) const4197 status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
4198 {
4199 audio_utils::lock_guard _l(mutex());
4200 if (mEffectsFactoryHal.get()) {
4201 return mEffectsFactoryHal->getDescriptor(index, descriptor);
4202 } else {
4203 return -ENODEV;
4204 }
4205 }
4206
getEffectDescriptor(const effect_uuid_t * pUuid,const effect_uuid_t * pTypeUuid,uint32_t preferredTypeFlag,effect_descriptor_t * descriptor) const4207 status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
4208 const effect_uuid_t *pTypeUuid,
4209 uint32_t preferredTypeFlag,
4210 effect_descriptor_t *descriptor) const
4211 {
4212 if (pUuid == NULL || pTypeUuid == NULL || descriptor == NULL) {
4213 return BAD_VALUE;
4214 }
4215
4216 audio_utils::lock_guard _l(mutex());
4217
4218 if (!mEffectsFactoryHal.get()) {
4219 return -ENODEV;
4220 }
4221
4222 status_t status = NO_ERROR;
4223 if (!EffectsFactoryHalInterface::isNullUuid(pUuid)) {
4224 // If uuid is specified, request effect descriptor from that.
4225 status = mEffectsFactoryHal->getDescriptor(pUuid, descriptor);
4226 } else if (!EffectsFactoryHalInterface::isNullUuid(pTypeUuid)) {
4227 // If uuid is not specified, look for an available implementation
4228 // of the required type instead.
4229
4230 // Use a temporary descriptor to avoid modifying |descriptor| in the failure case.
4231 effect_descriptor_t desc;
4232 desc.flags = 0; // prevent compiler warning
4233
4234 uint32_t numEffects = 0;
4235 status = mEffectsFactoryHal->queryNumberEffects(&numEffects);
4236 if (status < 0) {
4237 ALOGW("getEffectDescriptor() error %d from FactoryHal queryNumberEffects", status);
4238 return status;
4239 }
4240
4241 bool found = false;
4242 for (uint32_t i = 0; i < numEffects; i++) {
4243 status = mEffectsFactoryHal->getDescriptor(i, &desc);
4244 if (status < 0) {
4245 ALOGW("getEffectDescriptor() error %d from FactoryHal getDescriptor", status);
4246 continue;
4247 }
4248 if (memcmp(&desc.type, pTypeUuid, sizeof(effect_uuid_t)) == 0) {
4249 // If matching type found save effect descriptor.
4250 found = true;
4251 *descriptor = desc;
4252
4253 // If there's no preferred flag or this descriptor matches the preferred
4254 // flag, success! If this descriptor doesn't match the preferred
4255 // flag, continue enumeration in case a better matching version of this
4256 // effect type is available. Note that this means if no effect with a
4257 // correct flag is found, the descriptor returned will correspond to the
4258 // last effect that at least had a matching type uuid (if any).
4259 if (preferredTypeFlag == EFFECT_FLAG_TYPE_MASK ||
4260 (desc.flags & EFFECT_FLAG_TYPE_MASK) == preferredTypeFlag) {
4261 break;
4262 }
4263 }
4264 }
4265
4266 if (!found) {
4267 status = NAME_NOT_FOUND;
4268 ALOGW("getEffectDescriptor(): Effect not found by type.");
4269 }
4270 } else {
4271 status = BAD_VALUE;
4272 ALOGE("getEffectDescriptor(): Either uuid or type uuid must be non-null UUIDs.");
4273 }
4274 return status;
4275 }
4276
createEffect(const media::CreateEffectRequest & request,media::CreateEffectResponse * response)4277 status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request,
4278 media::CreateEffectResponse* response) {
4279 const sp<IEffectClient>& effectClient = request.client;
4280 const int32_t priority = request.priority;
4281 const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS(
4282 aidl2legacy_AudioDeviceTypeAddress(request.device));
4283 AttributionSourceState adjAttributionSource = request.attributionSource;
4284 const audio_session_t sessionId = VALUE_OR_RETURN_STATUS(
4285 aidl2legacy_int32_t_audio_session_t(request.sessionId));
4286 audio_io_handle_t io = VALUE_OR_RETURN_STATUS(
4287 aidl2legacy_int32_t_audio_io_handle_t(request.output));
4288 const effect_descriptor_t descIn = VALUE_OR_RETURN_STATUS(
4289 aidl2legacy_EffectDescriptor_effect_descriptor_t(request.desc));
4290 const bool probe = request.probe;
4291
4292 sp<IAfEffectHandle> handle;
4293 effect_descriptor_t descOut;
4294 int enabledOut = 0;
4295 int idOut = -1;
4296
4297 status_t lStatus = NO_ERROR;
4298 uid_t callingUid = IPCThreadState::self()->getCallingUid();
4299 pid_t currentPid;
4300 if (!com::android::media::audio::audioserver_permissions()) {
4301 adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid));
4302 currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid));
4303 if (currentPid == -1 || !isAudioServerOrMediaServerOrSystemServerOrRootUid(callingUid)) {
4304 const pid_t callingPid = IPCThreadState::self()->getCallingPid();
4305 ALOGW_IF(currentPid != -1 && currentPid != callingPid,
4306 "%s uid %d pid %d tried to pass itself off as pid %d",
4307 __func__, callingUid, callingPid, currentPid);
4308 adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(
4309 legacy2aidl_pid_t_int32_t(callingPid));
4310 currentPid = callingPid;
4311 }
4312 adjAttributionSource = afutils::checkAttributionSourcePackage(adjAttributionSource);
4313 } else {
4314 auto validatedAttrSource = VALUE_OR_RETURN_CONVERTED(
4315 validateAttributionFromContextOrTrustedCaller(request.attributionSource,
4316 getPermissionProvider()
4317 ));
4318 // TODO pass wrapped object around
4319 adjAttributionSource = std::move(validatedAttrSource).unwrapInto();
4320 currentPid = adjAttributionSource.pid;
4321 }
4322
4323
4324 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p",
4325 adjAttributionSource.pid, effectClient.get(), priority, sessionId, io,
4326 mEffectsFactoryHal.get());
4327
4328 if (mEffectsFactoryHal == 0) {
4329 ALOGE("%s: no effects factory hal", __func__);
4330 lStatus = NO_INIT;
4331 goto Exit;
4332 }
4333
4334 // check audio settings permission for global effects
4335 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4336 if (!settingsAllowed()) {
4337 ALOGE("%s: no permission for AUDIO_SESSION_OUTPUT_MIX", __func__);
4338 lStatus = PERMISSION_DENIED;
4339 goto Exit;
4340 }
4341 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
4342 if (io == AUDIO_IO_HANDLE_NONE) {
4343 ALOGE("%s: APM must specify output when using AUDIO_SESSION_OUTPUT_STAGE", __func__);
4344 lStatus = BAD_VALUE;
4345 goto Exit;
4346 }
4347 IAfPlaybackThread* thread;
4348 {
4349 audio_utils::lock_guard l(mutex());
4350 thread = checkPlaybackThread_l(io);
4351 }
4352 if (thread == nullptr) {
4353 ALOGE("%s: invalid output %d specified for AUDIO_SESSION_OUTPUT_STAGE", __func__, io);
4354 lStatus = BAD_VALUE;
4355 goto Exit;
4356 }
4357 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)
4358 && !isAudioServerUid(callingUid)) {
4359 ALOGE("%s: effect on AUDIO_SESSION_OUTPUT_STAGE not granted for uid %d",
4360 __func__, callingUid);
4361 lStatus = PERMISSION_DENIED;
4362 goto Exit;
4363 }
4364 } else if (sessionId == AUDIO_SESSION_DEVICE) {
4365 if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) {
4366 ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid);
4367 lStatus = PERMISSION_DENIED;
4368 goto Exit;
4369 }
4370 if (io != AUDIO_IO_HANDLE_NONE) {
4371 ALOGE("%s: io handle should not be specified for device effect", __func__);
4372 lStatus = BAD_VALUE;
4373 goto Exit;
4374 }
4375 } else {
4376 // general sessionId.
4377
4378 if (audio_unique_id_get_use(sessionId) != AUDIO_UNIQUE_ID_USE_SESSION) {
4379 ALOGE("%s: invalid sessionId %d", __func__, sessionId);
4380 lStatus = BAD_VALUE;
4381 goto Exit;
4382 }
4383
4384 // TODO: should we check if the callingUid (limited to pid) is in mAudioSessionRefs
4385 // to prevent creating an effect when one doesn't actually have track with that session?
4386 }
4387
4388 {
4389 // Get the full effect descriptor from the uuid/type.
4390 // If the session is the output mix, prefer an auxiliary effect,
4391 // otherwise no preference.
4392 uint32_t preferredType = (sessionId == AUDIO_SESSION_OUTPUT_MIX ?
4393 EFFECT_FLAG_TYPE_AUXILIARY : EFFECT_FLAG_TYPE_MASK);
4394 lStatus = getEffectDescriptor(&descIn.uuid, &descIn.type, preferredType, &descOut);
4395 if (lStatus < 0) {
4396 ALOGW("createEffect() error %d from getEffectDescriptor", lStatus);
4397 goto Exit;
4398 }
4399
4400 // Do not allow auxiliary effects on a session different from 0 (output mix)
4401 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
4402 (descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4403 lStatus = INVALID_OPERATION;
4404 goto Exit;
4405 }
4406
4407 // check recording permission for visualizer
4408 if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
4409 // TODO: Do we need to start/stop op - i.e. is there recording being performed?
4410 !recordingAllowed(adjAttributionSource)) {
4411 lStatus = PERMISSION_DENIED;
4412 goto Exit;
4413 }
4414
4415 const bool hapticPlaybackRequired = IAfEffectModule::isHapticGenerator(&descOut.type);
4416 if (hapticPlaybackRequired
4417 && (sessionId == AUDIO_SESSION_DEVICE
4418 || sessionId == AUDIO_SESSION_OUTPUT_MIX
4419 || sessionId == AUDIO_SESSION_OUTPUT_STAGE)) {
4420 // haptic-generating effect is only valid when the session id is a general session id
4421 lStatus = INVALID_OPERATION;
4422 goto Exit;
4423 }
4424
4425 // Only audio policy service can create a spatializer effect
4426 if (IAfEffectModule::isSpatializer(&descOut.type) &&
4427 (callingUid != AID_AUDIOSERVER || currentPid != getpid())) {
4428 ALOGW("%s: attempt to create a spatializer effect from uid/pid %d/%d",
4429 __func__, callingUid, currentPid);
4430 lStatus = PERMISSION_DENIED;
4431 goto Exit;
4432 }
4433
4434 if (io == AUDIO_IO_HANDLE_NONE && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4435 // if the output returned by getOutputForEffect() is removed before we lock the
4436 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
4437 // and we will exit safely
4438 io = AudioSystem::getOutputForEffect(&descOut);
4439 ALOGV("createEffect got output %d", io);
4440 }
4441
4442 audio_utils::lock_guard _l(mutex());
4443
4444 if (sessionId == AUDIO_SESSION_DEVICE) {
4445 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
4446 ALOGV("%s device type %#x address %s", __func__, device.mType, device.getAddress());
4447 handle = mDeviceEffectManager->createEffect_l(
4448 &descOut, device, client, effectClient, mPatchPanel->patches_l(),
4449 &enabledOut, &lStatus, probe, request.notifyFramesProcessed);
4450 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4451 // remove local strong reference to Client with clientMutex() held
4452 audio_utils::lock_guard _cl(clientMutex());
4453 client.clear();
4454 } else {
4455 // handle must be valid here, but check again to be safe.
4456 if (handle.get() != nullptr) idOut = handle->id();
4457 }
4458 goto Register;
4459 }
4460
4461 // If output is not specified try to find a matching audio session ID in one of the
4462 // output threads.
4463 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4464 // because of code checking output when entering the function.
4465 // Note: io is never AUDIO_IO_HANDLE_NONE when creating an effect on an input by APM.
4466 // An AudioEffect created from the Java API will have io as AUDIO_IO_HANDLE_NONE.
4467 if (io == AUDIO_IO_HANDLE_NONE) {
4468 // look for the thread where the specified audio session is present
4469 io = findIoHandleBySessionId_l(sessionId, mPlaybackThreads);
4470 if (io == AUDIO_IO_HANDLE_NONE) {
4471 io = findIoHandleBySessionId_l(sessionId, mRecordThreads);
4472 }
4473 if (io == AUDIO_IO_HANDLE_NONE) {
4474 io = findIoHandleBySessionId_l(sessionId, mMmapThreads);
4475 }
4476
4477 // If you wish to create a Record preprocessing AudioEffect in Java,
4478 // you MUST create an AudioRecord first and keep it alive so it is picked up above.
4479 // Otherwise it will fail when created on a Playback thread by legacy
4480 // handling below. Ditto with Mmap, the associated Mmap track must be created
4481 // before creating the AudioEffect or the io handle must be specified.
4482 //
4483 // Detect if the effect is created after an AudioRecord is destroyed.
4484 if (sessionId != AUDIO_SESSION_OUTPUT_MIX
4485 && ((descOut.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)
4486 && getOrphanEffectChain_l(sessionId).get() != nullptr) {
4487 ALOGE("%s: effect %s with no specified io handle is denied because the AudioRecord"
4488 " for session %d no longer exists",
4489 __func__, descOut.name, sessionId);
4490 lStatus = PERMISSION_DENIED;
4491 goto Exit;
4492 }
4493
4494 // Legacy handling of creating an effect on an expired or made-up
4495 // session id. We think that it is a Playback effect.
4496 //
4497 // If no output thread contains the requested session ID, park the effect to
4498 // the orphan chains. The effect chain will be moved to the correct output
4499 // thread when a track with the same session ID is created.
4500 if (io == AUDIO_IO_HANDLE_NONE) {
4501 if (probe) {
4502 // In probe mode, as no compatible thread found, exit with error.
4503 lStatus = BAD_VALUE;
4504 goto Exit;
4505 }
4506 ALOGV("%s() got io %d for effect %s", __func__, io, descOut.name);
4507 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
4508 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
4509 handle = createOrphanEffect_l(client, effectClient, priority, sessionId,
4510 &descOut, &enabledOut, &lStatus, pinned,
4511 request.notifyFramesProcessed);
4512 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4513 // remove local strong reference to Client with clientMutex() held
4514 audio_utils::lock_guard _cl(clientMutex());
4515 client.clear();
4516 }
4517 goto Register;
4518 }
4519 ALOGV("createEffect() got io %d for effect %s", io, descOut.name);
4520 } else if (checkPlaybackThread_l(io) != nullptr
4521 && sessionId != AUDIO_SESSION_OUTPUT_STAGE) {
4522 // allow only one effect chain per sessionId on mPlaybackThreads.
4523 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4524 const audio_io_handle_t checkIo = mPlaybackThreads.keyAt(i);
4525 if (io == checkIo) {
4526 if (hapticPlaybackRequired
4527 && mPlaybackThreads.valueAt(i)
4528 ->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4529 ALOGE("%s: haptic playback thread is required while the required playback "
4530 "thread(io=%d) doesn't support", __func__, (int)io);
4531 lStatus = BAD_VALUE;
4532 goto Exit;
4533 }
4534 continue;
4535 }
4536 const uint32_t sessionType =
4537 mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId);
4538 if ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0) {
4539 ALOGE("%s: effect %s io %d denied because session %d effect exists on io %d",
4540 __func__, descOut.name, (int) io, (int) sessionId, (int) checkIo);
4541 android_errorWriteLog(0x534e4554, "123237974");
4542 lStatus = BAD_VALUE;
4543 goto Exit;
4544 }
4545 }
4546 }
4547 IAfThreadBase* thread = checkRecordThread_l(io);
4548 if (thread == NULL) {
4549 thread = checkPlaybackThread_l(io);
4550 if (thread == NULL) {
4551 thread = checkMmapThread_l(io);
4552 if (thread == NULL) {
4553 ALOGE("createEffect() unknown output thread");
4554 lStatus = BAD_VALUE;
4555 goto Exit;
4556 }
4557 }
4558 }
4559 if (thread->type() == IAfThreadBase::RECORD || sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4560 // Check if one effect chain was awaiting for an effect to be created on this
4561 // session and used it instead of creating a new one.
4562 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
4563 if (chain != 0) {
4564 audio_utils::lock_guard _l2(thread->mutex());
4565 thread->addEffectChain_l(chain);
4566 }
4567 }
4568
4569 sp<Client> client = registerClient(currentPid, adjAttributionSource.uid);
4570
4571 // create effect on selected output thread
4572 bool pinned = !audio_is_global_session(sessionId) && isSessionAcquired_l(sessionId);
4573 IAfThreadBase* oriThread = nullptr;
4574 if (hapticPlaybackRequired && thread->hapticChannelMask() == AUDIO_CHANNEL_NONE) {
4575 IAfThreadBase* const hapticThread = hapticPlaybackThread_l();
4576 if (hapticThread == nullptr) {
4577 ALOGE("%s haptic thread not found while it is required", __func__);
4578 lStatus = INVALID_OPERATION;
4579 goto Exit;
4580 }
4581 if (hapticThread != thread) {
4582 // Force to use haptic thread for haptic-generating effect.
4583 oriThread = thread;
4584 thread = hapticThread;
4585 }
4586 }
4587 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4588 &descOut, &enabledOut, &lStatus, pinned, probe,
4589 request.notifyFramesProcessed);
4590 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4591 // remove local strong reference to Client with clientMutex() held
4592 audio_utils::lock_guard _cl(clientMutex());
4593 client.clear();
4594 } else {
4595 // handle must be valid here, but check again to be safe.
4596 if (handle.get() != nullptr) idOut = handle->id();
4597 // Invalidate audio session when haptic playback is created.
4598 if (hapticPlaybackRequired && oriThread != nullptr) {
4599 // invalidateTracksForAudioSession will trigger locking the thread.
4600 oriThread->invalidateTracksForAudioSession(sessionId);
4601 }
4602 }
4603 }
4604
4605 Register:
4606 if (!probe && (lStatus == NO_ERROR || lStatus == ALREADY_EXISTS)) {
4607 if (lStatus == ALREADY_EXISTS) {
4608 response->alreadyExists = true;
4609 lStatus = NO_ERROR;
4610 } else {
4611 response->alreadyExists = false;
4612 }
4613 // Check CPU and memory usage
4614 sp<IAfEffectBase> effect = handle->effect().promote();
4615 if (effect != nullptr) {
4616 status_t rStatus = effect->updatePolicyState();
4617 if (rStatus != NO_ERROR) {
4618 lStatus = rStatus;
4619 }
4620 }
4621 } else {
4622 handle.clear();
4623 }
4624
4625 response->id = idOut;
4626 response->enabled = enabledOut != 0;
4627 response->effect = handle.get() ? handle->asIEffect() : nullptr;
4628 response->desc = VALUE_OR_RETURN_STATUS(
4629 legacy2aidl_effect_descriptor_t_EffectDescriptor(descOut));
4630
4631 Exit:
4632 return lStatus;
4633 }
4634
createOrphanEffect_l(const sp<Client> & client,const sp<IEffectClient> & effectClient,int32_t priority,audio_session_t sessionId,effect_descriptor_t * desc,int * enabled,status_t * status,bool pinned,bool notifyFramesProcessed)4635 sp<IAfEffectHandle> AudioFlinger::createOrphanEffect_l(
4636 const sp<Client>& client,
4637 const sp<IEffectClient>& effectClient,
4638 int32_t priority,
4639 audio_session_t sessionId,
4640 effect_descriptor_t *desc,
4641 int *enabled,
4642 status_t *status,
4643 bool pinned,
4644 bool notifyFramesProcessed)
4645 {
4646 ALOGV("%s effectClient %p, priority %d, sessionId %d, factory %p",
4647 __func__, effectClient.get(), priority, sessionId, mEffectsFactoryHal.get());
4648
4649 // Check if an orphan effect chain exists for this session or create new chain for this session
4650 sp<IAfEffectModule> effect;
4651 sp<IAfEffectChain> chain = getOrphanEffectChain_l(sessionId);
4652 bool chainCreated = false;
4653 if (chain == nullptr) {
4654 chain = IAfEffectChain::create(/* ThreadBase= */ nullptr, sessionId, this);
4655 chainCreated = true;
4656 } else {
4657 effect = chain->getEffectFromDesc(desc);
4658 }
4659 bool effectCreated = false;
4660 if (effect == nullptr) {
4661 audio_unique_id_t effectId = nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
4662 // create a new effect module if none present in the chain
4663 status_t llStatus =
4664 chain->createEffect(effect, desc, effectId, sessionId, pinned);
4665 if (llStatus != NO_ERROR) {
4666 *status = llStatus;
4667 // if the effect chain was not created here, put it back
4668 if (!chainCreated) {
4669 putOrphanEffectChain_l(chain);
4670 }
4671 return nullptr;
4672 }
4673 effect->setMode(getMode());
4674
4675 if (effect->isHapticGenerator()) {
4676 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
4677 // for the HapticGenerator.
4678 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
4679 getDefaultVibratorInfo_l();
4680 if (defaultVibratorInfo) {
4681 // Only set the vibrator info when it is a valid one.
4682 audio_utils::lock_guard _cl(chain->mutex());
4683 effect->setVibratorInfo_l(*defaultVibratorInfo);
4684 }
4685 }
4686 effectCreated = true;
4687 }
4688 // create effect handle and connect it to effect module
4689 sp<IAfEffectHandle> handle =
4690 IAfEffectHandle::create(effect, client, effectClient, priority, notifyFramesProcessed);
4691 status_t lStatus = handle->initCheck();
4692 if (lStatus == OK) {
4693 lStatus = effect->addHandle(handle.get());
4694 }
4695 // in case of lStatus error, EffectHandle will still return and caller should do the clear
4696 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4697 if (effectCreated) {
4698 chain->removeEffect(effect);
4699 }
4700 // if the effect chain was not created here, put it back
4701 if (!chainCreated) {
4702 putOrphanEffectChain_l(chain);
4703 }
4704 } else {
4705 if (enabled != NULL) {
4706 *enabled = (int)effect->isEnabled();
4707 }
4708 putOrphanEffectChain_l(chain);
4709 }
4710 *status = lStatus;
4711 return handle;
4712 }
4713
moveEffects(audio_session_t sessionId,audio_io_handle_t srcIo,audio_io_handle_t dstIo)4714 status_t AudioFlinger::moveEffects(audio_session_t sessionId, audio_io_handle_t srcIo,
4715 audio_io_handle_t dstIo)
4716 NO_THREAD_SAFETY_ANALYSIS
4717 {
4718 ALOGV("%s() session %d, srcIo %d, dstIo %d", __func__, sessionId, srcIo, dstIo);
4719 audio_utils::lock_guard _l(mutex());
4720 if (srcIo == dstIo) {
4721 ALOGW("%s() same dst and src outputs %d", __func__, dstIo);
4722 return NO_ERROR;
4723 }
4724 IAfRecordThread* const srcRecordThread = checkRecordThread_l(srcIo);
4725 IAfRecordThread* const dstRecordThread = checkRecordThread_l(dstIo);
4726 if (srcRecordThread != nullptr || dstRecordThread != nullptr) {
4727 if (srcRecordThread != nullptr) {
4728 srcRecordThread->mutex().lock();
4729 }
4730 if (dstRecordThread != nullptr) {
4731 dstRecordThread->mutex().lock();
4732 }
4733 status_t ret = moveEffectChain_ll(sessionId, srcRecordThread, dstRecordThread);
4734 if (srcRecordThread != nullptr) {
4735 srcRecordThread->mutex().unlock();
4736 }
4737 if (dstRecordThread != nullptr) {
4738 dstRecordThread->mutex().unlock();
4739 }
4740 return ret;
4741 }
4742
4743 IAfPlaybackThread* dstThread = checkPlaybackThread_l(dstIo);
4744 if (dstThread == nullptr) {
4745 ALOGW("%s() bad dstIo %d", __func__, dstIo);
4746 return BAD_VALUE;
4747 }
4748
4749 IAfPlaybackThread* srcThread = checkPlaybackThread_l(srcIo);
4750 sp<IAfEffectChain> orphanChain = getOrphanEffectChain_l(sessionId);
4751 if (srcThread == nullptr && orphanChain == nullptr && sessionId == AUDIO_SESSION_OUTPUT_MIX) {
4752 ALOGW("%s() AUDIO_SESSION_OUTPUT_MIX not found in orphans, checking other mix", __func__);
4753 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4754 const sp<IAfPlaybackThread> pt = mPlaybackThreads.valueAt(i);
4755 const uint32_t sessionType = pt->hasAudioSession(AUDIO_SESSION_OUTPUT_MIX);
4756 if ((pt->type() == IAfThreadBase::MIXER || pt->type() == IAfThreadBase::OFFLOAD) &&
4757 ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0)) {
4758 srcThread = pt.get();
4759 if (srcThread == dstThread) {
4760 ALOGD("%s() same dst and src threads, ignoring move", __func__);
4761 return NO_ERROR;
4762 }
4763 ALOGW("%s() found srcOutput %d hosting AUDIO_SESSION_OUTPUT_MIX", __func__,
4764 pt->id());
4765 break;
4766 }
4767 }
4768 }
4769 if (srcThread == nullptr && orphanChain == nullptr) {
4770 ALOGW("moveEffects() bad srcIo %d", srcIo);
4771 return BAD_VALUE;
4772 }
4773 // dstThread pointer validity has already been checked
4774 if (orphanChain != nullptr) {
4775 audio_utils::scoped_lock _ll(dstThread->mutex());
4776 return moveEffectChain_ll(sessionId, nullptr, dstThread, orphanChain.get());
4777 }
4778 // srcThread pointer validity has already been checked
4779 audio_utils::scoped_lock _ll(dstThread->mutex(), srcThread->mutex());
4780 return moveEffectChain_ll(sessionId, srcThread, dstThread);
4781 }
4782
4783
setEffectSuspended(int effectId,audio_session_t sessionId,bool suspended)4784 void AudioFlinger::setEffectSuspended(int effectId,
4785 audio_session_t sessionId,
4786 bool suspended)
4787 {
4788 audio_utils::lock_guard _l(mutex());
4789
4790 sp<IAfThreadBase> thread = getEffectThread_l(sessionId, effectId);
4791 if (thread == nullptr) {
4792 return;
4793 }
4794 audio_utils::lock_guard _sl(thread->mutex());
4795 if (const auto& effect = thread->getEffect_l(sessionId, effectId)) {
4796 thread->setEffectSuspended_l(&effect->desc().type, suspended, sessionId);
4797 }
4798 }
4799
4800
4801 // moveEffectChain_ll must be called with the AudioFlinger::mutex()
4802 // and both srcThread and dstThread mutex()s held
moveEffectChain_ll(audio_session_t sessionId,IAfPlaybackThread * srcThread,IAfPlaybackThread * dstThread,IAfEffectChain * srcChain)4803 status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
4804 IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread,
4805 IAfEffectChain* srcChain)
4806 {
4807 ALOGV("%s: session %d from thread %p to thread %p %s",
4808 __func__, sessionId, srcThread, dstThread,
4809 (srcChain != nullptr ? "from specific chain" : ""));
4810 ALOG_ASSERT((srcThread != nullptr) != (srcChain != nullptr),
4811 "no source provided for source chain");
4812
4813 sp<IAfEffectChain> chain =
4814 srcChain != nullptr ? srcChain : srcThread->getEffectChain_l(sessionId);
4815 if (chain == 0) {
4816 ALOGW("%s: effect chain for session %d not on source thread %p",
4817 __func__, sessionId, srcThread);
4818 return INVALID_OPERATION;
4819 }
4820
4821 // Check whether the destination thread and all effects in the chain are compatible
4822 if (!chain->isCompatibleWithThread_l(dstThread)) {
4823 ALOGW("%s: effect chain failed because"
4824 " destination thread %p is not compatible with effects in the chain",
4825 __func__, dstThread);
4826 return INVALID_OPERATION;
4827 }
4828
4829 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
4830 // so that a new chain is created with correct parameters when first effect is added. This is
4831 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
4832 // removed.
4833 // TODO(b/216875016): consider holding the effect chain locks for the duration of the move.
4834 if (srcThread != nullptr) {
4835 srcThread->removeEffectChain_l(chain);
4836 }
4837 // transfer all effects one by one so that new effect chain is created on new thread with
4838 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
4839 sp<IAfEffectChain> dstChain;
4840 Vector<sp<IAfEffectModule>> removed;
4841 status_t status = NO_ERROR;
4842 std::string errorString;
4843 // process effects one by one.
4844 for (sp<IAfEffectModule> effect = chain->getEffectFromId_l(0); effect != nullptr;
4845 effect = chain->getEffectFromId_l(0)) {
4846 if (srcThread != nullptr) {
4847 srcThread->removeEffect_l(effect);
4848 } else {
4849 chain->removeEffect(effect);
4850 }
4851 removed.add(effect);
4852 status = dstThread->addEffect_ll(effect);
4853 if (status != NO_ERROR) {
4854 errorString = StringPrintf(
4855 "cannot add effect %p to destination thread", effect.get());
4856 break;
4857 }
4858 // if the move request is not received from audio policy manager, the effect must be
4859 // re-registered with the new strategy and output.
4860
4861 // We obtain the dstChain once the effect is on the new thread.
4862 if (dstChain == nullptr) {
4863 dstChain = effect->getCallback()->chain().promote();
4864 if (dstChain == nullptr) {
4865 errorString = StringPrintf("cannot get chain from effect %p", effect.get());
4866 status = NO_INIT;
4867 break;
4868 }
4869 }
4870 }
4871
4872 size_t restored = 0;
4873 if (status != NO_ERROR) {
4874 dstChain.clear(); // dstChain is now from the srcThread (could be recreated).
4875 for (const auto& effect : removed) {
4876 dstThread->removeEffect_l(effect); // Note: Depending on error location, the last
4877 // effect may not have been placed on dstThread.
4878 if (srcThread != nullptr && srcThread->addEffect_ll(effect) == NO_ERROR) {
4879 ++restored;
4880 if (dstChain == nullptr) {
4881 dstChain = effect->getCallback()->chain().promote();
4882 }
4883 }
4884 }
4885 }
4886
4887 // After all the effects have been moved to new thread (or put back) we restart the effects
4888 // because removeEffect_l() has stopped the effect if it is currently active.
4889 size_t started = 0;
4890 if (dstChain != nullptr && !removed.empty()) {
4891 // If we do not take the dstChain lock, it is possible that processing is ongoing
4892 // while we are starting the effect. This can cause glitches with volume,
4893 // see b/202360137.
4894 dstChain->mutex().lock();
4895 for (const auto& effect : removed) {
4896 if (effect->state() == IAfEffectModule::ACTIVE ||
4897 effect->state() == IAfEffectModule::STOPPING) {
4898 ++started;
4899 effect->start_l();
4900 }
4901 }
4902 dstChain->mutex().unlock();
4903 }
4904
4905 if (status != NO_ERROR) {
4906 if (errorString.empty()) {
4907 errorString = StringPrintf("%s: failed status %d", __func__, status);
4908 }
4909 ALOGW("%s: %s unsuccessful move of session %d from %s %p to dstThread %p "
4910 "(%zu effects removed from srcThread, %zu effects restored to srcThread, "
4911 "%zu effects started)",
4912 __func__, errorString.c_str(), sessionId,
4913 (srcThread != nullptr ? "srcThread" : "srcChain"),
4914 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
4915 removed.size(), restored, started);
4916 } else {
4917 ALOGD("%s: successful move of session %d from %s %p to dstThread %p "
4918 "(%zu effects moved, %zu effects started)",
4919 __func__, sessionId, (srcThread != nullptr ? "srcThread" : "srcChain"),
4920 (srcThread != nullptr ? (void*) srcThread : (void*) srcChain), dstThread,
4921 removed.size(), started);
4922 }
4923 return status;
4924 }
4925
4926
4927 // moveEffectChain_ll must be called with both srcThread (if not null) and dstThread (if not null)
4928 // mutex()s held
moveEffectChain_ll(audio_session_t sessionId,IAfRecordThread * srcThread,IAfRecordThread * dstThread)4929 status_t AudioFlinger::moveEffectChain_ll(audio_session_t sessionId,
4930 IAfRecordThread* srcThread, IAfRecordThread* dstThread)
4931 {
4932 sp<IAfEffectChain> chain = nullptr;
4933 if (srcThread != 0) {
4934 const Vector<sp<IAfEffectChain>> effectChains = srcThread->getEffectChains_l();
4935 for (size_t i = 0; i < effectChains.size(); i ++) {
4936 if (effectChains[i]->sessionId() == sessionId) {
4937 chain = effectChains[i];
4938 break;
4939 }
4940 }
4941 ALOGV_IF(effectChains.size() == 0, "%s: no effect chain on io=%d", __func__,
4942 srcThread->id());
4943 if (chain == nullptr) {
4944 ALOGE("%s wrong session id %d", __func__, sessionId);
4945 return BAD_VALUE;
4946 }
4947 ALOGV("%s: removing effect chain for session=%d io=%d", __func__, sessionId,
4948 srcThread->id());
4949 srcThread->removeEffectChain_l(chain);
4950 } else {
4951 chain = getOrphanEffectChain_l(sessionId);
4952 if (chain == nullptr) {
4953 ALOGE("%s: no orphan effect chain found for session=%d", __func__, sessionId);
4954 return BAD_VALUE;
4955 }
4956 }
4957 if (dstThread != 0) {
4958 ALOGV("%s: adding effect chain for session=%d on io=%d", __func__, sessionId,
4959 dstThread->id());
4960 dstThread->addEffectChain_l(chain);
4961 return NO_ERROR;
4962 }
4963 ALOGV("%s: parking to orphan effect chain for session=%d", __func__, sessionId);
4964 putOrphanEffectChain_l(chain);
4965 return NO_ERROR;
4966 }
4967
moveAuxEffectToIo(int EffectId,const sp<IAfPlaybackThread> & dstThread,sp<IAfPlaybackThread> * srcThread)4968 status_t AudioFlinger::moveAuxEffectToIo(int EffectId,
4969 const sp<IAfPlaybackThread>& dstThread, sp<IAfPlaybackThread>* srcThread)
4970 {
4971 status_t status = NO_ERROR;
4972 audio_utils::lock_guard _l(mutex());
4973 const sp<IAfThreadBase> threadBase = getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
4974 const sp<IAfPlaybackThread> thread = threadBase ? threadBase->asIAfPlaybackThread() : nullptr;
4975
4976 if (EffectId != 0 && thread != 0 && dstThread != thread.get()) {
4977 audio_utils::scoped_lock _ll(dstThread->mutex(), thread->mutex());
4978 sp<IAfEffectChain> srcChain = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4979 sp<IAfEffectChain> dstChain;
4980 if (srcChain == 0) {
4981 return INVALID_OPERATION;
4982 }
4983
4984 sp<IAfEffectModule> effect = srcChain->getEffectFromId_l(EffectId);
4985 if (effect == 0) {
4986 return INVALID_OPERATION;
4987 }
4988 thread->removeEffect_l(effect);
4989 status = dstThread->addEffect_ll(effect);
4990 if (status != NO_ERROR) {
4991 thread->addEffect_ll(effect);
4992 status = INVALID_OPERATION;
4993 goto Exit;
4994 }
4995
4996 dstChain = effect->getCallback()->chain().promote();
4997 if (dstChain == 0) {
4998 thread->addEffect_ll(effect);
4999 status = INVALID_OPERATION;
5000 }
5001
5002 Exit:
5003 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5004 if (effect->state() == IAfEffectModule::ACTIVE ||
5005 effect->state() == IAfEffectModule::STOPPING) {
5006 effect->start_l();
5007 }
5008 }
5009
5010 if (status == NO_ERROR && srcThread != nullptr) {
5011 *srcThread = thread;
5012 }
5013 return status;
5014 }
5015
isNonOffloadableGlobalEffectEnabled_l() const5016 bool AudioFlinger::isNonOffloadableGlobalEffectEnabled_l() const
5017 {
5018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5019 const auto thread = mPlaybackThreads.valueAt(i);
5020 audio_utils::lock_guard l(thread->mutex());
5021 const sp<IAfEffectChain> ec = thread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5022 if (ec != 0 && ec->isNonOffloadableEnabled()) {
5023 return true;
5024 }
5025 }
5026 return false;
5027 }
5028
onNonOffloadableGlobalEffectEnable()5029 void AudioFlinger::onNonOffloadableGlobalEffectEnable()
5030 {
5031 audio_utils::lock_guard _l(mutex());
5032
5033 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5034 const sp<IAfPlaybackThread> t = mPlaybackThreads.valueAt(i);
5035 if (t->type() == IAfThreadBase::OFFLOAD) {
5036 t->invalidateTracks(AUDIO_STREAM_MUSIC);
5037 }
5038 }
5039
5040 }
5041
putOrphanEffectChain_l(const sp<IAfEffectChain> & chain)5042 status_t AudioFlinger::putOrphanEffectChain_l(const sp<IAfEffectChain>& chain)
5043 {
5044 // clear possible suspended state before parking the chain so that it starts in default state
5045 // when attached to a new record thread
5046 chain->setEffectSuspended_l(FX_IID_AEC, false);
5047 chain->setEffectSuspended_l(FX_IID_NS, false);
5048
5049 audio_session_t session = chain->sessionId();
5050 ssize_t index = mOrphanEffectChains.indexOfKey(session);
5051 ALOGV("putOrphanEffectChain_l session %d index %zd", session, index);
5052 if (index >= 0) {
5053 ALOGW("putOrphanEffectChain_l chain for session %d already present", session);
5054 return ALREADY_EXISTS;
5055 }
5056 mOrphanEffectChains.add(session, chain);
5057 return NO_ERROR;
5058 }
5059
getOrphanEffectChain_l(audio_session_t session)5060 sp<IAfEffectChain> AudioFlinger::getOrphanEffectChain_l(audio_session_t session)
5061 {
5062 sp<IAfEffectChain> chain;
5063 ssize_t index = mOrphanEffectChains.indexOfKey(session);
5064 ALOGV("getOrphanEffectChain_l session %d index %zd", session, index);
5065 if (index >= 0) {
5066 chain = mOrphanEffectChains.valueAt(index);
5067 mOrphanEffectChains.removeItemsAt(index);
5068 }
5069 return chain;
5070 }
5071
updateOrphanEffectChains(const sp<IAfEffectModule> & effect)5072 bool AudioFlinger::updateOrphanEffectChains(const sp<IAfEffectModule>& effect)
5073 {
5074 audio_utils::lock_guard _l(mutex());
5075 return updateOrphanEffectChains_l(effect);
5076 }
5077
updateOrphanEffectChains_l(const sp<IAfEffectModule> & effect)5078 bool AudioFlinger::updateOrphanEffectChains_l(const sp<IAfEffectModule>& effect)
5079 {
5080 audio_session_t session = effect->sessionId();
5081 ssize_t index = mOrphanEffectChains.indexOfKey(session);
5082 ALOGV("updateOrphanEffectChains session %d index %zd", session, index);
5083 if (index >= 0) {
5084 sp<IAfEffectChain> chain = mOrphanEffectChains.valueAt(index);
5085 if (chain->removeEffect(effect, true) == 0) {
5086 ALOGV("updateOrphanEffectChains removing effect chain at index %zd", index);
5087 mOrphanEffectChains.removeItemsAt(index);
5088 }
5089 return true;
5090 }
5091 return false;
5092 }
5093
5094 // ----------------------------------------------------------------------------
5095 // from PatchPanel
5096
5097 /* List connected audio ports and their attributes */
listAudioPorts(unsigned int * num_ports,struct audio_port * ports) const5098 status_t AudioFlinger::listAudioPorts(unsigned int* num_ports,
5099 struct audio_port* ports) const
5100 {
5101 audio_utils::lock_guard _l(mutex());
5102 return mPatchPanel->listAudioPorts_l(num_ports, ports);
5103 }
5104
5105 /* Get supported attributes for a given audio port */
getAudioPort(struct audio_port_v7 * port) const5106 status_t AudioFlinger::getAudioPort(struct audio_port_v7* port) const {
5107 const status_t status = AudioValidator::validateAudioPort(*port);
5108 if (status != NO_ERROR) {
5109 return status;
5110 }
5111
5112 audio_utils::lock_guard _l(mutex());
5113 return mPatchPanel->getAudioPort_l(port);
5114 }
5115
5116 /* Connect a patch between several source and sink ports */
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle)5117 status_t AudioFlinger::createAudioPatch(
5118 const struct audio_patch* patch, audio_patch_handle_t* handle)
5119 {
5120 const status_t status = AudioValidator::validateAudioPatch(*patch);
5121 if (status != NO_ERROR) {
5122 return status;
5123 }
5124
5125 audio_utils::lock_guard _l(mutex());
5126 return mPatchPanel->createAudioPatch_l(patch, handle);
5127 }
5128
5129 /* Disconnect a patch */
releaseAudioPatch(audio_patch_handle_t handle)5130 status_t AudioFlinger::releaseAudioPatch(audio_patch_handle_t handle)
5131 {
5132 audio_utils::lock_guard _l(mutex());
5133 return mPatchPanel->releaseAudioPatch_l(handle);
5134 }
5135
5136 /* List connected audio ports and they attributes */
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches) const5137 status_t AudioFlinger::listAudioPatches(
5138 unsigned int* num_patches, struct audio_patch* patches) const
5139 {
5140 audio_utils::lock_guard _l(mutex());
5141 return mPatchPanel->listAudioPatches_l(num_patches, patches);
5142 }
5143
5144 /**
5145 * Get the attributes of the mix port when connecting to the given device port.
5146 */
getAudioMixPort(const struct audio_port_v7 * devicePort,struct audio_port_v7 * mixPort) const5147 status_t AudioFlinger::getAudioMixPort(const struct audio_port_v7 *devicePort,
5148 struct audio_port_v7 *mixPort) const {
5149 if (status_t status = AudioValidator::validateAudioPort(*devicePort); status != NO_ERROR) {
5150 ALOGE("%s, invalid device port, status=%d", __func__, status);
5151 return status;
5152 }
5153 if (status_t status = AudioValidator::validateAudioPort(*mixPort); status != NO_ERROR) {
5154 ALOGE("%s, invalid mix port, status=%d", __func__, status);
5155 return status;
5156 }
5157
5158 audio_utils::lock_guard _l(mutex());
5159 return mPatchPanel->getAudioMixPort_l(devicePort, mixPort);
5160 }
5161
setTracksInternalMute(const std::vector<media::TrackInternalMuteInfo> & tracksInternalMute)5162 status_t AudioFlinger::setTracksInternalMute(
5163 const std::vector<media::TrackInternalMuteInfo>& tracksInternalMute) {
5164 audio_utils::lock_guard _l(mutex());
5165 ALOGV("%s", __func__);
5166
5167 std::map<audio_port_handle_t, bool> tracksInternalMuteMap;
5168 for (const auto& trackInternalMute : tracksInternalMute) {
5169 audio_port_handle_t portId = VALUE_OR_RETURN_STATUS(
5170 aidl2legacy_int32_t_audio_port_handle_t(trackInternalMute.portId));
5171 tracksInternalMuteMap.emplace(portId, trackInternalMute.muted);
5172 }
5173 for (size_t i = 0; i < mPlaybackThreads.size() && !tracksInternalMuteMap.empty(); i++) {
5174 mPlaybackThreads.valueAt(i)->setTracksInternalMute(&tracksInternalMuteMap);
5175 }
5176 return NO_ERROR;
5177 }
5178
resetReferencesForTest()5179 status_t AudioFlinger::resetReferencesForTest() {
5180 mDeviceEffectManager.clear();
5181 mPatchPanel.clear();
5182 mMelReporter->resetReferencesForTest();
5183 return NO_ERROR;
5184 }
5185
5186 // ----------------------------------------------------------------------------
5187
onTransactWrapper(TransactionCode code,const Parcel & data,uint32_t flags,const std::function<status_t ()> & delegate)5188 status_t AudioFlinger::onTransactWrapper(TransactionCode code,
5189 [[maybe_unused]] const Parcel& data,
5190 [[maybe_unused]] uint32_t flags,
5191 const std::function<status_t()>& delegate) {
5192 // make sure transactions reserved to AudioPolicyManager do not come from other processes
5193 switch (code) {
5194 case TransactionCode::SET_STREAM_VOLUME:
5195 case TransactionCode::SET_STREAM_MUTE:
5196 case TransactionCode::OPEN_OUTPUT:
5197 case TransactionCode::OPEN_DUPLICATE_OUTPUT:
5198 case TransactionCode::CLOSE_OUTPUT:
5199 case TransactionCode::SUSPEND_OUTPUT:
5200 case TransactionCode::RESTORE_OUTPUT:
5201 case TransactionCode::OPEN_INPUT:
5202 case TransactionCode::CLOSE_INPUT:
5203 case TransactionCode::SET_VOICE_VOLUME:
5204 case TransactionCode::MOVE_EFFECTS:
5205 case TransactionCode::SET_EFFECT_SUSPENDED:
5206 case TransactionCode::LOAD_HW_MODULE:
5207 case TransactionCode::GET_AUDIO_PORT:
5208 case TransactionCode::CREATE_AUDIO_PATCH:
5209 case TransactionCode::RELEASE_AUDIO_PATCH:
5210 case TransactionCode::LIST_AUDIO_PATCHES:
5211 case TransactionCode::SET_AUDIO_PORT_CONFIG:
5212 case TransactionCode::SET_RECORD_SILENCED:
5213 case TransactionCode::AUDIO_POLICY_READY:
5214 case TransactionCode::SET_DEVICE_CONNECTED_STATE:
5215 case TransactionCode::SET_REQUESTED_LATENCY_MODE:
5216 case TransactionCode::GET_SUPPORTED_LATENCY_MODES:
5217 case TransactionCode::INVALIDATE_TRACKS:
5218 case TransactionCode::GET_AUDIO_POLICY_CONFIG:
5219 case TransactionCode::GET_AUDIO_MIX_PORT:
5220 case TransactionCode::SET_TRACKS_INTERNAL_MUTE:
5221 case TransactionCode::RESET_REFERENCES_FOR_TEST:
5222 case TransactionCode::SET_PORTS_VOLUME:
5223 ALOGW("%s: transaction %d received from PID %d",
5224 __func__, static_cast<int>(code), IPCThreadState::self()->getCallingPid());
5225 // return status only for non void methods
5226 switch (code) {
5227 case TransactionCode::SET_RECORD_SILENCED:
5228 case TransactionCode::SET_EFFECT_SUSPENDED:
5229 break;
5230 default:
5231 return INVALID_OPERATION;
5232 }
5233 // Fail silently in these cases.
5234 return OK;
5235 default:
5236 break;
5237 }
5238
5239 // make sure the following transactions come from system components
5240 switch (code) {
5241 case TransactionCode::SET_MASTER_VOLUME:
5242 case TransactionCode::SET_MASTER_MUTE:
5243 case TransactionCode::MASTER_MUTE:
5244 case TransactionCode::GET_SOUND_DOSE_INTERFACE:
5245 case TransactionCode::SET_MODE:
5246 case TransactionCode::SET_MIC_MUTE:
5247 case TransactionCode::SET_LOW_RAM_DEVICE:
5248 case TransactionCode::SYSTEM_READY:
5249 case TransactionCode::SET_AUDIO_HAL_PIDS:
5250 case TransactionCode::SET_VIBRATOR_INFOS:
5251 case TransactionCode::UPDATE_SECONDARY_OUTPUTS:
5252 case TransactionCode::SET_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5253 case TransactionCode::IS_BLUETOOTH_VARIABLE_LATENCY_ENABLED:
5254 case TransactionCode::SUPPORTS_BLUETOOTH_VARIABLE_LATENCY: {
5255 if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
5256 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
5257 __func__, static_cast<int>(code),
5258 IPCThreadState::self()->getCallingPid(),
5259 IPCThreadState::self()->getCallingUid());
5260 // return status only for non-void methods
5261 switch (code) {
5262 case TransactionCode::SYSTEM_READY:
5263 break;
5264 default:
5265 return INVALID_OPERATION;
5266 }
5267 // Fail silently in these cases.
5268 return OK;
5269 }
5270 } break;
5271 default:
5272 break;
5273 }
5274
5275 // List of relevant events that trigger log merging.
5276 // Log merging should activate during audio activity of any kind. This are considered the
5277 // most relevant events.
5278 // TODO should select more wisely the items from the list
5279 switch (code) {
5280 case TransactionCode::CREATE_TRACK:
5281 case TransactionCode::CREATE_RECORD:
5282 case TransactionCode::SET_MASTER_VOLUME:
5283 case TransactionCode::SET_MASTER_MUTE:
5284 case TransactionCode::SET_MIC_MUTE:
5285 case TransactionCode::SET_PARAMETERS:
5286 case TransactionCode::CREATE_EFFECT:
5287 case TransactionCode::SYSTEM_READY: {
5288 requestLogMerge();
5289 break;
5290 }
5291 default:
5292 break;
5293 }
5294
5295 const std::string methodName = getIAudioFlingerStatistics().getMethodForCode(code);
5296 mediautils::TimeCheck check(
5297 std::string("IAudioFlinger::").append(methodName),
5298 [code, methodName](bool timeout, float elapsedMs) { // don't move methodName.
5299 if (timeout) {
5300 mediametrics::LogItem(mMetricsId)
5301 .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_TIMEOUT)
5302 .set(AMEDIAMETRICS_PROP_METHODCODE, int64_t(code))
5303 .set(AMEDIAMETRICS_PROP_METHODNAME, methodName.c_str())
5304 .record();
5305 } else {
5306 getIAudioFlingerStatistics().event(code, elapsedMs);
5307 }
5308 }, mediautils::TimeCheck::getDefaultTimeoutDuration(),
5309 mediautils::TimeCheck::getDefaultSecondChanceDuration(),
5310 !property_get_bool("audio.timecheck.disabled", false) /* crashOnTimeout */);
5311
5312 return delegate();
5313 }
5314
5315 } // namespace android
5316