Effects.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. #ifndef INCLUDING_FROM_AUDIOFLINGER_H
  18. #error This header file should only be included from AudioFlinger.h
  19. #endif
  20. //--- Audio Effect Management
  21. // EffectModule and EffectChain classes both have their own mutex to protect
  22. // state changes or resource modifications. Always respect the following order
  23. // if multiple mutexes must be acquired to avoid cross deadlock:
  24. // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
  25. // AudioHandle -> ThreadBase -> EffectChain -> EffectModule
  26. // In addition, methods that lock the AudioPolicyService mutex (getOutputForEffect(),
  27. // startOutput(), getInputForAttr(), releaseInput()...) should never be called with AudioFlinger or
  28. // Threadbase mutex locked to avoid cross deadlock with other clients calling AudioPolicyService
  29. // methods that in turn call AudioFlinger thus locking the same mutexes in the reverse order.
  30. // The EffectModule class is a wrapper object controlling the effect engine implementation
  31. // in the effect library. It prevents concurrent calls to process() and command() functions
  32. // from different client threads. It keeps a list of EffectHandle objects corresponding
  33. // to all client applications using this effect and notifies applications of effect state,
  34. // control or parameter changes. It manages the activation state machine to send appropriate
  35. // reset, enable, disable commands to effect engine and provide volume
  36. // ramping when effects are activated/deactivated.
  37. // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
  38. // the attached track(s) to accumulate their auxiliary channel.
  39. class EffectModule : public RefBase {
  40. public:
  41. EffectModule(ThreadBase *thread,
  42. const wp<AudioFlinger::EffectChain>& chain,
  43. effect_descriptor_t *desc,
  44. int id,
  45. audio_session_t sessionId,
  46. bool pinned);
  47. virtual ~EffectModule();
  48. enum effect_state {
  49. IDLE,
  50. RESTART,
  51. STARTING,
  52. ACTIVE,
  53. STOPPING,
  54. STOPPED,
  55. DESTROYED
  56. };
  57. int id() const { return mId; }
  58. void process();
  59. bool updateState();
  60. status_t command(uint32_t cmdCode,
  61. uint32_t cmdSize,
  62. void *pCmdData,
  63. uint32_t *replySize,
  64. void *pReplyData);
  65. void reset_l();
  66. status_t configure();
  67. status_t init();
  68. effect_state state() const {
  69. return mState;
  70. }
  71. uint32_t status() {
  72. return mStatus;
  73. }
  74. audio_session_t sessionId() const {
  75. return mSessionId;
  76. }
  77. status_t setEnabled(bool enabled);
  78. status_t setEnabled_l(bool enabled);
  79. bool isEnabled() const;
  80. bool isProcessEnabled() const;
  81. bool isOffloadedOrDirect() const;
  82. bool isVolumeControlEnabled() const;
  83. void setInBuffer(const sp<EffectBufferHalInterface>& buffer);
  84. int16_t *inBuffer() const {
  85. return mInBuffer != 0 ? reinterpret_cast<int16_t*>(mInBuffer->ptr()) : NULL;
  86. }
  87. void setOutBuffer(const sp<EffectBufferHalInterface>& buffer);
  88. int16_t *outBuffer() const {
  89. return mOutBuffer != 0 ? reinterpret_cast<int16_t*>(mOutBuffer->ptr()) : NULL;
  90. }
  91. void setChain(const wp<EffectChain>& chain) { mChain = chain; }
  92. void setThread(const wp<ThreadBase>& thread)
  93. { mThread = thread; mThreadType = thread.promote()->type(); }
  94. const wp<ThreadBase>& thread() { return mThread; }
  95. status_t addHandle(EffectHandle *handle);
  96. ssize_t disconnectHandle(EffectHandle *handle, bool unpinIfLast);
  97. ssize_t removeHandle(EffectHandle *handle);
  98. ssize_t removeHandle_l(EffectHandle *handle);
  99. const effect_descriptor_t& desc() const { return mDescriptor; }
  100. wp<EffectChain>& chain() { return mChain; }
  101. status_t setDevice(audio_devices_t device);
  102. status_t setVolume(uint32_t *left, uint32_t *right, bool controller);
  103. status_t setMode(audio_mode_t mode);
  104. status_t setAudioSource(audio_source_t source);
  105. status_t start();
  106. status_t stop();
  107. void setSuspended(bool suspended);
  108. bool suspended() const;
  109. EffectHandle* controlHandle_l();
  110. bool isPinned() const { return mPinned; }
  111. void unPin() { mPinned = false; }
  112. bool purgeHandles();
  113. void lock() { mLock.lock(); }
  114. void unlock() { mLock.unlock(); }
  115. bool isOffloadable() const
  116. { return (mDescriptor.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) != 0; }
  117. bool isImplementationSoftware() const
  118. { return (mDescriptor.flags & EFFECT_FLAG_HW_ACC_MASK) == 0; }
  119. bool isProcessImplemented() const
  120. { return (mDescriptor.flags & EFFECT_FLAG_NO_PROCESS) == 0; }
  121. bool isVolumeControl() const
  122. { return (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK)
  123. == EFFECT_FLAG_VOLUME_CTRL; }
  124. bool isVolumeMonitor() const
  125. { return (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK)
  126. == EFFECT_FLAG_VOLUME_MONITOR; }
  127. status_t setOffloaded(bool offloaded, audio_io_handle_t io);
  128. bool isOffloaded() const;
  129. void addEffectToHal_l();
  130. void release_l();
  131. status_t updatePolicyState();
  132. void dump(int fd, const Vector<String16>& args);
  133. private:
  134. friend class AudioFlinger; // for mHandles
  135. bool mPinned;
  136. // Maximum time allocated to effect engines to complete the turn off sequence
  137. static const uint32_t MAX_DISABLE_TIME_MS = 10000;
  138. DISALLOW_COPY_AND_ASSIGN(EffectModule);
  139. status_t start_l();
  140. status_t stop_l();
  141. status_t remove_effect_from_hal_l();
  142. mutable Mutex mLock; // mutex for process, commands and handles list protection
  143. wp<ThreadBase> mThread; // parent thread
  144. ThreadBase::type_t mThreadType; // parent thread type
  145. wp<EffectChain> mChain; // 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_config_t mConfig; // input and output audio configuration
  150. sp<EffectHalInterface> mEffectInterface; // Effect module HAL
  151. sp<EffectBufferHalInterface> mInBuffer; // Buffers for interacting with HAL
  152. sp<EffectBufferHalInterface> mOutBuffer;
  153. status_t mStatus; // initialization status
  154. effect_state mState; // current activation state
  155. Vector<EffectHandle *> mHandles; // list of client handles
  156. // First handle in mHandles has highest priority and controls the effect module
  157. uint32_t mMaxDisableWaitCnt; // maximum grace period before forcing an effect off after
  158. // sending disable command.
  159. uint32_t mDisableWaitCnt; // current process() calls count during disable period.
  160. bool mSuspended; // effect is suspended: temporarily disabled by framework
  161. bool mOffloaded; // effect is currently offloaded to the audio DSP
  162. wp<AudioFlinger> mAudioFlinger;
  163. #ifdef FLOAT_EFFECT_CHAIN
  164. bool mSupportsFloat; // effect supports float processing
  165. sp<EffectBufferHalInterface> mInConversionBuffer; // Buffers for HAL conversion if needed.
  166. sp<EffectBufferHalInterface> mOutConversionBuffer;
  167. uint32_t mInChannelCountRequested;
  168. uint32_t mOutChannelCountRequested;
  169. #endif
  170. class AutoLockReentrant {
  171. public:
  172. AutoLockReentrant(Mutex& mutex, pid_t allowedTid)
  173. : mMutex(gettid() == allowedTid ? nullptr : &mutex)
  174. {
  175. if (mMutex != nullptr) mMutex->lock();
  176. }
  177. ~AutoLockReentrant() {
  178. if (mMutex != nullptr) mMutex->unlock();
  179. }
  180. private:
  181. Mutex * const mMutex;
  182. };
  183. static constexpr pid_t INVALID_PID = (pid_t)-1;
  184. // this tid is allowed to call setVolume() without acquiring the mutex.
  185. pid_t mSetVolumeReentrantTid = INVALID_PID;
  186. // Audio policy effect state management
  187. // Mutex protecting transactions with audio policy manager as mLock cannot
  188. // be held to avoid cross deadlocks with audio policy mutex
  189. Mutex mPolicyLock;
  190. // Effect is registered in APM or not
  191. bool mPolicyRegistered = false;
  192. // Effect enabled state communicated to APM. Enabled state corresponds to
  193. // state requested by the EffectHandle with control
  194. bool mPolicyEnabled = false;
  195. };
  196. // The EffectHandle class implements the IEffect interface. It provides resources
  197. // to receive parameter updates, keeps track of effect control
  198. // ownership and state and has a pointer to the EffectModule object it is controlling.
  199. // There is one EffectHandle object for each application controlling (or using)
  200. // an effect module.
  201. // The EffectHandle is obtained by calling AudioFlinger::createEffect().
  202. class EffectHandle: public android::BnEffect {
  203. public:
  204. EffectHandle(const sp<EffectModule>& effect,
  205. const sp<AudioFlinger::Client>& client,
  206. const sp<IEffectClient>& effectClient,
  207. int32_t priority);
  208. virtual ~EffectHandle();
  209. virtual status_t initCheck();
  210. // IEffect
  211. virtual status_t enable();
  212. virtual status_t disable();
  213. virtual status_t command(uint32_t cmdCode,
  214. uint32_t cmdSize,
  215. void *pCmdData,
  216. uint32_t *replySize,
  217. void *pReplyData);
  218. virtual void disconnect();
  219. private:
  220. void disconnect(bool unpinIfLast);
  221. public:
  222. virtual sp<IMemory> getCblk() const { return mCblkMemory; }
  223. virtual status_t onTransact(uint32_t code, const Parcel& data,
  224. Parcel* reply, uint32_t flags);
  225. // Give or take control of effect module
  226. // - hasControl: true if control is given, false if removed
  227. // - signal: true client app should be signaled of change, false otherwise
  228. // - enabled: state of the effect when control is passed
  229. void setControl(bool hasControl, bool signal, bool enabled);
  230. void commandExecuted(uint32_t cmdCode,
  231. uint32_t cmdSize,
  232. void *pCmdData,
  233. uint32_t replySize,
  234. void *pReplyData);
  235. void setEnabled(bool enabled);
  236. bool enabled() const { return mEnabled; }
  237. // Getters
  238. wp<EffectModule> effect() const { return mEffect; }
  239. int id() const {
  240. sp<EffectModule> effect = mEffect.promote();
  241. if (effect == 0) {
  242. return 0;
  243. }
  244. return effect->id();
  245. }
  246. int priority() const { return mPriority; }
  247. bool hasControl() const { return mHasControl; }
  248. bool disconnected() const { return mDisconnected; }
  249. void dumpToBuffer(char* buffer, size_t size);
  250. private:
  251. friend class AudioFlinger; // for mEffect, mHasControl, mEnabled
  252. DISALLOW_COPY_AND_ASSIGN(EffectHandle);
  253. Mutex mLock; // protects IEffect method calls
  254. wp<EffectModule> mEffect; // pointer to controlled EffectModule
  255. sp<IEffectClient> mEffectClient; // callback interface for client notifications
  256. /*const*/ sp<Client> mClient; // client for shared memory allocation, see disconnect()
  257. sp<IMemory> mCblkMemory; // shared memory for control block
  258. effect_param_cblk_t* mCblk; // control block for deferred parameter setting via
  259. // shared memory
  260. uint8_t* mBuffer; // pointer to parameter area in shared memory
  261. int mPriority; // client application priority to control the effect
  262. bool mHasControl; // true if this handle is controlling the effect
  263. bool mEnabled; // cached enable state: needed when the effect is
  264. // restored after being suspended
  265. bool mDisconnected; // Set to true by disconnect()
  266. };
  267. // the EffectChain class represents a group of effects associated to one audio session.
  268. // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
  269. // The EffectChain with session ID AUDIO_SESSION_OUTPUT_MIX contains global effects applied
  270. // to the output mix.
  271. // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to
  272. // tracks) are insert only. The EffectChain maintains an ordered list of effect module, the
  273. // order corresponding in the effect process order. When attached to a track (session ID !=
  274. // AUDIO_SESSION_OUTPUT_MIX),
  275. // it also provide it's own input buffer used by the track as accumulation buffer.
  276. class EffectChain : public RefBase {
  277. public:
  278. EffectChain(const wp<ThreadBase>& wThread, audio_session_t sessionId);
  279. EffectChain(ThreadBase *thread, audio_session_t sessionId);
  280. virtual ~EffectChain();
  281. // special key used for an entry in mSuspendedEffects keyed vector
  282. // corresponding to a suspend all request.
  283. static const int kKeyForSuspendAll = 0;
  284. // minimum duration during which we force calling effect process when last track on
  285. // a session is stopped or removed to allow effect tail to be rendered
  286. static const int kProcessTailDurationMs = 1000;
  287. void process_l();
  288. void lock() {
  289. mLock.lock();
  290. }
  291. void unlock() {
  292. mLock.unlock();
  293. }
  294. status_t createEffect_l(sp<EffectModule>& effect,
  295. ThreadBase *thread,
  296. effect_descriptor_t *desc,
  297. int id,
  298. audio_session_t sessionId,
  299. bool pinned);
  300. status_t addEffect_l(const sp<EffectModule>& handle);
  301. status_t addEffect_ll(const sp<EffectModule>& handle);
  302. size_t removeEffect_l(const sp<EffectModule>& handle, bool release = false);
  303. audio_session_t sessionId() const { return mSessionId; }
  304. void setSessionId(audio_session_t sessionId) { mSessionId = sessionId; }
  305. sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
  306. sp<EffectModule> getEffectFromId_l(int id);
  307. sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
  308. std::vector<int> getEffectIds();
  309. // FIXME use float to improve the dynamic range
  310. bool setVolume_l(uint32_t *left, uint32_t *right, bool force = false);
  311. void resetVolume_l();
  312. void setDevice_l(audio_devices_t device);
  313. void setMode_l(audio_mode_t mode);
  314. void setAudioSource_l(audio_source_t source);
  315. void setInBuffer(const sp<EffectBufferHalInterface>& buffer) {
  316. mInBuffer = buffer;
  317. }
  318. effect_buffer_t *inBuffer() const {
  319. return mInBuffer != 0 ? reinterpret_cast<effect_buffer_t*>(mInBuffer->ptr()) : NULL;
  320. }
  321. void setOutBuffer(const sp<EffectBufferHalInterface>& buffer) {
  322. mOutBuffer = buffer;
  323. }
  324. effect_buffer_t *outBuffer() const {
  325. return mOutBuffer != 0 ? reinterpret_cast<effect_buffer_t*>(mOutBuffer->ptr()) : NULL;
  326. }
  327. void incTrackCnt() { android_atomic_inc(&mTrackCnt); }
  328. void decTrackCnt() { android_atomic_dec(&mTrackCnt); }
  329. int32_t trackCnt() const { return android_atomic_acquire_load(&mTrackCnt); }
  330. void incActiveTrackCnt() { android_atomic_inc(&mActiveTrackCnt);
  331. mTailBufferCount = mMaxTailBuffers; }
  332. void decActiveTrackCnt() { android_atomic_dec(&mActiveTrackCnt); }
  333. int32_t activeTrackCnt() const { return android_atomic_acquire_load(&mActiveTrackCnt); }
  334. uint32_t strategy() const { return mStrategy; }
  335. void setStrategy(uint32_t strategy)
  336. { mStrategy = strategy; }
  337. // suspend or restore effects of the specified type. The number of suspend requests is counted
  338. // and restore occurs once all suspend requests are cancelled.
  339. void setEffectSuspended_l(const effect_uuid_t *type,
  340. bool suspend);
  341. // suspend all eligible effects
  342. void setEffectSuspendedAll_l(bool suspend);
  343. // check if effects should be suspend or restored when a given effect is enable or disabled
  344. void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
  345. bool enabled);
  346. void clearInputBuffer();
  347. // At least one non offloadable effect in the chain is enabled
  348. bool isNonOffloadableEnabled();
  349. bool isNonOffloadableEnabled_l();
  350. void syncHalEffectsState();
  351. // flags is an ORed set of audio_output_flags_t which is updated on return.
  352. void checkOutputFlagCompatibility(audio_output_flags_t *flags) const;
  353. // flags is an ORed set of audio_input_flags_t which is updated on return.
  354. void checkInputFlagCompatibility(audio_input_flags_t *flags) const;
  355. // Is this EffectChain compatible with the RAW audio flag.
  356. bool isRawCompatible() const;
  357. // Is this EffectChain compatible with the FAST audio flag.
  358. bool isFastCompatible() const;
  359. // isCompatibleWithThread_l() must be called with thread->mLock held
  360. bool isCompatibleWithThread_l(const sp<ThreadBase>& thread) const;
  361. void dump(int fd, const Vector<String16>& args);
  362. private:
  363. friend class AudioFlinger; // for mThread, mEffects
  364. DISALLOW_COPY_AND_ASSIGN(EffectChain);
  365. class SuspendedEffectDesc : public RefBase {
  366. public:
  367. SuspendedEffectDesc() : mRefCount(0) {}
  368. int mRefCount; // > 0 when suspended
  369. effect_uuid_t mType;
  370. wp<EffectModule> mEffect;
  371. };
  372. // get a list of effect modules to suspend when an effect of the type
  373. // passed is enabled.
  374. void getSuspendEligibleEffects(Vector< sp<EffectModule> > &effects);
  375. // get an effect module if it is currently enable
  376. sp<EffectModule> getEffectIfEnabled(const effect_uuid_t *type);
  377. // true if the effect whose descriptor is passed can be suspended
  378. // OEMs can modify the rules implemented in this method to exclude specific effect
  379. // types or implementations from the suspend/restore mechanism.
  380. bool isEffectEligibleForSuspend(const effect_descriptor_t& desc);
  381. static bool isEffectEligibleForBtNrecSuspend(const effect_uuid_t *type);
  382. void clearInputBuffer_l(const sp<ThreadBase>& thread);
  383. void setThread(const sp<ThreadBase>& thread);
  384. void setVolumeForOutput_l(uint32_t left, uint32_t right);
  385. wp<ThreadBase> mThread; // parent mixer thread
  386. mutable Mutex mLock; // mutex protecting effect list
  387. Vector< sp<EffectModule> > mEffects; // list of effect modules
  388. audio_session_t mSessionId; // audio session ID
  389. sp<EffectBufferHalInterface> mInBuffer; // chain input buffer
  390. sp<EffectBufferHalInterface> mOutBuffer; // chain output buffer
  391. // 'volatile' here means these are accessed with atomic operations instead of mutex
  392. volatile int32_t mActiveTrackCnt; // number of active tracks connected
  393. volatile int32_t mTrackCnt; // number of tracks connected
  394. int32_t mTailBufferCount; // current effect tail buffer count
  395. int32_t mMaxTailBuffers; // maximum effect tail buffers
  396. int mVolumeCtrlIdx; // index of insert effect having control over volume
  397. uint32_t mLeftVolume; // previous volume on left channel
  398. uint32_t mRightVolume; // previous volume on right channel
  399. uint32_t mNewLeftVolume; // new volume on left channel
  400. uint32_t mNewRightVolume; // new volume on right channel
  401. uint32_t mStrategy; // strategy for this effect chain
  402. // mSuspendedEffects lists all effects currently suspended in the chain.
  403. // Use effect type UUID timelow field as key. There is no real risk of identical
  404. // timeLow fields among effect type UUIDs.
  405. // Updated by setEffectSuspended_l() and setEffectSuspendedAll_l() only.
  406. KeyedVector< int, sp<SuspendedEffectDesc> > mSuspendedEffects;
  407. };