1 /*
2  * Copyright (C) 2017 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 #define LOG_TAG "EffectsConfig"
18 
19 #include <algorithm>
20 #include <cstdint>
21 #include <functional>
22 #include <string>
23 #include <unistd.h>
24 
25 #include <tinyxml2.h>
26 #include <log/log.h>
27 
28 #include <media/EffectsConfig.h>
29 
30 using namespace tinyxml2;
31 
32 namespace android {
33 namespace effectsConfig {
34 
35 /** All functions except `parse(const char*)` are static. */
36 namespace {
37 
38 /** @return all `node`s children that are elements and match the tag if provided. */
getChildren(const XMLNode & node,const char * childTag=nullptr)39 std::vector<std::reference_wrapper<const XMLElement>> getChildren(const XMLNode& node,
40                                                                   const char* childTag = nullptr) {
41     std::vector<std::reference_wrapper<const XMLElement>> children;
42     for (auto* child = node.FirstChildElement(childTag); child != nullptr;
43             child = child->NextSiblingElement(childTag)) {
44         children.emplace_back(*child);
45     }
46     return children;
47 }
48 
49 /** @return xml dump of the provided element.
50  * By not providing a printer, it is implicitly created in the caller context.
51  * In such case the return pointer has the same lifetime as the expression containing dump().
52  */
dump(const XMLElement & element,XMLPrinter && printer={})53 const char* dump(const XMLElement& element, XMLPrinter&& printer = {}) {
54     element.Accept(&printer);
55     return printer.CStr();
56 }
57 
58 
stringToUuid(const char * str,effect_uuid_t * uuid)59 bool stringToUuid(const char *str, effect_uuid_t *uuid)
60 {
61     uint32_t tmp[10];
62 
63     if (sscanf(str, "%08x-%04x-%04x-%04x-%02x%02x%02x%02x%02x%02x",
64             tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5, tmp+6, tmp+7, tmp+8, tmp+9) < 10) {
65         return false;
66     }
67     uuid->timeLow = (uint32_t)tmp[0];
68     uuid->timeMid = (uint16_t)tmp[1];
69     uuid->timeHiAndVersion = (uint16_t)tmp[2];
70     uuid->clockSeq = (uint16_t)tmp[3];
71     uuid->node[0] = (uint8_t)tmp[4];
72     uuid->node[1] = (uint8_t)tmp[5];
73     uuid->node[2] = (uint8_t)tmp[6];
74     uuid->node[3] = (uint8_t)tmp[7];
75     uuid->node[4] = (uint8_t)tmp[8];
76     uuid->node[5] = (uint8_t)tmp[9];
77 
78     return true;
79 }
80 
81 /** Map the enum and string representation of a string type.
82  *  Intended to be specialized for each enum to deserialize.
83  *  The general template is disabled.
84  */
85 template <class Enum>
86 constexpr std::enable_if<false, Enum> STREAM_NAME_MAP;
87 
88 /** All output stream types which support effects.
89  * This need to be kept in sync with the xsd streamOutputType.
90  */
91 template <>
92 constexpr std::pair<audio_stream_type_t, const char*> STREAM_NAME_MAP<audio_stream_type_t>[] = {
93         {AUDIO_STREAM_VOICE_CALL, "voice_call"},
94         {AUDIO_STREAM_SYSTEM, "system"},
95         {AUDIO_STREAM_RING, "ring"},
96         {AUDIO_STREAM_MUSIC, "music"},
97         {AUDIO_STREAM_ALARM, "alarm"},
98         {AUDIO_STREAM_NOTIFICATION, "notification"},
99         {AUDIO_STREAM_BLUETOOTH_SCO, "bluetooth_sco"},
100         {AUDIO_STREAM_ENFORCED_AUDIBLE, "enforced_audible"},
101         {AUDIO_STREAM_DTMF, "dtmf"},
102         {AUDIO_STREAM_TTS, "tts"},
103 };
104 
105 /** All input stream types which support effects.
106  * This need to be kept in sync with the xsd streamOutputType.
107  */
108 template <>
109 constexpr std::pair<audio_source_t, const char*> STREAM_NAME_MAP<audio_source_t>[] = {
110         {AUDIO_SOURCE_MIC, "mic"},
111         {AUDIO_SOURCE_VOICE_UPLINK, "voice_uplink"},
112         {AUDIO_SOURCE_VOICE_DOWNLINK, "voice_downlink"},
113         {AUDIO_SOURCE_VOICE_CALL, "voice_call"},
114         {AUDIO_SOURCE_CAMCORDER, "camcorder"},
115         {AUDIO_SOURCE_VOICE_RECOGNITION, "voice_recognition"},
116         {AUDIO_SOURCE_VOICE_COMMUNICATION, "voice_communication"},
117         {AUDIO_SOURCE_UNPROCESSED, "unprocessed"},
118 };
119 
120 /** Find the stream type enum corresponding to the stream type name or return false */
121 template <class Type>
stringToStreamType(const char * streamName,Type * type)122 bool stringToStreamType(const char *streamName, Type* type)
123 {
124     for (auto& streamNamePair : STREAM_NAME_MAP<Type>) {
125         if (strcmp(streamNamePair.second, streamName) == 0) {
126             *type = streamNamePair.first;
127             return true;
128         }
129     }
130     return false;
131 }
132 
133 /** Parse a library xml note and push the result in libraries or return false on failure. */
parseLibrary(const XMLElement & xmlLibrary,Libraries * libraries)134 bool parseLibrary(const XMLElement& xmlLibrary, Libraries* libraries) {
135     const char* name = xmlLibrary.Attribute("name");
136     const char* path = xmlLibrary.Attribute("path");
137     if (name == nullptr || path == nullptr) {
138         ALOGE("library must have a name and a path: %s", dump(xmlLibrary));
139         return false;
140     }
141     libraries->push_back({name, path});
142     return true;
143 }
144 
145 /** Find an element in a collection by its name.
146  * @return nullptr if not found, the element address if found.
147  */
148 template <class T>
findByName(const char * name,std::vector<T> & collection)149 T* findByName(const char* name, std::vector<T>& collection) {
150     auto it = find_if(begin(collection), end(collection),
151                          [name] (auto& item) { return item.name == name; });
152     return it != end(collection) ? &*it : nullptr;
153 }
154 
155 /** Parse an effect from an xml element describing it.
156  * @return true and pushes the effect in effects on success,
157  *         false on failure. */
parseEffect(const XMLElement & xmlEffect,Libraries & libraries,Effects * effects)158 bool parseEffect(const XMLElement& xmlEffect, Libraries& libraries, Effects* effects) {
159     Effect effect{};
160 
161     const char* name = xmlEffect.Attribute("name");
162     if (name == nullptr) {
163         ALOGE("%s must have a name: %s", xmlEffect.Value(), dump(xmlEffect));
164         return false;
165     }
166     effect.name = name;
167 
168     // Function to parse effect.library and effect.uuid from xml
169     auto parseImpl = [&libraries](const XMLElement& xmlImpl, EffectImpl& effect) {
170         // Retrieve library name and uuid from xml
171         const char* libraryName = xmlImpl.Attribute("library");
172         const char* uuid = xmlImpl.Attribute("uuid");
173         if (libraryName == nullptr || uuid == nullptr) {
174             ALOGE("effect must have a library name and a uuid: %s", dump(xmlImpl));
175             return false;
176         }
177 
178         // Convert library name to a pointer to the previously loaded library
179         auto* library = findByName(libraryName, libraries);
180         if (library == nullptr) {
181             ALOGE("Could not find library referenced in: %s", dump(xmlImpl));
182             return false;
183         }
184         effect.library = library;
185 
186         if (!stringToUuid(uuid, &effect.uuid)) {
187             ALOGE("Invalid uuid in: %s", dump(xmlImpl));
188             return false;
189         }
190         return true;
191     };
192 
193     if (!parseImpl(xmlEffect, effect)) {
194         return false;
195     }
196 
197     // Handle proxy effects
198     effect.isProxy = false;
199     if (std::strcmp(xmlEffect.Name(), "effectProxy") == 0) {
200         effect.isProxy = true;
201 
202         // Function to parse libhw and libsw
203         auto parseProxy = [&xmlEffect, &parseImpl](const char* tag, EffectImpl& proxyLib) {
204             auto* xmlProxyLib = xmlEffect.FirstChildElement(tag);
205             if (xmlProxyLib == nullptr) {
206                 ALOGE("effectProxy must contain a <%s>: %s", tag, dump(xmlEffect));
207                 return false;
208             }
209             return parseImpl(*xmlProxyLib, proxyLib);
210         };
211         if (!parseProxy("libhw", effect.libHw) || !parseProxy("libsw", effect.libSw)) {
212             return false;
213         }
214     }
215 
216     effects->push_back(std::move(effect));
217     return true;
218 }
219 
220 /** Parse an stream from an xml element describing it.
221  * @return true and pushes the stream in streams on success,
222  *         false on failure. */
223 template <class Stream>
parseStream(const XMLElement & xmlStream,Effects & effects,std::vector<Stream> * streams)224 bool parseStream(const XMLElement& xmlStream, Effects& effects, std::vector<Stream>* streams) {
225     const char* streamType = xmlStream.Attribute("type");
226     if (streamType == nullptr) {
227         ALOGE("stream must have a type: %s", dump(xmlStream));
228         return false;
229     }
230     Stream stream;
231     if (!stringToStreamType(streamType, &stream.type)) {
232         ALOGE("Invalid stream type %s: %s", streamType, dump(xmlStream));
233         return false;
234     }
235 
236     for (auto& xmlApply : getChildren(xmlStream, "apply")) {
237         const char* effectName = xmlApply.get().Attribute("effect");
238         if (effectName == nullptr) {
239             ALOGE("stream/apply must have reference an effect: %s", dump(xmlApply));
240             return false;
241         }
242         auto* effect = findByName(effectName, effects);
243         if (effect == nullptr) {
244             ALOGE("Could not find effect referenced in: %s", dump(xmlApply));
245             return false;
246         }
247         stream.effects.emplace_back(*effect);
248     }
249     streams->push_back(std::move(stream));
250     return true;
251 }
252 
253 /** Internal version of the public parse(const char* path) with precondition `path != nullptr`. */
parseWithPath(const char * path)254 ParsingResult parseWithPath(const char* path) {
255     XMLDocument doc;
256     doc.LoadFile(path);
257     if (doc.Error()) {
258         ALOGE("Failed to parse %s: Tinyxml2 error (%d): %s", path,
259               doc.ErrorID(), doc.ErrorStr());
260         return {nullptr, 0, path};
261     }
262 
263     auto config = std::make_unique<Config>();
264     size_t nbSkippedElements = 0;
265     auto registerFailure = [&nbSkippedElements](bool result) {
266         nbSkippedElements += result ? 0 : 1;
267     };
268     for (auto& xmlConfig : getChildren(doc, "audio_effects_conf")) {
269 
270         // Parse library
271         for (auto& xmlLibraries : getChildren(xmlConfig, "libraries")) {
272             for (auto& xmlLibrary : getChildren(xmlLibraries, "library")) {
273                 registerFailure(parseLibrary(xmlLibrary, &config->libraries));
274             }
275         }
276 
277         // Parse effects
278         for (auto& xmlEffects : getChildren(xmlConfig, "effects")) {
279             for (auto& xmlEffect : getChildren(xmlEffects)) {
280                 registerFailure(parseEffect(xmlEffect, config->libraries, &config->effects));
281             }
282         }
283 
284         // Parse pre processing chains
285         for (auto& xmlPreprocess : getChildren(xmlConfig, "preprocess")) {
286             for (auto& xmlStream : getChildren(xmlPreprocess, "stream")) {
287                 registerFailure(parseStream(xmlStream, config->effects, &config->preprocess));
288             }
289         }
290 
291         // Parse post processing chains
292         for (auto& xmlPostprocess : getChildren(xmlConfig, "postprocess")) {
293             for (auto& xmlStream : getChildren(xmlPostprocess, "stream")) {
294                 registerFailure(parseStream(xmlStream, config->effects, &config->postprocess));
295             }
296         }
297     }
298     return {std::move(config), nbSkippedElements, path};
299 }
300 
301 }; // namespace
302 
parse(const char * path)303 ParsingResult parse(const char* path) {
304     if (path != nullptr) {
305         return parseWithPath(path);
306     }
307 
308     for (std::string location : DEFAULT_LOCATIONS) {
309         std::string defaultPath = location + '/' + DEFAULT_NAME;
310         if (access(defaultPath.c_str(), R_OK) != 0) {
311             continue;
312         }
313         auto result = parseWithPath(defaultPath.c_str());
314         if (result.parsedConfig != nullptr) {
315             return result;
316         }
317     }
318 
319     ALOGE("Could not parse effect configuration in any of the default locations.");
320     return {nullptr, 0, nullptr};
321 }
322 
323 } // namespace effectsConfig
324 } // namespace android
325