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