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