1 /* 2 ** 3 ** Copyright 2012, 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 #include "DeviceEffectManager.h" 21 #include "IAfEffect.h" 22 23 #include <android-base/macros.h> // DISALLOW_COPY_AND_ASSIGN 24 #include <mediautils/Synchronization.h> 25 #include <private/media/AudioEffectShared.h> 26 27 #include <map> // avoid transitive dependency 28 #include <optional> 29 #include <vector> 30 31 namespace android { 32 33 //--- Audio Effect Management 34 35 // EffectBase(EffectModule) and EffectChain classes both have their own mutex to protect 36 // state changes or resource modifications. Always respect the following order 37 // if multiple mutexes must be acquired to avoid cross deadlock: 38 // AudioFlinger -> ThreadBase -> EffectChain -> EffectBase(EffectModule) 39 // AudioHandle -> ThreadBase -> EffectChain -> EffectBase(EffectModule) 40 41 // NOTE: When implementing the EffectCallbackInterface, in an EffectChain or other, it is important 42 // to pay attention to this locking order as some callback methods can be called from a state where 43 // EffectModule and/or EffectChain mutexes are held. 44 45 // In addition, methods that lock the AudioPolicyService mutex (getOutputForEffect(), 46 // startOutput(), getInputForAttr(), releaseInput()...) should never be called with AudioFlinger or 47 // Threadbase mutex locked to avoid cross deadlock with other clients calling AudioPolicyService 48 // methods that in turn call AudioFlinger thus locking the same mutexes in the reverse order. 49 50 51 // The EffectBase class contains common properties, state and behavior for and EffectModule or 52 // other derived classes managing an audio effect instance within the effect framework. 53 // It also contains the class mutex (see comment on locking order above). 54 class EffectBase : public virtual IAfEffectBase { 55 public: 56 EffectBase(const sp<EffectCallbackInterface>& callback, 57 effect_descriptor_t *desc, 58 int id, 59 audio_session_t sessionId, 60 bool pinned); 61 id()62 int id() const final { return mId; } state()63 effect_state state() const final { 64 return mState; 65 } sessionId()66 audio_session_t sessionId() const final { 67 return mSessionId; 68 } desc()69 const effect_descriptor_t& desc() const final { return mDescriptor; } isOffloadable()70 bool isOffloadable() const final 71 { return (mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0; } isImplementationSoftware()72 bool isImplementationSoftware() const final 73 { return (mDescriptor.flags & EFFECT_FLAG_HW_ACC_MASK) == 0; } isProcessImplemented()74 bool isProcessImplemented() const final 75 { return (mDescriptor.flags & EFFECT_FLAG_NO_PROCESS) == 0; } isVolumeControl()76 bool isVolumeControl() const 77 { return (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) 78 == EFFECT_FLAG_VOLUME_CTRL; } isVolumeMonitor()79 bool isVolumeMonitor() const final 80 { return (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) 81 == EFFECT_FLAG_VOLUME_MONITOR; } 82 83 status_t setEnabled(bool enabled, bool fromHandle) override EXCLUDES_EffectBase_Mutex; 84 status_t setEnabled_l(bool enabled) final REQUIRES(audio_utils::EffectBase_Mutex); 85 bool isEnabled() const final; 86 void setSuspended(bool suspended) final EXCLUDES_EffectBase_Mutex; 87 bool suspended() const final EXCLUDES_EffectBase_Mutex; 88 command(int32_t __unused,const std::vector<uint8_t> & __unused,int32_t __unused,std::vector<uint8_t> * __unused)89 status_t command(int32_t __unused, 90 const std::vector<uint8_t>& __unused, 91 int32_t __unused, 92 std::vector<uint8_t>* __unused) override { 93 return NO_ERROR; 94 } 95 96 // mCallback is atomic so this can be lock-free. setCallback(const sp<EffectCallbackInterface> & callback)97 void setCallback(const sp<EffectCallbackInterface>& callback) final { 98 mCallback = callback; 99 } getCallback()100 sp<EffectCallbackInterface> getCallback() const final { 101 return mCallback.load(); 102 } 103 104 status_t addHandle(IAfEffectHandle* handle) final EXCLUDES_EffectBase_Mutex; 105 ssize_t disconnectHandle(IAfEffectHandle* handle, 106 bool unpinIfLast) final EXCLUDES_EffectBase_Mutex; 107 ssize_t removeHandle(IAfEffectHandle* handle) final EXCLUDES_EffectBase_Mutex; 108 ssize_t removeHandle_l(IAfEffectHandle* handle) final REQUIRES(audio_utils::EffectBase_Mutex); 109 IAfEffectHandle* controlHandle_l() final REQUIRES(audio_utils::EffectBase_Mutex); 110 bool purgeHandles() final EXCLUDES_EffectBase_Mutex; 111 112 void checkSuspendOnEffectEnabled(bool enabled, bool threadLocked) final; 113 isPinned()114 bool isPinned() const final { return mPinned; } unPin()115 void unPin() final { mPinned = false; } 116 mutex()117 audio_utils::mutex& mutex() const final 118 RETURN_CAPABILITY(android::audio_utils::EffectBase_Mutex) { 119 return mMutex; 120 } 121 122 status_t updatePolicyState() final EXCLUDES_EffectBase_Mutex; 123 asEffectModule()124 sp<IAfEffectModule> asEffectModule() override { return nullptr; } asDeviceEffectProxy()125 sp<IAfDeviceEffectProxy> asDeviceEffectProxy() override { return nullptr; } 126 127 void dump(int fd, const Vector<String16>& args) const override; 128 129 protected: isInternal_l()130 bool isInternal_l() const REQUIRES(audio_utils::EffectBase_Mutex) { 131 for (auto handle : mHandles) { 132 if (handle->client() != nullptr) { 133 return false; 134 } 135 } 136 return true; 137 } 138 139 bool mPinned = false; 140 141 DISALLOW_COPY_AND_ASSIGN(EffectBase); 142 143 // mutex for process, commands and handles list protection 144 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kEffectBase_Mutex}; 145 mediautils::atomic_sp<EffectCallbackInterface> mCallback; // parent effect chain 146 const int mId; // this instance unique ID 147 const audio_session_t mSessionId; // audio session ID 148 const effect_descriptor_t mDescriptor;// effect descriptor received from effect engine 149 effect_state mState = IDLE; // current activation state 150 // effect is suspended: temporarily disabled by framework 151 bool mSuspended = false; 152 153 Vector<IAfEffectHandle *> mHandles; // list of client handles 154 // First handle in mHandles has highest priority and controls the effect module 155 156 // Audio policy effect state management 157 // Mutex protecting transactions with audio policy manager as mutex() cannot 158 // be held to avoid cross deadlocks with audio policy mutex policyMutex()159 audio_utils::mutex& policyMutex() const 160 RETURN_CAPABILITY(android::audio_utils::EffectBase_PolicyMutex) { 161 return mPolicyMutex; 162 } 163 mutable audio_utils::mutex mPolicyMutex{audio_utils::MutexOrder::kEffectBase_PolicyMutex}; 164 // Effect is registered in APM or not 165 bool mPolicyRegistered = false; 166 // Effect enabled state communicated to APM. Enabled state corresponds to 167 // state requested by the EffectHandle with control 168 bool mPolicyEnabled = false; 169 }; 170 171 // The EffectModule class is a wrapper object controlling the effect engine implementation 172 // in the effect library. It prevents concurrent calls to process() and command() functions 173 // from different client threads. It keeps a list of EffectHandle objects corresponding 174 // to all client applications using this effect and notifies applications of effect state, 175 // control or parameter changes. It manages the activation state machine to send appropriate 176 // reset, enable, disable commands to effect engine and provide volume 177 // ramping when effects are activated/deactivated. 178 // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by 179 // the attached track(s) to accumulate their auxiliary channel. 180 class EffectModule : public IAfEffectModule, public EffectBase { 181 public: 182 EffectModule(const sp<EffectCallbackInterface>& callback, 183 effect_descriptor_t *desc, 184 int id, 185 audio_session_t sessionId, 186 bool pinned, 187 audio_port_handle_t deviceId) REQUIRES(audio_utils::EffectChain_Mutex); 188 ~EffectModule() override REQUIRES(audio_utils::EffectChain_Mutex); 189 190 void process() final EXCLUDES_EffectBase_Mutex; 191 bool updateState_l() final REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 192 status_t command(int32_t cmdCode, const std::vector<uint8_t>& cmdData, int32_t maxReplySize, 193 std::vector<uint8_t>* reply) final EXCLUDES_EffectBase_Mutex; 194 195 void reset_l() final REQUIRES(audio_utils::EffectBase_Mutex); 196 status_t configure_l() final REQUIRES(audio_utils::EffectChain_Mutex); 197 status_t init_l() final REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; status()198 uint32_t status() const final { 199 return mStatus; 200 } 201 bool isProcessEnabled() const final; 202 bool isOffloadedOrDirect_l() const final REQUIRES(audio_utils::EffectChain_Mutex); 203 bool isVolumeControlEnabled_l() const final REQUIRES(audio_utils::EffectChain_Mutex); 204 void setInBuffer(const sp<EffectBufferHalInterface>& buffer) final; inBuffer()205 int16_t *inBuffer() const final { 206 return mInBuffer != 0 ? reinterpret_cast<int16_t*>(mInBuffer->ptr()) : NULL; 207 } 208 void setOutBuffer(const sp<EffectBufferHalInterface>& buffer) final; outBuffer()209 int16_t *outBuffer() const final { 210 return mOutBuffer != 0 ? reinterpret_cast<int16_t*>(mOutBuffer->ptr()) : NULL; 211 } 212 // Updates the access mode if it is out of date. May issue a new effect configure. updateAccessMode_l()213 void updateAccessMode_l() final REQUIRES(audio_utils::EffectChain_Mutex) { 214 if (requiredEffectBufferAccessMode() != mConfig.outputCfg.accessMode) { 215 configure_l(); 216 } 217 } 218 status_t setDevices(const AudioDeviceTypeAddrVector& devices) final EXCLUDES_EffectBase_Mutex; 219 status_t setInputDevice(const AudioDeviceTypeAddr& device) final EXCLUDES_EffectBase_Mutex; 220 status_t setVolume_l(uint32_t* left, uint32_t* right, bool controller, bool force) final 221 REQUIRES(audio_utils::EffectChain_Mutex); 222 status_t setMode(audio_mode_t mode) final EXCLUDES_EffectBase_Mutex; 223 status_t setAudioSource(audio_source_t source) final EXCLUDES_EffectBase_Mutex; 224 status_t start_l() final REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 225 status_t stop_l() final REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 226 227 status_t setOffloaded_l(bool offloaded, audio_io_handle_t io) final 228 REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 229 bool isOffloaded_l() const final 230 REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 231 void addEffectToHal_l() override REQUIRES(audio_utils::EffectChain_Mutex); 232 void release_l(const std::string& from = "") final REQUIRES(audio_utils::EffectChain_Mutex); 233 asEffectModule()234 sp<IAfEffectModule> asEffectModule() final { return this; } 235 236 bool isHapticGenerator() const final; 237 bool isSpatializer() const final; 238 bool isEffect(const effect_uuid_t &uuid) const; 239 240 status_t setHapticScale_l(int id, os::HapticScale hapticScale) final 241 REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 242 status_t setVibratorInfo_l(const media::AudioVibratorInfo& vibratorInfo) final 243 REQUIRES(audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 244 status_t sendMetadata_ll(const std::vector<playback_track_metadata_v7_t>& metadata) final 245 REQUIRES(audio_utils::ThreadBase_Mutex, 246 audio_utils::EffectChain_Mutex) EXCLUDES_EffectBase_Mutex; 247 248 status_t getConfigs_l(audio_config_base_t* inputCfg, audio_config_base_t* outputCfg, 249 bool* isOutput) const final 250 REQUIRES(audio_utils::EffectHandle_Mutex) EXCLUDES_EffectBase_Mutex; 251 252 void dump(int fd, const Vector<String16>& args) const final; 253 254 protected: 255 sp<EffectHalInterface> mEffectInterface; // Effect module HAL 256 257 private: 258 259 // Maximum time allocated to effect engines to complete the turn off sequence 260 static const uint32_t MAX_DISABLE_TIME_MS = 10000; 261 262 DISALLOW_COPY_AND_ASSIGN(EffectModule); 263 264 status_t start_ll() REQUIRES(audio_utils::EffectChain_Mutex, audio_utils::EffectBase_Mutex); 265 status_t stop_ll() REQUIRES(audio_utils::EffectChain_Mutex, audio_utils::EffectBase_Mutex); 266 status_t removeEffectFromHal_l() override REQUIRES(audio_utils::EffectChain_Mutex); 267 status_t sendSetAudioDevicesCommand(const AudioDeviceTypeAddrVector &devices, uint32_t cmdCode); requiredEffectBufferAccessMode()268 effect_buffer_access_e requiredEffectBufferAccessMode() const { 269 return mConfig.inputCfg.buffer.raw == mConfig.outputCfg.buffer.raw 270 ? EFFECT_BUFFER_ACCESS_WRITE : EFFECT_BUFFER_ACCESS_ACCUMULATE; 271 } 272 273 status_t setVolumeInternal_ll(uint32_t* left, uint32_t* right, 274 bool controller /* the volume controller effect of the chain */) 275 REQUIRES(audio_utils::EffectChain_Mutex, audio_utils::EffectBase_Mutex); 276 277 effect_config_t mConfig; // input and output audio configuration 278 sp<EffectBufferHalInterface> mInBuffer; // Buffers for interacting with HAL 279 sp<EffectBufferHalInterface> mOutBuffer; 280 status_t mStatus; // initialization status 281 // First handle in mHandles has highest priority and controls the effect module 282 uint32_t mMaxDisableWaitCnt; // maximum grace period before forcing an effect off after 283 // sending disable command. 284 uint32_t mDisableWaitCnt; // current process() calls count during disable period. 285 bool mOffloaded; // effect is currently offloaded to the audio DSP 286 // effect has been added to this HAL input stream 287 audio_io_handle_t mCurrentHalStream = AUDIO_IO_HANDLE_NONE; 288 bool mIsOutput; // direction of the AF thread 289 290 bool mSupportsFloat; // effect supports float processing 291 sp<EffectBufferHalInterface> mInConversionBuffer; // Buffers for HAL conversion if needed. 292 sp<EffectBufferHalInterface> mOutConversionBuffer; 293 uint32_t mInChannelCountRequested; 294 uint32_t mOutChannelCountRequested; 295 296 template <typename MUTEX> 297 class AutoLockReentrant { 298 public: AutoLockReentrant(MUTEX & mutex,pid_t allowedTid)299 AutoLockReentrant(MUTEX& mutex, pid_t allowedTid) ACQUIRE(audio_utils::EffectBase_Mutex) 300 : mMutex(gettid() == allowedTid ? nullptr : &mutex) 301 { 302 if (mMutex != nullptr) mMutex->lock(); 303 } RELEASE(audio_utils::EffectBase_Mutex)304 ~AutoLockReentrant() RELEASE(audio_utils::EffectBase_Mutex) { 305 if (mMutex != nullptr) mMutex->unlock(); 306 } 307 private: 308 MUTEX * const mMutex; 309 }; 310 311 static constexpr pid_t INVALID_PID = (pid_t)-1; 312 // this tid is allowed to call setVolume() without acquiring the mutex. 313 pid_t mSetVolumeReentrantTid = INVALID_PID; 314 315 // Cache the volume that has been set successfully. 316 std::optional<std::vector<uint32_t>> mVolume; 317 // Cache the volume that returned from the effect when setting volume successfully. The value 318 // here is used to indicate the volume to apply before this effect. 319 std::optional<std::vector<uint32_t>> mReturnedVolume; 320 // TODO: b/315995877, remove this debugging string after root cause 321 std::string mEffectInterfaceDebug GUARDED_BY(audio_utils::EffectChain_Mutex); 322 }; 323 324 class HwAccDeviceEffectModule : public EffectModule { 325 public: HwAccDeviceEffectModule(const sp<EffectCallbackInterface> & callback,effect_descriptor_t * desc,int id,audio_port_handle_t deviceId)326 HwAccDeviceEffectModule(const sp<EffectCallbackInterface>& callback, effect_descriptor_t *desc, 327 int id, audio_port_handle_t deviceId) : 328 EffectModule(callback, desc, id, AUDIO_SESSION_DEVICE, /* pinned */ false, deviceId) {} 329 void addEffectToHal_l() final REQUIRES(audio_utils::EffectChain_Mutex); 330 331 private: 332 status_t removeEffectFromHal_l() final REQUIRES(audio_utils::EffectChain_Mutex); 333 bool mAddedToHal = false; 334 }; 335 336 // The EffectHandle class implements the IEffect interface. It provides resources 337 // to receive parameter updates, keeps track of effect control 338 // ownership and state and has a pointer to the EffectModule object it is controlling. 339 // There is one EffectHandle object for each application controlling (or using) 340 // an effect module. 341 // The EffectHandle is obtained by calling AudioFlinger::createEffect(). 342 class EffectHandle: public IAfEffectHandle, public android::media::BnEffect { 343 public: 344 345 EffectHandle(const sp<IAfEffectBase>& effect, 346 const sp<Client>& client, 347 const sp<media::IEffectClient>& effectClient, 348 int32_t priority, bool notifyFramesProcessed, bool isInternal = false, 349 audio_utils::MutexOrder mutexOrder = audio_utils::MutexOrder::kEffectHandle_Mutex); 350 ~EffectHandle() override; 351 status_t onTransact( 352 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) final; 353 status_t initCheck() const final; 354 355 // IEffect 356 android::binder::Status enable(int32_t* _aidl_return) final; 357 android::binder::Status disable(int32_t* _aidl_return) final; 358 android::binder::Status command(int32_t cmdCode, 359 const std::vector<uint8_t>& cmdData, 360 int32_t maxResponseSize, 361 std::vector<uint8_t>* response, 362 int32_t* _aidl_return) final; 363 android::binder::Status disconnect() final; 364 android::binder::Status getCblk(media::SharedFileRegion* _aidl_return) final; 365 android::binder::Status getConfig(media::EffectConfig* _config, 366 int32_t* _aidl_return) final; 367 client()368 const sp<Client>& client() const final { return mClient; } 369 /** 370 * Checks if the handle is internal, aka created by AudioFlinger for internal needs (e.g. 371 * device effect HAL handle or device effect thread handle). 372 */ isInternal()373 virtual bool isInternal() const { return mIsInternal; } 374 asIEffect()375 sp<android::media::IEffect> asIEffect() final { 376 return sp<android::media::IEffect>::fromExisting(this); 377 } 378 379 private: 380 void disconnect(bool unpinIfLast); 381 382 // Give or take control of effect module 383 // - hasControl: true if control is given, false if removed 384 // - signal: true client app should be signaled of change, false otherwise 385 // - enabled: state of the effect when control is passed 386 void setControl(bool hasControl, bool signal, bool enabled) final; 387 void commandExecuted(uint32_t cmdCode, 388 const std::vector<uint8_t>& cmdData, 389 const std::vector<uint8_t>& replyData) final; enabled()390 bool enabled() const final { return mEnabled; } 391 void setEnabled(bool enabled) final; 392 void framesProcessed(int32_t frames) const final; 393 394 public: 395 // Getters effect()396 wp<IAfEffectBase> effect() const final { return mEffect; } id()397 int id() const final { 398 sp<IAfEffectBase> effect = mEffect.promote(); 399 if (effect == 0) { 400 return 0; 401 } 402 return effect->id(); 403 } 404 private: priority()405 int priority() const final { return mPriority; } hasControl()406 bool hasControl() const final { return mHasControl; } disconnected()407 bool disconnected() const final { return mDisconnected; } 408 409 void dumpToBuffer(char* buffer, size_t size) const final; 410 411 protected: 412 // protects IEffect method calls 413 mutable audio_utils::mutex mMutex; 414 415 private: 416 DISALLOW_COPY_AND_ASSIGN(EffectHandle); 417 mutex()418 virtual audio_utils::mutex& mutex() const 419 RETURN_CAPABILITY(android::audio_utils::EffectHandle_Mutex) { 420 return mMutex; 421 } 422 423 const wp<IAfEffectBase> mEffect; // pointer to controlled EffectModule 424 const sp<media::IEffectClient> mEffectClient; // callback interface for client notifications 425 /*const*/ sp<Client> mClient; // client for shared memory allocation, see 426 // disconnect() 427 sp<IMemory> mCblkMemory; // shared memory for control block 428 effect_param_cblk_t* mCblk; // control block for deferred parameter setting via 429 // shared memory 430 uint8_t* mBuffer; // pointer to parameter area in shared memory 431 int mPriority; // client application priority to control the effect 432 bool mHasControl; // true if this handle is controlling the effect 433 bool mEnabled; // cached enable state: needed when the effect is 434 // restored after being suspended 435 bool mDisconnected; // Set to true by disconnect() 436 const bool mNotifyFramesProcessed; // true if the client callback event 437 // EVENT_FRAMES_PROCESSED must be generated 438 const bool mIsInternal; 439 }; 440 441 /** 442 * There are 2 types of effects: 443 * -Session Effect: handle is directly called from the client, without AudioFlinger lock. 444 * -Device Effect: a device effect proxy is aggregating a collection of internal effect handles that 445 * controls the same effect added on all audio patches involving the device effect selected port 446 * requested either by a client or by AudioPolicyEffects. These internal effect handles do not have 447 * client. Sequence flow implies a different locking order, hence the lock is specialied. 448 */ 449 class InternalEffectHandle : public EffectHandle { 450 public: InternalEffectHandle(const sp<IAfEffectBase> & effect,bool notifyFramesProcessed)451 InternalEffectHandle(const sp<IAfEffectBase>& effect, bool notifyFramesProcessed) : 452 EffectHandle(effect, /* client= */ nullptr, /* effectClient= */ nullptr, 453 /* priority= */ 0, notifyFramesProcessed, /* isInternal */ true, 454 audio_utils::MutexOrder::kDeviceEffectHandle_Mutex) {} 455 mutex()456 virtual audio_utils::mutex& mutex() const 457 RETURN_CAPABILITY(android::audio_utils::DeviceEffectHandle_Mutex) { 458 return mMutex; 459 } 460 }; 461 462 // the EffectChain class represents a group of effects associated to one audio session. 463 // There can be any number of EffectChain objects per output mixer thread (PlaybackThread). 464 // The EffectChain with session ID AUDIO_SESSION_OUTPUT_MIX contains global effects applied 465 // to the output mix. 466 // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to 467 // tracks) are insert only. The EffectChain maintains an ordered list of effect module, the 468 // order corresponding in the effect process order. When attached to a track (session ID != 469 // AUDIO_SESSION_OUTPUT_MIX), 470 // it also provide it's own input buffer used by the track as accumulation buffer. 471 class EffectChain : public IAfEffectChain { 472 public: 473 EffectChain(const sp<IAfThreadBase>& thread, 474 audio_session_t sessionId, 475 const sp<IAfThreadCallback>& afThreadCallback); 476 477 void process_l() final REQUIRES(audio_utils::EffectChain_Mutex); 478 mutex()479 audio_utils::mutex& mutex() const final RETURN_CAPABILITY(audio_utils::EffectChain_Mutex) { 480 return mMutex; 481 } 482 483 status_t createEffect(sp<IAfEffectModule>& effect, effect_descriptor_t* desc, int id, 484 audio_session_t sessionId, bool pinned) final 485 EXCLUDES_EffectChain_Mutex; 486 status_t addEffect(const sp<IAfEffectModule>& handle) final 487 EXCLUDES_EffectChain_Mutex; 488 status_t addEffect_l(const sp<IAfEffectModule>& handle) final 489 REQUIRES(audio_utils::EffectChain_Mutex); 490 size_t removeEffect(const sp<IAfEffectModule>& handle, bool release = false) final 491 EXCLUDES_EffectChain_Mutex; 492 sessionId()493 audio_session_t sessionId() const final { return mSessionId; } setSessionId(audio_session_t sessionId)494 void setSessionId(audio_session_t sessionId) final { mSessionId = sessionId; } 495 496 sp<IAfEffectModule> getEffectFromDesc(effect_descriptor_t* descriptor) const final 497 EXCLUDES_EffectChain_Mutex; 498 sp<IAfEffectModule> getEffectFromId_l(int id) const final 499 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 500 sp<IAfEffectModule> getEffectFromType_l(const effect_uuid_t* type) const final 501 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 502 std::vector<int> getEffectIds_l() const final REQUIRES(audio_utils::ThreadBase_Mutex); 503 // FIXME use float to improve the dynamic range 504 505 bool setVolume(uint32_t* left, uint32_t* right, 506 bool force = false) final EXCLUDES_EffectChain_Mutex; 507 void resetVolume_l() final REQUIRES(audio_utils::EffectChain_Mutex); 508 void setDevices_l(const AudioDeviceTypeAddrVector& devices) final 509 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 510 void setInputDevice_l(const AudioDeviceTypeAddr& device) final 511 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 512 void setMode_l(audio_mode_t mode) final 513 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 514 void setAudioSource_l(audio_source_t source) final 515 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 516 setInBuffer(const sp<EffectBufferHalInterface> & buffer)517 void setInBuffer(const sp<EffectBufferHalInterface>& buffer) final { 518 mInBuffer = buffer; 519 } inBuffer()520 float *inBuffer() const final { 521 return mInBuffer != 0 ? reinterpret_cast<float*>(mInBuffer->ptr()) : NULL; 522 } setOutBuffer(const sp<EffectBufferHalInterface> & buffer)523 void setOutBuffer(const sp<EffectBufferHalInterface>& buffer) final { 524 mOutBuffer = buffer; 525 } outBuffer()526 float *outBuffer() const final { 527 return mOutBuffer != 0 ? reinterpret_cast<float*>(mOutBuffer->ptr()) : NULL; 528 } incTrackCnt()529 void incTrackCnt() final { android_atomic_inc(&mTrackCnt); } decTrackCnt()530 void decTrackCnt() final { android_atomic_dec(&mTrackCnt); } trackCnt()531 int32_t trackCnt() const final { return android_atomic_acquire_load(&mTrackCnt); } 532 incActiveTrackCnt()533 void incActiveTrackCnt() final { android_atomic_inc(&mActiveTrackCnt); 534 mTailBufferCount = mMaxTailBuffers; } decActiveTrackCnt()535 void decActiveTrackCnt() final { android_atomic_dec(&mActiveTrackCnt); } activeTrackCnt()536 int32_t activeTrackCnt() const final { 537 return android_atomic_acquire_load(&mActiveTrackCnt); 538 } 539 strategy()540 product_strategy_t strategy() const final { return mStrategy; } setStrategy(product_strategy_t strategy)541 void setStrategy(product_strategy_t strategy) final 542 { mStrategy = strategy; } 543 544 // suspend or restore effects of the specified type. The number of suspend requests is counted 545 // and restore occurs once all suspend requests are cancelled. 546 void setEffectSuspended_l(const effect_uuid_t* type, bool suspend) final 547 REQUIRES(audio_utils::ThreadBase_Mutex); 548 // suspend all eligible effects 549 void setEffectSuspendedAll_l(bool suspend) final REQUIRES(audio_utils::ThreadBase_Mutex); 550 // check if effects should be suspended or restored when a given effect is enable or disabled 551 void checkSuspendOnEffectEnabled_l(const sp<IAfEffectModule>& effect, bool enabled) final 552 REQUIRES(audio_utils::ThreadBase_Mutex); 553 554 void clearInputBuffer() final EXCLUDES_EffectChain_Mutex; 555 556 // At least one non offloadable effect in the chain is enabled 557 bool isNonOffloadableEnabled() const final EXCLUDES_EffectChain_Mutex; 558 bool isNonOffloadableEnabled_l() const final REQUIRES(audio_utils::EffectChain_Mutex); 559 560 void syncHalEffectsState_l() 561 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex final; 562 563 // flags is an ORed set of audio_output_flags_t which is updated on return. 564 void checkOutputFlagCompatibility(audio_output_flags_t *flags) const final; 565 566 // flags is an ORed set of audio_input_flags_t which is updated on return. 567 void checkInputFlagCompatibility(audio_input_flags_t *flags) const final; 568 569 // Is this EffectChain compatible with the RAW audio flag. 570 bool isRawCompatible() const final; 571 572 // Is this EffectChain compatible with the FAST audio flag. 573 bool isFastCompatible() const final; 574 575 // Is this EffectChain compatible with the bit-perfect audio flag. 576 bool isBitPerfectCompatible() const final; 577 578 // isCompatibleWithThread_l() must be called with thread->mutex() held 579 bool isCompatibleWithThread_l(const sp<IAfThreadBase>& thread) const final 580 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 581 582 bool containsHapticGeneratingEffect() final 583 EXCLUDES_EffectChain_Mutex; 584 585 bool containsHapticGeneratingEffect_l() final 586 REQUIRES(audio_utils::EffectChain_Mutex); 587 588 void setHapticScale_l(int id, os::HapticScale hapticScale) final 589 REQUIRES(audio_utils::ThreadBase_Mutex) EXCLUDES_EffectChain_Mutex; 590 effectCallback()591 sp<EffectCallbackInterface> effectCallback() const final { return mEffectCallback; } 592 thread()593 wp<IAfThreadBase> thread() const final { return mEffectCallback->thread(); } 594 isFirstEffect_l(int id)595 bool isFirstEffect_l(int id) const final REQUIRES(audio_utils::EffectChain_Mutex) { 596 return !mEffects.isEmpty() && id == mEffects[0]->id(); 597 } 598 599 void dump(int fd, const Vector<String16>& args) const final; 600 numberOfEffects()601 size_t numberOfEffects() const final { 602 audio_utils::lock_guard _l(mutex()); 603 return mEffects.size(); 604 } 605 getEffectModule(size_t index)606 sp<IAfEffectModule> getEffectModule(size_t index) const final { 607 audio_utils::lock_guard _l(mutex()); 608 return mEffects[index]; 609 } 610 611 void sendMetadata_l(const std::vector<playback_track_metadata_v7_t>& allMetadata, 612 const std::optional<const std::vector<playback_track_metadata_v7_t>> spatializedMetadata) 613 final REQUIRES(audio_utils::ThreadBase_Mutex); 614 615 void setThread(const sp<IAfThreadBase>& thread) final EXCLUDES_EffectChain_Mutex; 616 617 private: 618 bool setVolume_l(uint32_t* left, uint32_t* right, bool force = false) 619 REQUIRES(audio_utils::EffectChain_Mutex); 620 621 // For transaction consistency, please consider holding the EffectChain lock before 622 // calling the EffectChain::EffectCallback methods, excepting 623 // createEffectHal and allocateHalBuffer. 624 // 625 // This prevents migration of the EffectChain to another PlaybackThread 626 // for the purposes of the EffectCallback. 627 class EffectCallback : public EffectCallbackInterface { 628 public: 629 // Note: ctors taking a weak pointer to their owner must not promote it 630 // during construction (but may keep a reference for later promotion). EffectCallback(const wp<EffectChain> & owner,const sp<IAfThreadBase> & thread,const sp<IAfThreadCallback> & afThreadCallback)631 EffectCallback(const wp<EffectChain>& owner, 632 const sp<IAfThreadBase>& thread, 633 const sp<IAfThreadCallback>& afThreadCallback) // we take a sp<> but store a wp<>. 634 : mChain(owner) 635 , mThread(thread), mAfThreadCallback(afThreadCallback) { 636 if (thread != nullptr) { 637 mThreadType = thread->type(); 638 } 639 } 640 641 status_t createEffectHal(const effect_uuid_t *pEffectUuid, 642 int32_t sessionId, int32_t deviceId, sp<EffectHalInterface> *effect) override; 643 status_t allocateHalBuffer(size_t size, sp<EffectBufferHalInterface>* buffer) override; 644 bool updateOrphanEffectChains(const sp<IAfEffectBase>& effect) override; 645 646 audio_io_handle_t io() const override; 647 bool isOutput() const override; 648 bool isOffload() const override; 649 bool isOffloadOrDirect() const override; 650 bool isOffloadOrMmap() const override; 651 bool isSpatializer() const override; 652 653 uint32_t sampleRate() const override; 654 audio_channel_mask_t inChannelMask(int id) const override; 655 uint32_t inChannelCount(int id) const override; 656 audio_channel_mask_t outChannelMask() const override; 657 uint32_t outChannelCount() const override; 658 audio_channel_mask_t hapticChannelMask() const override; 659 size_t frameCount() const override; 660 uint32_t latency() const override; 661 662 status_t addEffectToHal(const sp<EffectHalInterface>& effect) override; 663 status_t removeEffectFromHal(const sp<EffectHalInterface>& effect) override; 664 bool disconnectEffectHandle(IAfEffectHandle *handle, bool unpinIfLast) override; 665 void setVolumeForOutput(float left, float right) const override; 666 667 // check if effects should be suspended/restored when a given effect is enable/disabled 668 void checkSuspendOnEffectEnabled(const sp<IAfEffectBase>& effect, bool enabled, 669 bool threadLocked) override; 670 void resetVolume_l() override 671 REQUIRES(audio_utils::ThreadBase_Mutex, audio_utils::EffectChain_Mutex); 672 product_strategy_t strategy() const override; 673 int32_t activeTrackCnt() const override; 674 void onEffectEnable(const sp<IAfEffectBase>& effect) override; 675 void onEffectDisable(const sp<IAfEffectBase>& effect) override; 676 chain()677 wp<IAfEffectChain> chain() const final { return mChain; } 678 isAudioPolicyReady()679 bool isAudioPolicyReady() const final { 680 if (mAfThreadCallback == nullptr) { 681 return false; 682 } 683 return mAfThreadCallback->isAudioPolicyReady(); 684 } 685 thread()686 wp<IAfThreadBase> thread() const { return mThread.load(); } 687 setThread(const sp<IAfThreadBase> & thread)688 void setThread(const sp<IAfThreadBase>& thread) { 689 mThread = thread; 690 if (thread != nullptr) { 691 mThreadType = thread->type(); 692 mAfThreadCallback = thread->afThreadCallback(); 693 } 694 } hasThreadAttached()695 bool hasThreadAttached() const { 696 return thread().promote() != nullptr; 697 } 698 private: 699 const wp<IAfEffectChain> mChain; 700 mediautils::atomic_wp<IAfThreadBase> mThread; 701 sp<IAfThreadCallback> mAfThreadCallback; 702 IAfThreadBase::type_t mThreadType = IAfThreadBase::MIXER; 703 }; 704 705 DISALLOW_COPY_AND_ASSIGN(EffectChain); 706 707 class SuspendedEffectDesc : public RefBase { 708 public: SuspendedEffectDesc()709 SuspendedEffectDesc() : mRefCount(0) {} 710 711 int mRefCount; // > 0 when suspended 712 effect_uuid_t mType; 713 wp<IAfEffectModule> mEffect; 714 }; 715 716 // get a list of effect modules to suspend when an effect of the type 717 // passed is enabled. 718 void getSuspendEligibleEffects(Vector<sp<IAfEffectModule>>& effects) 719 EXCLUDES_EffectChain_Mutex; 720 721 // get an effect module if it is currently enable 722 sp<IAfEffectModule> getEffectIfEnabled_l(const effect_uuid_t* type) 723 REQUIRES(audio_utils::ThreadBase_Mutex); 724 // true if the effect whose descriptor is passed can be suspended 725 // OEMs can modify the rules implemented in this method to exclude specific effect 726 // types or implementations from the suspend/restore mechanism. 727 bool isEffectEligibleForSuspend(const effect_descriptor_t& desc); 728 729 static bool isEffectEligibleForBtNrecSuspend_l(const effect_uuid_t* type) 730 REQUIRES(audio_utils::ThreadBase_Mutex); 731 732 void clearInputBuffer_l() REQUIRES(audio_utils::EffectChain_Mutex); 733 734 // true if any effect module within the chain has volume control 735 bool hasVolumeControlEnabled_l() const REQUIRES(audio_utils::EffectChain_Mutex); 736 737 void setVolumeForOutput_l(uint32_t left, uint32_t right) 738 REQUIRES(audio_utils::EffectChain_Mutex); 739 740 ssize_t getInsertIndex_l(const effect_descriptor_t& desc) 741 REQUIRES(audio_utils::EffectChain_Mutex); 742 743 std::optional<size_t> findVolumeControl_l(size_t from, size_t to) const 744 REQUIRES(audio_utils::EffectChain_Mutex); 745 746 // mutex protecting effect list 747 mutable audio_utils::mutex mMutex{audio_utils::MutexOrder::kEffectChain_Mutex}; 748 Vector<sp<IAfEffectModule>> mEffects GUARDED_BY(mutex()); // list of effect modules 749 audio_session_t mSessionId; // audio session ID 750 sp<EffectBufferHalInterface> mInBuffer; // chain input buffer 751 sp<EffectBufferHalInterface> mOutBuffer; // chain output buffer 752 753 // 'volatile' here means these are accessed with atomic operations instead of mutex 754 volatile int32_t mActiveTrackCnt; // number of active tracks connected 755 volatile int32_t mTrackCnt; // number of tracks connected 756 757 int32_t mTailBufferCount; // current effect tail buffer count 758 int32_t mMaxTailBuffers; // maximum effect tail buffers 759 uint32_t mLeftVolume; // previous volume on left channel 760 uint32_t mRightVolume; // previous volume on right channel 761 uint32_t mNewLeftVolume; // new volume on left channel 762 uint32_t mNewRightVolume; // new volume on right channel 763 product_strategy_t mStrategy = PRODUCT_STRATEGY_NONE; // strategy for this effect chain 764 // mSuspendedEffects lists all effects currently suspended in the chain. 765 // Use effect type UUID timelow field as key. There is no real risk of identical 766 // timeLow fields among effect type UUIDs. 767 // Updated by setEffectSuspended_l() and setEffectSuspendedAll_l() only. 768 KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects; 769 770 const sp<EffectCallback> mEffectCallback; 771 772 wp<IAfEffectModule> mVolumeControlEffect; 773 }; 774 775 class DeviceEffectProxy : public IAfDeviceEffectProxy, public EffectBase { 776 public: DeviceEffectProxy(const AudioDeviceTypeAddr & device,const sp<DeviceEffectManagerCallback> & callback,effect_descriptor_t * desc,int id,bool notifyFramesProcessed)777 DeviceEffectProxy(const AudioDeviceTypeAddr& device, 778 const sp<DeviceEffectManagerCallback>& callback, 779 effect_descriptor_t *desc, int id, bool notifyFramesProcessed) 780 : EffectBase(callback, desc, id, AUDIO_SESSION_DEVICE, false), 781 mDevice(device), mManagerCallback(callback), 782 mMyCallback(new ProxyCallback(wp<DeviceEffectProxy>(this), callback)), 783 mNotifyFramesProcessed(notifyFramesProcessed) {} 784 785 status_t setEnabled(bool enabled, bool fromHandle) final; asDeviceEffectProxy()786 sp<IAfDeviceEffectProxy> asDeviceEffectProxy() final { return this; } 787 788 status_t init_l(const std::map<audio_patch_handle_t, IAfPatchPanel::Patch>& patches) final 789 REQUIRES(audio_utils::DeviceEffectManager_Mutex) EXCLUDES_EffectBase_Mutex; 790 791 status_t onCreatePatch(audio_patch_handle_t patchHandle, 792 const IAfPatchPanel::Patch& patch) final; 793 794 status_t onUpdatePatch(audio_patch_handle_t oldPatchHandle, audio_patch_handle_t newPatchHandle, 795 const IAfPatchPanel::Patch& patch) final; 796 797 sp<IAfEffectHandle> onReleasePatch(audio_patch_handle_t patchHandle) final; 798 799 size_t removeEffect(const sp<IAfEffectModule>& effect) final; 800 801 status_t addEffectToHal(const sp<EffectHalInterface>& effect) final; 802 status_t removeEffectFromHal(const sp<EffectHalInterface>& effect) final; 803 device()804 const AudioDeviceTypeAddr& device() const final { return mDevice; }; 805 bool isOutput() const final; 806 uint32_t sampleRate() const final; 807 audio_channel_mask_t channelMask() const final; 808 uint32_t channelCount() const final; 809 810 status_t command(int32_t cmdCode, const std::vector<uint8_t>& cmdData, int32_t maxReplySize, 811 std::vector<uint8_t>* reply) final EXCLUDES_DeviceEffectProxy_ProxyMutex; 812 813 void dump2(int fd, int spaces) const final; 814 815 private: 816 817 class ProxyCallback : public EffectCallbackInterface { 818 public: 819 // Note: ctors taking a weak pointer to their owner must not promote it 820 // during construction (but may keep a reference for later promotion). ProxyCallback(const wp<DeviceEffectProxy> & owner,const sp<DeviceEffectManagerCallback> & callback)821 ProxyCallback(const wp<DeviceEffectProxy>& owner, 822 const sp<DeviceEffectManagerCallback>& callback) 823 : mProxy(owner), mManagerCallback(callback) {} 824 825 status_t createEffectHal(const effect_uuid_t *pEffectUuid, 826 int32_t sessionId, int32_t deviceId, sp<EffectHalInterface> *effect) override; allocateHalBuffer(size_t size __unused,sp<EffectBufferHalInterface> * buffer __unused)827 status_t allocateHalBuffer(size_t size __unused, 828 sp<EffectBufferHalInterface>* buffer __unused) override { return NO_ERROR; } updateOrphanEffectChains(const sp<IAfEffectBase> & effect __unused)829 bool updateOrphanEffectChains(const sp<IAfEffectBase>& effect __unused) override { 830 return false; 831 } 832 io()833 audio_io_handle_t io() const override { return AUDIO_IO_HANDLE_NONE; } 834 bool isOutput() const override; isOffload()835 bool isOffload() const override { return false; } isOffloadOrDirect()836 bool isOffloadOrDirect() const override { return false; } isOffloadOrMmap()837 bool isOffloadOrMmap() const override { return false; } isSpatializer()838 bool isSpatializer() const override { return false; } 839 840 uint32_t sampleRate() const override; 841 audio_channel_mask_t inChannelMask(int id) const override; 842 uint32_t inChannelCount(int id) const override; 843 audio_channel_mask_t outChannelMask() const override; 844 uint32_t outChannelCount() const override; hapticChannelMask()845 audio_channel_mask_t hapticChannelMask() const override { return AUDIO_CHANNEL_NONE; } 846 /** 847 * frameCount cannot be zero. 848 */ frameCount()849 size_t frameCount() const override { return 1; } latency()850 uint32_t latency() const override { return 0; } 851 852 status_t addEffectToHal(const sp<EffectHalInterface>& effect) override; 853 status_t removeEffectFromHal(const sp<EffectHalInterface>& effect) override; 854 855 bool disconnectEffectHandle(IAfEffectHandle *handle, bool unpinIfLast) override; setVolumeForOutput(float left __unused,float right __unused)856 void setVolumeForOutput(float left __unused, float right __unused) const override {} 857 checkSuspendOnEffectEnabled(const sp<IAfEffectBase> & effect __unused,bool enabled __unused,bool threadLocked __unused)858 void checkSuspendOnEffectEnabled(const sp<IAfEffectBase>& effect __unused, 859 bool enabled __unused, bool threadLocked __unused) override {} resetVolume_l()860 void resetVolume_l() override REQUIRES(audio_utils::EffectChain_Mutex) {} strategy()861 product_strategy_t strategy() const override { return PRODUCT_STRATEGY_NONE; } activeTrackCnt()862 int32_t activeTrackCnt() const override { return 0; } 863 void onEffectEnable(const sp<IAfEffectBase>& effect __unused) override; 864 void onEffectDisable(const sp<IAfEffectBase>& effect __unused) override; 865 chain()866 wp<IAfEffectChain> chain() const override { return nullptr; } 867 isAudioPolicyReady()868 bool isAudioPolicyReady() const override { 869 return mManagerCallback->isAudioPolicyReady(); 870 } 871 872 int newEffectId(); 873 874 private: 875 const wp<DeviceEffectProxy> mProxy; 876 const sp<DeviceEffectManagerCallback> mManagerCallback; 877 }; 878 879 status_t checkPort(const IAfPatchPanel::Patch& patch, 880 const struct audio_port_config* port, sp<IAfEffectHandle>* handle); 881 882 const AudioDeviceTypeAddr mDevice; 883 const sp<DeviceEffectManagerCallback> mManagerCallback; 884 const sp<ProxyCallback> mMyCallback; 885 proxyMutex()886 audio_utils::mutex& proxyMutex() const 887 RETURN_CAPABILITY(android::audio_utils::DeviceEffectProxy_ProxyMutex) { 888 return mProxyMutex; 889 } 890 mutable audio_utils::mutex mProxyMutex{ 891 audio_utils::MutexOrder::kDeviceEffectProxy_ProxyMutex}; 892 std::map<audio_patch_handle_t, sp<IAfEffectHandle>> mEffectHandles; // protected by mProxyMutex 893 sp<IAfEffectModule> mHalEffect; // protected by mProxyMutex 894 struct audio_port_config mDevicePort = { .id = AUDIO_PORT_HANDLE_NONE }; 895 const bool mNotifyFramesProcessed; 896 }; 897 898 } // namespace android 899