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