1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_AUDIOPOLICYEFFECTS_H
18 #define ANDROID_AUDIOPOLICYEFFECTS_H
19 
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <cutils/misc.h>
24 #include <media/AudioEffect.h>
25 #include <system/audio.h>
26 #include <utils/Vector.h>
27 #include <utils/SortedVector.h>
28 #include <android-base/thread_annotations.h>
29 
30 #include <future>
31 
32 namespace android {
33 
34 // ----------------------------------------------------------------------------
35 
36 // AudioPolicyEffects class
37 // This class will manage all effects attached to input and output streams in
38 // AudioPolicyService as configured in audio_effects.conf.
39 class AudioPolicyEffects : public RefBase
40 {
41 
42 public:
43 
44     // The constructor will parse audio_effects.conf
45     // First it will look whether vendor specific file exists,
46     // otherwise it will parse the system default file.
47 	         AudioPolicyEffects();
48     virtual ~AudioPolicyEffects();
49 
50     // NOTE: methods on AudioPolicyEffects should never be called with the AudioPolicyService
51     // main mutex (mLock) held as they will indirectly call back into AudioPolicyService when
52     // managing audio effects.
53 
54     // Return a list of effect descriptors for default input effects
55     // associated with audioSession
56     status_t queryDefaultInputEffects(audio_session_t audioSession,
57                              effect_descriptor_t *descriptors,
58                              uint32_t *count);
59 
60     // Add all input effects associated with this input
61     // Effects are attached depending on the audio_source_t
62     status_t addInputEffects(audio_io_handle_t input,
63                              audio_source_t inputSource,
64                              audio_session_t audioSession);
65 
66     // Add all input effects associated to this input
67     status_t releaseInputEffects(audio_io_handle_t input,
68                                  audio_session_t audioSession);
69 
70     // Return a list of effect descriptors for default output effects
71     // associated with audioSession
72     status_t queryDefaultOutputSessionEffects(audio_session_t audioSession,
73                              effect_descriptor_t *descriptors,
74                              uint32_t *count);
75 
76     // Add all output effects associated to this output
77     // Effects are attached depending on the audio_stream_type_t
78     status_t addOutputSessionEffects(audio_io_handle_t output,
79                              audio_stream_type_t stream,
80                              audio_session_t audioSession);
81 
82     // release all output effects associated with this output stream and audiosession
83     status_t releaseOutputSessionEffects(audio_io_handle_t output,
84                              audio_stream_type_t stream,
85                              audio_session_t audioSession);
86 
87     // Add the effect to the list of default effects for sources of type |source|.
88     status_t addSourceDefaultEffect(const effect_uuid_t *type,
89                                     const String16& opPackageName,
90                                     const effect_uuid_t *uuid,
91                                     int32_t priority,
92                                     audio_source_t source,
93                                     audio_unique_id_t* id);
94 
95     // Add the effect to the list of default effects for streams of a given usage.
96     status_t addStreamDefaultEffect(const effect_uuid_t *type,
97                                     const String16& opPackageName,
98                                     const effect_uuid_t *uuid,
99                                     int32_t priority,
100                                     audio_usage_t usage,
101                                     audio_unique_id_t* id);
102 
103     // Remove the default source effect from wherever it's attached.
104     status_t removeSourceDefaultEffect(audio_unique_id_t id);
105 
106     // Remove the default stream effect from wherever it's attached.
107     status_t removeStreamDefaultEffect(audio_unique_id_t id);
108 
109 private:
110     void initDefaultDeviceEffects();
111 
112     // class to store the description of an effects and its parameters
113     // as defined in audio_effects.conf
114     class EffectDesc {
115     public:
EffectDesc(const char * name,const effect_uuid_t & typeUuid,const String16 & opPackageName,const effect_uuid_t & uuid,uint32_t priority,audio_unique_id_t id)116         EffectDesc(const char *name,
117                    const effect_uuid_t& typeUuid,
118                    const String16& opPackageName,
119                    const effect_uuid_t& uuid,
120                    uint32_t priority,
121                    audio_unique_id_t id) :
122                         mName(strdup(name)),
123                         mTypeUuid(typeUuid),
124                         mOpPackageName(opPackageName),
125                         mUuid(uuid),
126                         mPriority(priority),
127                         mId(id) { }
EffectDesc(const char * name,const effect_uuid_t & uuid)128         EffectDesc(const char *name, const effect_uuid_t& uuid) :
129                         EffectDesc(name,
130                                    *EFFECT_UUID_NULL,
131                                    String16(""),
132                                    uuid,
133                                    0,
134                                    AUDIO_UNIQUE_ID_ALLOCATE) { }
EffectDesc(const EffectDesc & orig)135         EffectDesc(const EffectDesc& orig) :
136                         mName(strdup(orig.mName)),
137                         mTypeUuid(orig.mTypeUuid),
138                         mOpPackageName(orig.mOpPackageName),
139                         mUuid(orig.mUuid),
140                         mPriority(orig.mPriority),
141                         mId(orig.mId) {
142                             // deep copy mParams
143                             for (size_t k = 0; k < orig.mParams.size(); k++) {
144                                 effect_param_t *origParam = orig.mParams[k];
145                                 // psize and vsize are rounded up to an int boundary for allocation
146                                 size_t origSize = sizeof(effect_param_t) +
147                                                   ((origParam->psize + 3) & ~3) +
148                                                   ((origParam->vsize + 3) & ~3);
149                                 effect_param_t *dupParam = (effect_param_t *) malloc(origSize);
150                                 memcpy(dupParam, origParam, origSize);
151                                 // This works because the param buffer allocation is also done by
152                                 // multiples of 4 bytes originally. In theory we should memcpy only
153                                 // the actual param size, that is without rounding vsize.
154                                 mParams.add(dupParam);
155                             }
156                         }
~EffectDesc()157         /*virtual*/ ~EffectDesc() {
158             free(mName);
159             for (size_t k = 0; k < mParams.size(); k++) {
160                 free(mParams[k]);
161             }
162         }
163         char *mName;
164         effect_uuid_t mTypeUuid;
165         String16 mOpPackageName;
166         effect_uuid_t mUuid;
167         int32_t mPriority;
168         audio_unique_id_t mId;
169         Vector <effect_param_t *> mParams;
170     };
171 
172     // class to store voctor of EffectDesc
173     class EffectDescVector {
174     public:
EffectDescVector()175         EffectDescVector() {}
~EffectDescVector()176         /*virtual*/ ~EffectDescVector() {
177             for (size_t j = 0; j < mEffects.size(); j++) {
178                 delete mEffects[j];
179             }
180         }
181         Vector <EffectDesc *> mEffects;
182     };
183 
184     // class to store voctor of AudioEffects
185     class EffectVector {
186     public:
EffectVector(audio_session_t session)187         explicit EffectVector(audio_session_t session) : mSessionId(session), mRefCount(0) {}
~EffectVector()188         /*virtual*/ ~EffectVector() {}
189 
190         // Enable or disable all effects in effect vector
191         void setProcessorEnabled(bool enabled);
192 
193         const audio_session_t mSessionId;
194         // AudioPolicyManager keeps mLock, no need for lock on reference count here
195         int mRefCount;
196         Vector< sp<AudioEffect> >mEffects;
197     };
198 
199     /**
200      * @brief The DeviceEffects class stores the effects associated to a given Device Port.
201      */
202     class DeviceEffects {
203     public:
DeviceEffects(std::unique_ptr<EffectDescVector> effectDescriptors,audio_devices_t device,const std::string & address)204         DeviceEffects(std::unique_ptr<EffectDescVector> effectDescriptors,
205                                audio_devices_t device, const std::string& address) :
206             mEffectDescriptors(std::move(effectDescriptors)),
207             mDeviceType(device), mDeviceAddress(address) {}
208         /*virtual*/ ~DeviceEffects() = default;
209 
210         std::vector<std::unique_ptr<AudioEffect>> mEffects;
getDeviceType()211         audio_devices_t getDeviceType() const { return mDeviceType; }
getDeviceAddress()212         std::string getDeviceAddress() const { return mDeviceAddress; }
213         const std::unique_ptr<EffectDescVector> mEffectDescriptors;
214 
215     private:
216         const audio_devices_t mDeviceType;
217         const std::string mDeviceAddress;
218 
219     };
220 
221 
222     static const char * const kInputSourceNames[AUDIO_SOURCE_CNT -1];
223     static audio_source_t inputSourceNameToEnum(const char *name);
224 
225     static const char *kStreamNames[AUDIO_STREAM_PUBLIC_CNT+1]; //+1 required as streams start from -1
226     audio_stream_type_t streamNameToEnum(const char *name);
227 
228     // Parse audio_effects.conf
229     status_t loadAudioEffectConfig(const char *path); // TODO: add legacy in the name
230     status_t loadAudioEffectXmlConfig(); // TODO: remove "Xml" in the name
231 
232     // Load all effects descriptors in configuration file
233     status_t loadEffects(cnode *root, Vector <EffectDesc *>& effects);
234     EffectDesc *loadEffect(cnode *root);
235 
236     // Load all automatic effect configurations
237     status_t loadInputEffectConfigurations(cnode *root, const Vector <EffectDesc *>& effects);
238     status_t loadStreamEffectConfigurations(cnode *root, const Vector <EffectDesc *>& effects);
239     EffectDescVector *loadEffectConfig(cnode *root, const Vector <EffectDesc *>& effects);
240 
241     // Load all automatic effect parameters
242     void loadEffectParameters(cnode *root, Vector <effect_param_t *>& params);
243     effect_param_t *loadEffectParameter(cnode *root);
244     size_t readParamValue(cnode *node,
245                           char **param,
246                           size_t *curSize,
247                           size_t *totSize);
248     size_t growParamSize(char **param,
249                          size_t size,
250                          size_t *curSize,
251                          size_t *totSize);
252 
253     // protects access to mInputSources, mInputSessions, mOutputStreams, mOutputSessions
254     // never hold AudioPolicyService::mLock when calling AudioPolicyEffects methods as
255     // those can call back into AudioPolicyService methods and try to acquire the mutex
256     Mutex mLock;
257     // Automatic input effects are configured per audio_source_t
258     KeyedVector< audio_source_t, EffectDescVector* > mInputSources;
259     // Automatic input effects are unique for audio_io_handle_t
260     KeyedVector< audio_session_t, EffectVector* > mInputSessions;
261 
262     // Automatic output effects are organized per audio_stream_type_t
263     KeyedVector< audio_stream_type_t, EffectDescVector* > mOutputStreams;
264     // Automatic output effects are unique for audiosession ID
265     KeyedVector< audio_session_t, EffectVector* > mOutputSessions;
266 
267     /**
268      * @brief mDeviceEffects map of device effects indexed by the device address
269      */
270     std::map<std::string, std::unique_ptr<DeviceEffects>> mDeviceEffects GUARDED_BY(mLock);
271 
272     /**
273      * Device Effect initialization must be asynchronous: the audio_policy service parses and init
274      * effect on first reference. AudioFlinger will handle effect creation and register these
275      * effect on audio_policy service.
276      * We must store the reference of the furture garantee real asynchronous operation.
277      */
278     std::future<void> mDefaultDeviceEffectFuture;
279 };
280 
281 } // namespace android
282 
283 #endif // ANDROID_AUDIOPOLICYEFFECTS_H
284