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