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         {AUDIO_SOURCE_VOICE_PERFORMANCE, "voice_performance"},
119 };
120 
121 /** Find the stream type enum corresponding to the stream type name or return false */
122 template <class Type>
stringToStreamType(const char * streamName,Type * type)123 bool stringToStreamType(const char *streamName, Type* type)
124 {
125     for (auto& streamNamePair : STREAM_NAME_MAP<Type>) {
126         if (strcmp(streamNamePair.second, streamName) == 0) {
127             *type = streamNamePair.first;
128             return true;
129         }
130     }
131     return false;
132 }
133 
134 /** Parse a library xml note and push the result in libraries or return false on failure. */
parseLibrary(const XMLElement & xmlLibrary,Libraries * libraries)135 bool parseLibrary(const XMLElement& xmlLibrary, Libraries* libraries) {
136     const char* name = xmlLibrary.Attribute("name");
137     const char* path = xmlLibrary.Attribute("path");
138     if (name == nullptr || path == nullptr) {
139         ALOGE("library must have a name and a path: %s", dump(xmlLibrary));
140         return false;
141     }
142     libraries->push_back({name, path});
143     return true;
144 }
145 
146 /** Find an element in a collection by its name.
147  * @return nullptr if not found, the element address if found.
148  */
149 template <class T>
findByName(const char * name,std::vector<T> & collection)150 T* findByName(const char* name, std::vector<T>& collection) {
151     auto it = find_if(begin(collection), end(collection),
152                          [name] (auto& item) { return item.name == name; });
153     return it != end(collection) ? &*it : nullptr;
154 }
155 
156 /** Parse an effect from an xml element describing it.
157  * @return true and pushes the effect in effects on success,
158  *         false on failure. */
parseEffect(const XMLElement & xmlEffect,Libraries & libraries,Effects * effects)159 bool parseEffect(const XMLElement& xmlEffect, Libraries& libraries, Effects* effects) {
160     Effect effect{};
161 
162     const char* name = xmlEffect.Attribute("name");
163     if (name == nullptr) {
164         ALOGE("%s must have a name: %s", xmlEffect.Value(), dump(xmlEffect));
165         return false;
166     }
167     effect.name = name;
168 
169     // Function to parse effect.library and effect.uuid from xml
170     auto parseImpl = [&libraries](const XMLElement& xmlImpl, EffectImpl& effect) {
171         // Retrieve library name and uuid from xml
172         const char* libraryName = xmlImpl.Attribute("library");
173         const char* uuid = xmlImpl.Attribute("uuid");
174         if (libraryName == nullptr || uuid == nullptr) {
175             ALOGE("effect must have a library name and a uuid: %s", dump(xmlImpl));
176             return false;
177         }
178 
179         // Convert library name to a pointer to the previously loaded library
180         auto* library = findByName(libraryName, libraries);
181         if (library == nullptr) {
182             ALOGE("Could not find library referenced in: %s", dump(xmlImpl));
183             return false;
184         }
185         effect.library = library;
186 
187         if (!stringToUuid(uuid, &effect.uuid)) {
188             ALOGE("Invalid uuid in: %s", dump(xmlImpl));
189             return false;
190         }
191         return true;
192     };
193 
194     if (!parseImpl(xmlEffect, effect)) {
195         return false;
196     }
197 
198     // Handle proxy effects
199     effect.isProxy = false;
200     if (std::strcmp(xmlEffect.Name(), "effectProxy") == 0) {
201         effect.isProxy = true;
202 
203         // Function to parse libhw and libsw
204         auto parseProxy = [&xmlEffect, &parseImpl](const char* tag, EffectImpl& proxyLib) {
205             auto* xmlProxyLib = xmlEffect.FirstChildElement(tag);
206             if (xmlProxyLib == nullptr) {
207                 ALOGE("effectProxy must contain a <%s>: %s", tag, dump(xmlEffect));
208                 return false;
209             }
210             return parseImpl(*xmlProxyLib, proxyLib);
211         };
212         if (!parseProxy("libhw", effect.libHw) || !parseProxy("libsw", effect.libSw)) {
213             return false;
214         }
215     }
216 
217     effects->push_back(std::move(effect));
218     return true;
219 }
220 
221 /** Parse an stream from an xml element describing it.
222  * @return true and pushes the stream in streams on success,
223  *         false on failure. */
224 template <class Stream>
parseStream(const XMLElement & xmlStream,Effects & effects,std::vector<Stream> * streams)225 bool parseStream(const XMLElement& xmlStream, Effects& effects, std::vector<Stream>* streams) {
226     const char* streamType = xmlStream.Attribute("type");
227     if (streamType == nullptr) {
228         ALOGE("stream must have a type: %s", dump(xmlStream));
229         return false;
230     }
231     Stream stream;
232     if (!stringToStreamType(streamType, &stream.type)) {
233         ALOGE("Invalid stream type %s: %s", streamType, dump(xmlStream));
234         return false;
235     }
236 
237     for (auto& xmlApply : getChildren(xmlStream, "apply")) {
238         const char* effectName = xmlApply.get().Attribute("effect");
239         if (effectName == nullptr) {
240             ALOGE("stream/apply must have reference an effect: %s", dump(xmlApply));
241             return false;
242         }
243         auto* effect = findByName(effectName, effects);
244         if (effect == nullptr) {
245             ALOGE("Could not find effect referenced in: %s", dump(xmlApply));
246             return false;
247         }
248         stream.effects.emplace_back(*effect);
249     }
250     streams->push_back(std::move(stream));
251     return true;
252 }
253 
254 /** Internal version of the public parse(const char* path) where path always exist. */
parseWithPath(std::string && path)255 ParsingResult parseWithPath(std::string&& path) {
256     XMLDocument doc;
257     doc.LoadFile(path.c_str());
258     if (doc.Error()) {
259         ALOGE("Failed to parse %s: Tinyxml2 error (%d): %s", path.c_str(),
260               doc.ErrorID(), doc.ErrorStr());
261         return {nullptr, 0, std::move(path)};
262     }
263 
264     auto config = std::make_unique<Config>();
265     size_t nbSkippedElements = 0;
266     auto registerFailure = [&nbSkippedElements](bool result) {
267         nbSkippedElements += result ? 0 : 1;
268     };
269     for (auto& xmlConfig : getChildren(doc, "audio_effects_conf")) {
270 
271         // Parse library
272         for (auto& xmlLibraries : getChildren(xmlConfig, "libraries")) {
273             for (auto& xmlLibrary : getChildren(xmlLibraries, "library")) {
274                 registerFailure(parseLibrary(xmlLibrary, &config->libraries));
275             }
276         }
277 
278         // Parse effects
279         for (auto& xmlEffects : getChildren(xmlConfig, "effects")) {
280             for (auto& xmlEffect : getChildren(xmlEffects)) {
281                 registerFailure(parseEffect(xmlEffect, config->libraries, &config->effects));
282             }
283         }
284 
285         // Parse pre processing chains
286         for (auto& xmlPreprocess : getChildren(xmlConfig, "preprocess")) {
287             for (auto& xmlStream : getChildren(xmlPreprocess, "stream")) {
288                 registerFailure(parseStream(xmlStream, config->effects, &config->preprocess));
289             }
290         }
291 
292         // Parse post processing chains
293         for (auto& xmlPostprocess : getChildren(xmlConfig, "postprocess")) {
294             for (auto& xmlStream : getChildren(xmlPostprocess, "stream")) {
295                 registerFailure(parseStream(xmlStream, config->effects, &config->postprocess));
296             }
297         }
298     }
299     return {std::move(config), nbSkippedElements, std::move(path)};
300 }
301 
302 }; // namespace
303 
parse(const char * path)304 ParsingResult parse(const char* path) {
305     if (path != nullptr) {
306         return parseWithPath(path);
307     }
308 
309     for (const std::string& location : DEFAULT_LOCATIONS) {
310         std::string defaultPath = location + '/' + DEFAULT_NAME;
311         if (access(defaultPath.c_str(), R_OK) != 0) {
312             continue;
313         }
314         auto result = parseWithPath(std::move(defaultPath));
315         if (result.parsedConfig != nullptr) {
316             return result;
317         }
318     }
319 
320     ALOGE("Could not parse effect configuration in any of the default locations.");
321     return {nullptr, 0, ""};
322 }
323 
324 } // namespace effectsConfig
325 } // namespace android
326