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