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