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 #pragma once 19 20 // Classes and interfaces directly used. 21 #include "Client.h" 22 #include "DeviceEffectManager.h" 23 #include "EffectConfiguration.h" 24 #include "IAfEffect.h" 25 #include "IAfPatchPanel.h" 26 #include "IAfThread.h" 27 #include "IAfTrack.h" 28 #include "MelReporter.h" 29 #include "PatchCommandThread.h" 30 31 // External classes 32 #include <audio_utils/mutex.h> 33 #include <audio_utils/FdToString.h> 34 #include <audio_utils/SimpleLog.h> 35 #include <media/IAudioFlinger.h> 36 #include <media/IAudioPolicyServiceLocal.h> 37 #include <media/MediaMetricsItem.h> 38 #include <media/audiohal/DevicesFactoryHalInterface.h> 39 #include <mediautils/ServiceUtilities.h> 40 #include <mediautils/Synchronization.h> 41 42 // not needed with the includes above, added to prevent transitive include dependency. 43 #include <utils/KeyedVector.h> 44 #include <utils/String16.h> 45 #include <atomic> 46 #include <functional> 47 #include <map> 48 #include <optional> 49 #include <set> 50 51 namespace android { 52 53 class AudioFlinger 54 : public AudioFlingerServerAdapter::Delegate // IAudioFlinger client interface 55 , public IAfClientCallback 56 , public IAfDeviceEffectManagerCallback 57 , public IAfMelReporterCallback 58 , public IAfPatchPanelCallback 59 , public IAfThreadCallback 60 { 61 friend class sp<AudioFlinger>; 62 public: 63 static void instantiate() ANDROID_API; 64 65 status_t resetReferencesForTest(); 66 67 private: 68 69 // ---- begin IAudioFlinger interface 70 71 status_t dump(int fd, const Vector<String16>& args) final EXCLUDES_AudioFlinger_Mutex; 72 73 status_t createTrack(const media::CreateTrackRequest& input, 74 media::CreateTrackResponse& output) final EXCLUDES_AudioFlinger_Mutex; 75 76 status_t createRecord(const media::CreateRecordRequest& input, 77 media::CreateRecordResponse& output) final EXCLUDES_AudioFlinger_Mutex; 78 79 uint32_t sampleRate(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex; 80 audio_format_t format(audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex; 81 size_t frameCount(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex; 82 size_t frameCountHAL(audio_io_handle_t ioHandle) const final EXCLUDES_AudioFlinger_Mutex; 83 uint32_t latency(audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex; 84 85 status_t setMasterVolume(float value) final EXCLUDES_AudioFlinger_Mutex; 86 status_t setMasterMute(bool muted) final EXCLUDES_AudioFlinger_Mutex; 87 float masterVolume() const final EXCLUDES_AudioFlinger_Mutex; 88 bool masterMute() const final EXCLUDES_AudioFlinger_Mutex; 89 90 // Balance value must be within -1.f (left only) to 1.f (right only) inclusive. 91 status_t setMasterBalance(float balance) final EXCLUDES_AudioFlinger_Mutex; 92 status_t getMasterBalance(float* balance) const final EXCLUDES_AudioFlinger_Mutex; 93 94 status_t setStreamVolume(audio_stream_type_t stream, float value, 95 audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex; 96 status_t setStreamMute(audio_stream_type_t stream, bool muted) final 97 EXCLUDES_AudioFlinger_Mutex; 98 99 float streamVolume(audio_stream_type_t stream, 100 audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex; 101 bool streamMute(audio_stream_type_t stream) const final EXCLUDES_AudioFlinger_Mutex; 102 103 status_t setMode(audio_mode_t mode) final EXCLUDES_AudioFlinger_Mutex; 104 105 status_t setMicMute(bool state) final EXCLUDES_AudioFlinger_Mutex; 106 bool getMicMute() const final EXCLUDES_AudioFlinger_Mutex; 107 108 void setRecordSilenced(audio_port_handle_t portId, bool silenced) final 109 EXCLUDES_AudioFlinger_Mutex; 110 111 status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs) final 112 EXCLUDES_AudioFlinger_Mutex; 113 String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) const final 114 EXCLUDES_AudioFlinger_Mutex; 115 116 void registerClient(const sp<media::IAudioFlingerClient>& client) final 117 EXCLUDES_AudioFlinger_Mutex; 118 size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, 119 audio_channel_mask_t channelMask) const final EXCLUDES_AudioFlinger_Mutex; 120 121 status_t openOutput(const media::OpenOutputRequest& request, 122 media::OpenOutputResponse* response) final EXCLUDES_AudioFlinger_Mutex; 123 124 audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, 125 audio_io_handle_t output2) final EXCLUDES_AudioFlinger_Mutex; 126 127 status_t closeOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex; 128 129 status_t suspendOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex; 130 131 status_t restoreOutput(audio_io_handle_t output) final EXCLUDES_AudioFlinger_Mutex; 132 133 status_t openInput(const media::OpenInputRequest& request, 134 media::OpenInputResponse* response) final EXCLUDES_AudioFlinger_Mutex; 135 136 status_t closeInput(audio_io_handle_t input) final EXCLUDES_AudioFlinger_Mutex; 137 138 status_t setVoiceVolume(float volume) final EXCLUDES_AudioFlinger_Mutex; 139 140 status_t getRenderPosition(uint32_t* halFrames, uint32_t* dspFrames, 141 audio_io_handle_t output) const final EXCLUDES_AudioFlinger_Mutex; 142 143 uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const final 144 EXCLUDES_AudioFlinger_Mutex; 145 146 // This is the binder API. For the internal API see nextUniqueId(). 147 audio_unique_id_t newAudioUniqueId(audio_unique_id_use_t use) final 148 EXCLUDES_AudioFlinger_Mutex; 149 150 void acquireAudioSessionId(audio_session_t audioSession, pid_t pid, uid_t uid) final 151 EXCLUDES_AudioFlinger_Mutex; 152 153 void releaseAudioSessionId(audio_session_t audioSession, pid_t pid) final 154 EXCLUDES_AudioFlinger_Mutex; 155 156 status_t queryNumberEffects(uint32_t* numEffects) const final EXCLUDES_AudioFlinger_Mutex; 157 158 status_t queryEffect(uint32_t index, effect_descriptor_t* descriptor) const final 159 EXCLUDES_AudioFlinger_Mutex; 160 161 status_t getEffectDescriptor(const effect_uuid_t* pUuid, 162 const effect_uuid_t* pTypeUuid, 163 uint32_t preferredTypeFlag, 164 effect_descriptor_t* descriptor) const final EXCLUDES_AudioFlinger_Mutex; 165 166 status_t createEffect(const media::CreateEffectRequest& request, 167 media::CreateEffectResponse* response) final EXCLUDES_AudioFlinger_Mutex; 168 169 status_t moveEffects(audio_session_t sessionId, audio_io_handle_t srcOutput, 170 audio_io_handle_t dstOutput) final EXCLUDES_AudioFlinger_Mutex; 171 172 void setEffectSuspended(int effectId, 173 audio_session_t sessionId, 174 bool suspended) final EXCLUDES_AudioFlinger_Mutex; 175 176 audio_module_handle_t loadHwModule(const char* name) final EXCLUDES_AudioFlinger_Mutex; 177 178 uint32_t getPrimaryOutputSamplingRate() const final EXCLUDES_AudioFlinger_Mutex; 179 size_t getPrimaryOutputFrameCount() const final EXCLUDES_AudioFlinger_Mutex; 180 181 status_t setLowRamDevice(bool isLowRamDevice, int64_t totalMemory) final 182 EXCLUDES_AudioFlinger_Mutex; 183 184 /* Get attributes for a given audio port */ 185 status_t getAudioPort(struct audio_port_v7* port) const final EXCLUDES_AudioFlinger_Mutex; 186 187 /* Create an audio patch between several source and sink ports */ 188 status_t createAudioPatch(const struct audio_patch *patch, 189 audio_patch_handle_t* handle) final EXCLUDES_AudioFlinger_Mutex; 190 191 /* Release an audio patch */ 192 status_t releaseAudioPatch(audio_patch_handle_t handle) final EXCLUDES_AudioFlinger_Mutex; 193 194 /* List existing audio patches */ 195 status_t listAudioPatches(unsigned int* num_patches, 196 struct audio_patch* patches) const final EXCLUDES_AudioFlinger_Mutex; 197 198 /* Set audio port configuration */ 199 status_t setAudioPortConfig(const struct audio_port_config* config) final 200 EXCLUDES_AudioFlinger_Mutex; 201 202 /* Get the HW synchronization source used for an audio session */ 203 audio_hw_sync_t getAudioHwSyncForSession(audio_session_t sessionId) final 204 EXCLUDES_AudioFlinger_Mutex; 205 206 /* Indicate JAVA services are ready (scheduling, power management ...) */ 207 status_t systemReady() final EXCLUDES_AudioFlinger_Mutex; audioPolicyReady()208 status_t audioPolicyReady() final { mAudioPolicyReady.store(true); return NO_ERROR; } 209 210 status_t getMicrophones(std::vector<media::MicrophoneInfoFw>* microphones) const final 211 EXCLUDES_AudioFlinger_Mutex; 212 213 status_t setAudioHalPids(const std::vector<pid_t>& pids) final 214 EXCLUDES_AudioFlinger_Mutex; 215 216 status_t setVibratorInfos(const std::vector<media::AudioVibratorInfo>& vibratorInfos) final 217 EXCLUDES_AudioFlinger_Mutex; 218 219 status_t updateSecondaryOutputs( 220 const TrackSecondaryOutputsMap& trackSecondaryOutputs) final 221 EXCLUDES_AudioFlinger_Mutex; 222 223 status_t getMmapPolicyInfos( 224 media::audio::common::AudioMMapPolicyType policyType, 225 std::vector<media::audio::common::AudioMMapPolicyInfo>* policyInfos) final 226 EXCLUDES_AudioFlinger_Mutex; 227 228 int32_t getAAudioMixerBurstCount() const final EXCLUDES_AudioFlinger_Mutex; 229 230 int32_t getAAudioHardwareBurstMinUsec() const final EXCLUDES_AudioFlinger_Mutex; 231 232 status_t setDeviceConnectedState(const struct audio_port_v7* port, 233 media::DeviceConnectedState state) final EXCLUDES_AudioFlinger_Mutex; 234 235 status_t setSimulateDeviceConnections(bool enabled) final EXCLUDES_AudioFlinger_Mutex; 236 237 status_t setRequestedLatencyMode( 238 audio_io_handle_t output, audio_latency_mode_t mode) final 239 EXCLUDES_AudioFlinger_Mutex; 240 241 status_t getSupportedLatencyModes(audio_io_handle_t output, 242 std::vector<audio_latency_mode_t>* modes) const final EXCLUDES_AudioFlinger_Mutex; 243 244 status_t setBluetoothVariableLatencyEnabled(bool enabled) final EXCLUDES_AudioFlinger_Mutex; 245 246 status_t isBluetoothVariableLatencyEnabled(bool* enabled) const final 247 EXCLUDES_AudioFlinger_Mutex; 248 249 status_t supportsBluetoothVariableLatency(bool* support) const final 250 EXCLUDES_AudioFlinger_Mutex; 251 252 status_t getSoundDoseInterface(const sp<media::ISoundDoseCallback>& callback, 253 sp<media::ISoundDose>* soundDose) const final EXCLUDES_AudioFlinger_Mutex; 254 255 status_t invalidateTracks(const std::vector<audio_port_handle_t>& portIds) final 256 EXCLUDES_AudioFlinger_Mutex; 257 258 status_t getAudioPolicyConfig(media::AudioPolicyConfig* config) final 259 EXCLUDES_AudioFlinger_Mutex; 260 261 // Get the attributes of the mix port when connecting to the given device port. 262 status_t getAudioMixPort(const struct audio_port_v7* devicePort, 263 struct audio_port_v7* mixPort) const final EXCLUDES_AudioFlinger_Mutex; 264 265 status_t setTracksInternalMute( 266 const std::vector<media::TrackInternalMuteInfo>& tracksInternalMute) final 267 EXCLUDES_AudioFlinger_Mutex; 268 269 status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, 270 const std::function<status_t()>& delegate) final EXCLUDES_AudioFlinger_Mutex; 271 272 // ---- end of IAudioFlinger interface 273 274 // ---- begin IAfClientCallback interface 275 clientMutex()276 audio_utils::mutex& clientMutex() const final 277 RETURN_CAPABILITY(audio_utils::AudioFlinger_ClientMutex) { 278 return mClientMutex; 279 } 280 void removeClient_l(pid_t pid) REQUIRES(clientMutex()) final; 281 void removeNotificationClient(pid_t pid) final EXCLUDES_AudioFlinger_Mutex; 282 status_t moveAuxEffectToIo( 283 int effectId, 284 const sp<IAfPlaybackThread>& dstThread, 285 sp<IAfPlaybackThread>* srcThread) final EXCLUDES_AudioFlinger_Mutex; 286 287 // ---- end of IAfClientCallback interface 288 289 // ---- begin IAfDeviceEffectManagerCallback interface 290 291 // also used by IAfThreadCallback isAudioPolicyReady()292 bool isAudioPolicyReady() const final { return mAudioPolicyReady.load(); } 293 // below also used by IAfMelReporterCallback, IAfPatchPanelCallback getPatchCommandThread()294 const sp<PatchCommandThread>& getPatchCommandThread() final { return mPatchCommandThread; } 295 status_t addEffectToHal( 296 const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final 297 EXCLUDES_AudioFlinger_HardwareMutex; 298 status_t removeEffectFromHal( 299 const struct audio_port_config* device, const sp<EffectHalInterface>& effect) final 300 EXCLUDES_AudioFlinger_HardwareMutex; 301 302 // ---- end of IAfDeviceEffectManagerCallback interface 303 304 // ---- begin IAfMelReporterCallback interface 305 306 // below also used by IAfThreadCallback mutex()307 audio_utils::mutex& mutex() const final 308 RETURN_CAPABILITY(audio_utils::AudioFlinger_Mutex) 309 EXCLUDES_BELOW_AudioFlinger_Mutex { return mMutex; } 310 sp<IAfThreadBase> checkOutputThread_l(audio_io_handle_t ioHandle) const final 311 REQUIRES(mutex()); 312 313 // ---- end of IAfMelReporterCallback interface 314 315 // ---- begin IAfPatchPanelCallback interface 316 317 void closeThreadInternal_l(const sp<IAfPlaybackThread>& thread) final REQUIRES(mutex()); 318 void closeThreadInternal_l(const sp<IAfRecordThread>& thread) final REQUIRES(mutex()); 319 // return thread associated with primary hardware device, or NULL 320 IAfPlaybackThread* primaryPlaybackThread_l() const final REQUIRES(mutex()); 321 IAfPlaybackThread* checkPlaybackThread_l(audio_io_handle_t output) const final 322 REQUIRES(mutex()); 323 IAfRecordThread* checkRecordThread_l(audio_io_handle_t input) const final REQUIRES(mutex()); 324 IAfMmapThread* checkMmapThread_l(audio_io_handle_t io) const final REQUIRES(mutex()); 325 sp<IAfThreadBase> openInput_l(audio_module_handle_t module, 326 audio_io_handle_t* input, 327 audio_config_t* config, 328 audio_devices_t device, 329 const char* address, 330 audio_source_t source, 331 audio_input_flags_t flags, 332 audio_devices_t outputDevice, 333 const String8& outputDeviceAddress) final REQUIRES(mutex()); 334 sp<IAfThreadBase> openOutput_l(audio_module_handle_t module, 335 audio_io_handle_t* output, 336 audio_config_t* halConfig, 337 audio_config_base_t* mixerConfig, 338 audio_devices_t deviceType, 339 const String8& address, 340 audio_output_flags_t flags) final REQUIRES(mutex()); 341 const DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*>& getAudioHwDevs_l()342 getAudioHwDevs_l() const final REQUIRES(mutex()) { return mAudioHwDevs; } 343 void updateDownStreamPatches_l(const struct audio_patch* patch, 344 const std::set<audio_io_handle_t>& streams) final REQUIRES(mutex()); 345 void updateOutDevicesForRecordThreads_l(const DeviceDescriptorBaseVector& devices) final 346 REQUIRES(mutex()); 347 348 // ---- end of IAfPatchPanelCallback interface 349 350 // ----- begin IAfThreadCallback interface 351 352 bool isNonOffloadableGlobalEffectEnabled_l() const final 353 REQUIRES(mutex()) EXCLUDES_ThreadBase_Mutex; btNrecIsOff()354 bool btNrecIsOff() const final { return mBtNrecIsOff.load(); } 355 float masterVolume_l() const final REQUIRES(mutex()); 356 bool masterMute_l() const final REQUIRES(mutex()); 357 float getMasterBalance_l() const REQUIRES(mutex()); 358 // no range check, AudioFlinger::mutex() held streamMute_l(audio_stream_type_t stream)359 bool streamMute_l(audio_stream_type_t stream) const final REQUIRES(mutex()) { 360 return mStreamTypes[stream].mute; 361 } getMode()362 audio_mode_t getMode() const final { return mMode; } isLowRamDevice()363 bool isLowRamDevice() const final { return mIsLowRamDevice; } getScreenState()364 uint32_t getScreenState() const final { return mScreenState; } 365 366 std::optional<media::AudioVibratorInfo> getDefaultVibratorInfo_l() const final 367 REQUIRES(mutex()); getPatchPanel()368 const sp<IAfPatchPanel>& getPatchPanel() const final { return mPatchPanel; } getMelReporter()369 const sp<MelReporter>& getMelReporter() const final { return mMelReporter; } getEffectsFactoryHal()370 const sp<EffectsFactoryHalInterface>& getEffectsFactoryHal() const final { 371 return mEffectsFactoryHal; 372 } 373 sp<IAudioManager> getOrCreateAudioManager() final; 374 375 // Called when the last effect handle on an effect instance is removed. If this 376 // effect belongs to an effect chain in mOrphanEffectChains, the chain is updated 377 // and removed from mOrphanEffectChains if it does not contain any effect. 378 // Return true if the effect was found in mOrphanEffectChains, false otherwise. 379 bool updateOrphanEffectChains(const sp<IAfEffectModule>& effect) final 380 EXCLUDES_AudioFlinger_Mutex; 381 382 status_t moveEffectChain_ll(audio_session_t sessionId, 383 IAfPlaybackThread* srcThread, IAfPlaybackThread* dstThread, 384 IAfEffectChain* srcChain = nullptr) final 385 REQUIRES(mutex(), audio_utils::ThreadBase_Mutex); 386 387 // This is a helper that is called during incoming binder calls. 388 // Requests media.log to start merging log buffers 389 void requestLogMerge() final; 390 sp<NBLog::Writer> newWriter_l(size_t size, const char *name) final REQUIRES(mutex()); 391 void unregisterWriter(const sp<NBLog::Writer>& writer) final; 392 393 sp<audioflinger::SyncEvent> createSyncEvent(AudioSystem::sync_event_t type, 394 audio_session_t triggerSession, 395 audio_session_t listenerSession, 396 const audioflinger::SyncEventCallback& callBack, 397 const wp<IAfTrackBase>& cookie) final EXCLUDES_AudioFlinger_Mutex; 398 399 // Hold either AudioFlinger::mutex or ThreadBase::mutex 400 void ioConfigChanged_l(audio_io_config_event_t event, 401 const sp<AudioIoDescriptor>& ioDesc, 402 pid_t pid = 0) final EXCLUDES_AudioFlinger_ClientMutex; 403 void onNonOffloadableGlobalEffectEnable() final EXCLUDES_AudioFlinger_Mutex; 404 void onSupportedLatencyModesChanged( 405 audio_io_handle_t output, const std::vector<audio_latency_mode_t>& modes) final 406 EXCLUDES_AudioFlinger_ClientMutex; 407 void onHardError(std::set<audio_port_handle_t>& trackPortIds) final 408 EXCLUDES_AudioFlinger_ClientMutex; 409 410 // ---- end of IAfThreadCallback interface 411 412 /* List available audio ports and their attributes */ 413 status_t listAudioPorts(unsigned int* num_ports, struct audio_port* ports) const 414 EXCLUDES_AudioFlinger_Mutex; 415 416 sp<EffectsFactoryHalInterface> getEffectsFactory(); 417 418 public: 419 // TODO(b/292281786): Remove this when Oboeservice can get access to 420 // openMmapStream through an IAudioFlinger handle directly. 421 static inline std::atomic<AudioFlinger*> gAudioFlinger = nullptr; 422 423 status_t openMmapStream(MmapStreamInterface::stream_direction_t direction, 424 const audio_attributes_t *attr, 425 audio_config_base_t *config, 426 const AudioClient& client, 427 audio_port_handle_t *deviceId, 428 audio_session_t *sessionId, 429 const sp<MmapStreamCallback>& callback, 430 sp<MmapStreamInterface>& interface, 431 audio_port_handle_t *handle) EXCLUDES_AudioFlinger_Mutex; 432 initAudioPolicyLocal(sp<media::IAudioPolicyServiceLocal> audioPolicyLocal)433 void initAudioPolicyLocal(sp<media::IAudioPolicyServiceLocal> audioPolicyLocal) { 434 if (mAudioPolicyServiceLocal.load() == nullptr) { 435 mAudioPolicyServiceLocal = std::move(audioPolicyLocal); 436 } 437 } 438 439 private: 440 // FIXME The 400 is temporarily too high until a leak of writers in media.log is fixed. 441 static const size_t kLogMemorySize = 400 * 1024; 442 sp<MemoryDealer> mLogMemoryDealer; // == 0 when NBLog is disabled 443 // When a log writer is unregistered, it is done lazily so that media.log can continue to see it 444 // for as long as possible. The memory is only freed when it is needed for another log writer. 445 Vector< sp<NBLog::Writer> > mUnregisteredWriters; unregisteredWritersMutex()446 audio_utils::mutex& unregisteredWritersMutex() const { return mUnregisteredWritersMutex; } 447 mutable audio_utils::mutex mUnregisteredWritersMutex{ 448 audio_utils::MutexOrder::kAudioFlinger_UnregisteredWritersMutex}; 449 450 AudioFlinger() ANDROID_API; 451 ~AudioFlinger() override; 452 453 // call in any IAudioFlinger method that accesses mPrimaryHardwareDev initCheck()454 status_t initCheck() const { return mPrimaryHardwareDev == NULL ? 455 NO_INIT : NO_ERROR; } 456 457 // RefBase 458 void onFirstRef() override; 459 460 AudioHwDevice* findSuitableHwDev_l(audio_module_handle_t module, 461 audio_devices_t deviceType) REQUIRES(mutex()); 462 463 // incremented by 2 when screen state changes, bit 0 == 1 means "off" 464 // AudioFlinger::setParameters() updates with mutex(). 465 std::atomic_uint32_t mScreenState{}; 466 467 void dumpPermissionDenial(int fd, const Vector<String16>& args); 468 void dumpClients_ll(int fd, const Vector<String16>& args) REQUIRES(mutex(), clientMutex()); 469 void dumpInternals_l(int fd, const Vector<String16>& args) REQUIRES(mutex()); 470 471 SimpleLog mThreadLog{16}; // 16 Thread history limit 472 473 void dumpToThreadLog_l(const sp<IAfThreadBase>& thread) REQUIRES(mutex()); 474 475 // --- Notification Client --- 476 class NotificationClient : public IBinder::DeathRecipient { 477 public: 478 NotificationClient(const sp<AudioFlinger>& audioFlinger, 479 const sp<media::IAudioFlingerClient>& client, 480 pid_t pid, 481 uid_t uid); 482 virtual ~NotificationClient(); 483 audioFlingerClient()484 sp<media::IAudioFlingerClient> audioFlingerClient() const { return mAudioFlingerClient; } getPid()485 pid_t getPid() const { return mPid; } getUid()486 uid_t getUid() const { return mUid; } 487 488 // IBinder::DeathRecipient 489 virtual void binderDied(const wp<IBinder>& who); 490 491 private: 492 DISALLOW_COPY_AND_ASSIGN(NotificationClient); 493 494 const sp<AudioFlinger> mAudioFlinger; 495 const pid_t mPid; 496 const uid_t mUid; 497 const sp<media::IAudioFlingerClient> mAudioFlingerClient; 498 }; 499 500 // --- MediaLogNotifier --- 501 // Thread in charge of notifying MediaLogService to start merging. 502 // Receives requests from AudioFlinger's binder activity. It is used to reduce the amount of 503 // binder calls to MediaLogService in case of bursts of AudioFlinger binder calls. 504 class MediaLogNotifier : public Thread { 505 public: 506 MediaLogNotifier(); 507 508 // Requests a MediaLogService notification. It's ignored if there has recently been another 509 void requestMerge(); 510 private: 511 // Every iteration blocks waiting for a request, then interacts with MediaLogService to 512 // start merging. 513 // As every MediaLogService binder call is expensive, once it gets a request it ignores the 514 // following ones for a period of time. 515 virtual bool threadLoop() override; 516 517 bool mPendingRequests; 518 519 // Mutex and condition variable around mPendingRequests' value 520 audio_utils::mutex mMutex{audio_utils::MutexOrder::kMediaLogNotifier_Mutex}; 521 audio_utils::condition_variable mCondition; 522 523 // Duration of the sleep period after a processed request 524 static const int kPostTriggerSleepPeriod = 1000000; 525 }; 526 527 const sp<MediaLogNotifier> mMediaLogNotifier = sp<MediaLogNotifier>::make(); 528 529 // Find io handle by session id. 530 // Preference is given to an io handle with a matching effect chain to session id. 531 // If none found, AUDIO_IO_HANDLE_NONE is returned. 532 template <typename T> findIoHandleBySessionId_l(audio_session_t sessionId,const T & threads)533 static audio_io_handle_t findIoHandleBySessionId_l( 534 audio_session_t sessionId, const T& threads) 535 REQUIRES(audio_utils::AudioFlinger_Mutex) { 536 audio_io_handle_t io = AUDIO_IO_HANDLE_NONE; 537 538 for (size_t i = 0; i < threads.size(); i++) { 539 const uint32_t sessionType = threads.valueAt(i)->hasAudioSession(sessionId); 540 if (sessionType != 0) { 541 io = threads.keyAt(i); 542 if ((sessionType & IAfThreadBase::EFFECT_SESSION) != 0) { 543 break; // effect chain here. 544 } 545 } 546 } 547 return io; 548 } 549 550 IAfThreadBase* checkThread_l(audio_io_handle_t ioHandle) const REQUIRES(mutex()); 551 IAfPlaybackThread* checkMixerThread_l(audio_io_handle_t output) const REQUIRES(mutex()); 552 553 sp<VolumeInterface> getVolumeInterface_l(audio_io_handle_t output) const REQUIRES(mutex()); 554 std::vector<sp<VolumeInterface>> getAllVolumeInterfaces_l() const REQUIRES(mutex()); 555 556 557 static void closeOutputFinish(const sp<IAfPlaybackThread>& thread); 558 void closeInputFinish(const sp<IAfRecordThread>& thread); 559 560 // Allocate an audio_unique_id_t. 561 // Specific types are audio_io_handle_t, audio_session_t, effect ID (int), 562 // audio_module_handle_t, and audio_patch_handle_t. 563 // They all share the same ID space, but the namespaces are actually independent 564 // because there are separate KeyedVectors for each kind of ID. 565 // The return value is cast to the specific type depending on how the ID will be used. 566 // FIXME This API does not handle rollover to zero (for unsigned IDs), 567 // or from positive to negative (for signed IDs). 568 // Thus it may fail by returning an ID of the wrong sign, 569 // or by returning a non-unique ID. 570 // This is the internal API. For the binder API see newAudioUniqueId(). 571 // used by IAfDeviceEffectManagerCallback, IAfPatchPanelCallback, IAfThreadCallback 572 audio_unique_id_t nextUniqueId(audio_unique_id_use_t use) final; 573 574 status_t moveEffectChain_ll(audio_session_t sessionId, 575 IAfRecordThread* srcThread, IAfRecordThread* dstThread) 576 REQUIRES(mutex(), audio_utils::ThreadBase_Mutex); 577 578 // return thread associated with primary hardware device, or NULL 579 DeviceTypeSet primaryOutputDevice_l() const REQUIRES(mutex()); 580 581 // return the playback thread with smallest HAL buffer size, and prefer fast 582 IAfPlaybackThread* fastPlaybackThread_l() const REQUIRES(mutex()); 583 584 sp<IAfThreadBase> getEffectThread_l(audio_session_t sessionId, int effectId) 585 REQUIRES(mutex()); 586 587 IAfThreadBase* hapticPlaybackThread_l() const REQUIRES(mutex()); 588 589 void updateSecondaryOutputsForTrack_l( 590 IAfTrack* track, 591 IAfPlaybackThread* thread, 592 const std::vector<audio_io_handle_t>& secondaryOutputs) const REQUIRES(mutex()); 593 594 bool isSessionAcquired_l(audio_session_t audioSession) REQUIRES(mutex()); 595 596 // Store an effect chain to mOrphanEffectChains keyed vector. 597 // Called when a thread exits and effects are still attached to it. 598 // If effects are later created on the same session, they will reuse the same 599 // effect chain and same instances in the effect library. 600 // return ALREADY_EXISTS if a chain with the same session already exists in 601 // mOrphanEffectChains. Note that this should never happen as there is only one 602 // chain for a given session and it is attached to only one thread at a time. 603 status_t putOrphanEffectChain_l(const sp<IAfEffectChain>& chain) REQUIRES(mutex()); 604 // Get an effect chain for the specified session in mOrphanEffectChains and remove 605 // it if found. Returns 0 if not found (this is the most common case). 606 sp<IAfEffectChain> getOrphanEffectChain_l(audio_session_t session) REQUIRES(mutex()); 607 608 std::vector< sp<IAfEffectModule> > purgeStaleEffects_l() REQUIRES(mutex()); 609 610 std::vector< sp<IAfEffectModule> > purgeOrphanEffectChains_l() REQUIRES(mutex()); 611 bool updateOrphanEffectChains_l(const sp<IAfEffectModule>& effect) REQUIRES(mutex()); 612 613 void broadcastParametersToRecordThreads_l(const String8& keyValuePairs) REQUIRES(mutex()); 614 void forwardParametersToDownstreamPatches_l( 615 audio_io_handle_t upStream, const String8& keyValuePairs, 616 const std::function<bool(const sp<IAfPlaybackThread>&)>& useThread = nullptr) 617 REQUIRES(mutex()); 618 619 // for mAudioSessionRefs only 620 struct AudioSessionRef { AudioSessionRefAudioSessionRef621 AudioSessionRef(audio_session_t sessionid, pid_t pid, uid_t uid) : 622 mSessionid(sessionid), mPid(pid), mUid(uid), mCnt(1) {} 623 const audio_session_t mSessionid; 624 const pid_t mPid; 625 const uid_t mUid; 626 int mCnt; 627 }; 628 629 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kAudioFlinger_Mutex}; 630 // protects mClients and mNotificationClients. 631 // must be locked after mutex() and ThreadBase::mutex() if both must be locked 632 // avoids acquiring AudioFlinger::mutex() from inside thread loop. 633 634 mutable audio_utils::mutex mClientMutex{audio_utils::MutexOrder::kAudioFlinger_ClientMutex}; 635 636 DefaultKeyedVector<pid_t, wp<Client>> mClients GUARDED_BY(clientMutex()); // see ~Client() 637 hardwareMutex()638 audio_utils::mutex& hardwareMutex() const { return mHardwareMutex; } 639 640 mutable audio_utils::mutex mHardwareMutex{ 641 audio_utils::MutexOrder::kAudioFlinger_HardwareMutex}; 642 // NOTE: If both mMutex and mHardwareMutex mutexes must be held, 643 // always take mMutex before mHardwareMutex 644 645 std::atomic<AudioHwDevice*> mPrimaryHardwareDev = nullptr; 646 DefaultKeyedVector<audio_module_handle_t, AudioHwDevice*> mAudioHwDevs GUARDED_BY(hardwareMutex ())647 GUARDED_BY(hardwareMutex()) {nullptr /* defValue */}; 648 649 static bool inputBufferSizeDevsCmp(const AudioHwDevice* lhs, const AudioHwDevice* rhs); 650 std::set<AudioHwDevice*, decltype(&inputBufferSizeDevsCmp)> GUARDED_BY(hardwareMutex ())651 mInputBufferSizeOrderedDevs GUARDED_BY(hardwareMutex()) {inputBufferSizeDevsCmp}; 652 653 const sp<DevicesFactoryHalInterface> mDevicesFactoryHal = 654 DevicesFactoryHalInterface::create(); 655 /* const */ sp<DevicesFactoryHalCallback> mDevicesFactoryHalCallback; // set onFirstRef(). 656 657 // for dump, indicates which hardware operation is currently in progress (but not stream ops) 658 enum hardware_call_state { 659 AUDIO_HW_IDLE = 0, // no operation in progress 660 AUDIO_HW_INIT, // init_check 661 AUDIO_HW_OUTPUT_OPEN, // open_output_stream 662 AUDIO_HW_OUTPUT_CLOSE, // unused 663 AUDIO_HW_INPUT_OPEN, // unused 664 AUDIO_HW_INPUT_CLOSE, // unused 665 AUDIO_HW_STANDBY, // unused 666 AUDIO_HW_SET_MASTER_VOLUME, // set_master_volume 667 AUDIO_HW_GET_ROUTING, // unused 668 AUDIO_HW_SET_ROUTING, // unused 669 AUDIO_HW_GET_MODE, // unused 670 AUDIO_HW_SET_MODE, // set_mode 671 AUDIO_HW_GET_MIC_MUTE, // get_mic_mute 672 AUDIO_HW_SET_MIC_MUTE, // set_mic_mute 673 AUDIO_HW_SET_VOICE_VOLUME, // set_voice_volume 674 AUDIO_HW_SET_PARAMETER, // set_parameters 675 AUDIO_HW_GET_INPUT_BUFFER_SIZE, // get_input_buffer_size 676 AUDIO_HW_GET_MASTER_VOLUME, // get_master_volume 677 AUDIO_HW_GET_PARAMETER, // get_parameters 678 AUDIO_HW_SET_MASTER_MUTE, // set_master_mute 679 AUDIO_HW_GET_MASTER_MUTE, // get_master_mute 680 AUDIO_HW_GET_MICROPHONES, // getMicrophones 681 AUDIO_HW_SET_CONNECTED_STATE, // setConnectedState 682 AUDIO_HW_SET_SIMULATE_CONNECTIONS, // setSimulateDeviceConnections 683 }; 684 685 mutable hardware_call_state mHardwareStatus = AUDIO_HW_IDLE; // for dump only 686 DefaultKeyedVector<audio_io_handle_t, sp<IAfPlaybackThread>> mPlaybackThreads 687 GUARDED_BY(mutex()); 688 stream_type_t mStreamTypes[AUDIO_STREAM_CNT] GUARDED_BY(mutex()); 689 690 float mMasterVolume GUARDED_BY(mutex()) = 1.f; 691 bool mMasterMute GUARDED_BY(mutex()) = false; 692 float mMasterBalance GUARDED_BY(mutex()) = 0.f; 693 694 DefaultKeyedVector<audio_io_handle_t, sp<IAfRecordThread>> mRecordThreads GUARDED_BY(mutex()); 695 696 DefaultKeyedVector<pid_t, sp<NotificationClient>> mNotificationClients 697 GUARDED_BY(clientMutex()); 698 699 // updated by atomic_fetch_add_explicit 700 volatile atomic_uint_fast32_t mNextUniqueIds[AUDIO_UNIQUE_ID_USE_MAX]; // ctor init 701 702 std::atomic<audio_mode_t> mMode = AUDIO_MODE_INVALID; 703 std::atomic<bool> mBtNrecIsOff = false; 704 705 Vector<AudioSessionRef*> mAudioSessionRefs GUARDED_BY(mutex()); 706 707 AudioHwDevice* loadHwModule_ll(const char *name) REQUIRES(mutex(), hardwareMutex()); 708 709 // sync events awaiting for a session to be created. 710 std::list<sp<audioflinger::SyncEvent>> mPendingSyncEvents GUARDED_BY(mutex()); 711 712 // Effect chains without a valid thread 713 DefaultKeyedVector<audio_session_t, sp<IAfEffectChain>> mOrphanEffectChains 714 GUARDED_BY(mutex()); 715 716 // list of sessions for which a valid HW A/V sync ID was retrieved from the HAL 717 DefaultKeyedVector<audio_session_t, audio_hw_sync_t> mHwAvSyncIds GUARDED_BY(mutex()); 718 719 // list of MMAP stream control threads. Those threads allow for wake lock, routing 720 // and volume control for activity on the associated MMAP stream at the HAL. 721 // Audio data transfer is directly handled by the client creating the MMAP stream 722 DefaultKeyedVector<audio_io_handle_t, sp<IAfMmapThread>> mMmapThreads GUARDED_BY(mutex()); 723 724 sp<Client> registerPid(pid_t pid) EXCLUDES_AudioFlinger_ClientMutex; // always returns non-0 725 726 sp<IAfEffectHandle> createOrphanEffect_l(const sp<Client>& client, 727 const sp<media::IEffectClient>& effectClient, 728 int32_t priority, 729 audio_session_t sessionId, 730 effect_descriptor_t *desc, 731 int *enabled, 732 status_t *status /*non-NULL*/, 733 bool pinned, 734 bool notifyFramesProcessed) REQUIRES(mutex()); 735 736 // for use from destructor 737 status_t closeOutput_nonvirtual(audio_io_handle_t output) EXCLUDES_AudioFlinger_Mutex; 738 status_t closeInput_nonvirtual(audio_io_handle_t input) EXCLUDES_AudioFlinger_Mutex; 739 void setAudioHwSyncForSession_l(IAfPlaybackThread* thread, audio_session_t sessionId) 740 REQUIRES(mutex()); 741 742 static status_t checkStreamType(audio_stream_type_t stream); 743 744 // no mutex needed. 745 void filterReservedParameters(String8& keyValuePairs, uid_t callingUid); 746 void logFilteredParameters(size_t originalKVPSize, const String8& originalKVPs, 747 size_t rejectedKVPSize, const String8& rejectedKVPs, 748 uid_t callingUid); 749 750 // These methods read variables atomically without mLock, 751 // though the variables are updated with mLock. 752 size_t getClientSharedHeapSize() const; 753 754 std::atomic<bool> mIsLowRamDevice = true; 755 bool mIsDeviceTypeKnown GUARDED_BY(mutex()) = false; 756 int64_t mTotalMemory GUARDED_BY(mutex()) = 0; 757 std::atomic<size_t> mClientSharedHeapSize = kMinimumClientSharedHeapSizeBytes; 758 static constexpr size_t kMinimumClientSharedHeapSizeBytes = 1024 * 1024; // 1MB 759 760 // when a global effect was last enabled 761 nsecs_t mGlobalEffectEnableTime GUARDED_BY(mutex()) = 0; 762 763 /* const */ sp<IAfPatchPanel> mPatchPanel; 764 765 const sp<EffectsFactoryHalInterface> mEffectsFactoryHal = 766 audioflinger::EffectConfiguration::getEffectsFactoryHal(); 767 768 const sp<PatchCommandThread> mPatchCommandThread = sp<PatchCommandThread>::make(); 769 /* const */ sp<DeviceEffectManager> mDeviceEffectManager; // set onFirstRef 770 /* const */ sp<MelReporter> mMelReporter; // set onFirstRef 771 772 bool mSystemReady GUARDED_BY(mutex()) = false; 773 std::atomic<bool> mAudioPolicyReady = false; 774 775 mediautils::UidInfo mUidInfo GUARDED_BY(mutex()); 776 777 // no mutex needed. 778 SimpleLog mRejectedSetParameterLog; 779 SimpleLog mAppSetParameterLog; 780 SimpleLog mSystemSetParameterLog; 781 782 std::vector<media::AudioVibratorInfo> mAudioVibratorInfos GUARDED_BY(mutex()); 783 784 static inline constexpr const char *mMetricsId = AMEDIAMETRICS_KEY_AUDIO_FLINGER; 785 786 std::map<media::audio::common::AudioMMapPolicyType, 787 std::vector<media::audio::common::AudioMMapPolicyInfo>> mPolicyInfos 788 GUARDED_BY(mutex()); 789 int32_t mAAudioBurstsPerBuffer GUARDED_BY(mutex()) = 0; 790 int32_t mAAudioHwBurstMinMicros GUARDED_BY(mutex()) = 0; 791 792 /** Interface for interacting with the AudioService. */ 793 mediautils::atomic_sp<IAudioManager> mAudioManager; 794 795 // Bluetooth Variable latency control logic is enabled or disabled 796 std::atomic<bool> mBluetoothLatencyModesEnabled = true; 797 798 // Local interface to AudioPolicyService, late inited, but logically const 799 mediautils::atomic_sp<media::IAudioPolicyServiceLocal> mAudioPolicyServiceLocal; 800 }; 801 802 // ---------------------------------------------------------------------------- 803 804 } // namespace android 805