1 /*
2  * Copyright (C) 2022 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 #include <optional>
18 #include <string>
19 #define LOG_TAG "AHAL_EffectConfig"
20 #include <android-base/logging.h>
21 #include <system/audio_aidl_utils.h>
22 #include <system/audio_effects/audio_effects_conf.h>
23 #include <system/audio_effects/effect_uuid.h>
24 
25 #include "effectFactory-impl/EffectConfig.h"
26 
27 #ifdef __ANDROID_APEX__
28 #include <android/apexsupport.h>
29 #endif
30 
31 using aidl::android::media::audio::common::AudioSource;
32 using aidl::android::media::audio::common::AudioStreamType;
33 using aidl::android::media::audio::common::AudioUuid;
34 
35 namespace aidl::android::hardware::audio::effect {
36 
EffectConfig(const std::string & file)37 EffectConfig::EffectConfig(const std::string& file) {
38     tinyxml2::XMLDocument doc;
39     doc.LoadFile(file.c_str());
40     // parse the xml file into maps
41     if (doc.Error()) {
42         LOG(ERROR) << __func__ << " tinyxml2 failed to load " << file
43                    << " error: " << doc.ErrorStr();
44         return;
45     }
46 
47     auto registerFailure = [&](bool result) { mSkippedElements += result ? 0 : 1; };
48 
49     for (auto& xmlConfig : getChildren(doc, "audio_effects_conf")) {
50         // Parse library
51         for (auto& xmlLibraries : getChildren(xmlConfig, "libraries")) {
52             for (auto& xmlLibrary : getChildren(xmlLibraries, "library")) {
53                 registerFailure(parseLibrary(xmlLibrary));
54             }
55         }
56 
57         // Parse effects
58         for (auto& xmlEffects : getChildren(xmlConfig, "effects")) {
59             for (auto& xmlEffect : getChildren(xmlEffects)) {
60                 registerFailure(parseEffect(xmlEffect));
61             }
62         }
63 
64         // Parse pre processing chains
65         for (auto& xmlPreprocess : getChildren(xmlConfig, "preprocess")) {
66             for (auto& xmlStream : getChildren(xmlPreprocess, "stream")) {
67                 // AudioSource
68                 registerFailure(parseProcessing(Processing::Type::source, xmlStream));
69             }
70         }
71 
72         // Parse post processing chains
73         for (auto& xmlPostprocess : getChildren(xmlConfig, "postprocess")) {
74             for (auto& xmlStream : getChildren(xmlPostprocess, "stream")) {
75                 // AudioStreamType
76                 registerFailure(parseProcessing(Processing::Type::streamType, xmlStream));
77             }
78         }
79     }
80     LOG(DEBUG) << __func__ << " successfully parsed " << file << ", skipping " << mSkippedElements
81                << " element(s)";
82 }
83 
getChildren(const tinyxml2::XMLNode & node,const char * childTag)84 std::vector<std::reference_wrapper<const tinyxml2::XMLElement>> EffectConfig::getChildren(
85         const tinyxml2::XMLNode& node, const char* childTag) {
86     std::vector<std::reference_wrapper<const tinyxml2::XMLElement>> children;
87     for (auto* child = node.FirstChildElement(childTag); child != nullptr;
88          child = child->NextSiblingElement(childTag)) {
89         children.emplace_back(*child);
90     }
91     return children;
92 }
93 
resolveLibrary(const std::string & path,std::string * resolvedPath)94 bool EffectConfig::resolveLibrary(const std::string& path, std::string* resolvedPath) {
95     if constexpr (__ANDROID_VENDOR_API__ >= 202404) {
96         AApexInfo *apexInfo;
97         if (AApexInfo_create(&apexInfo) == AAPEXINFO_OK) {
98             std::string apexName(AApexInfo_getName(apexInfo));
99             AApexInfo_destroy(apexInfo);
100             std::string candidatePath("/apex/");
101             candidatePath.append(apexName).append(kEffectLibApexPath).append(path);
102             LOG(DEBUG) << __func__ << " effect lib path " << candidatePath;
103             if (access(candidatePath.c_str(), R_OK) == 0) {
104                 *resolvedPath = std::move(candidatePath);
105                 return true;
106             }
107         }
108     } else {
109         LOG(DEBUG) << __func__ << " libapexsupport is not supported";
110     }
111 
112     // If audio effects libs are not in vendor apex, locate them in kEffectLibPath
113     for (auto* libraryDirectory : kEffectLibPath) {
114         std::string candidatePath = std::string(libraryDirectory) + '/' + path;
115         if (access(candidatePath.c_str(), R_OK) == 0) {
116             *resolvedPath = std::move(candidatePath);
117             return true;
118         }
119     }
120     return false;
121 }
122 
parseLibrary(const tinyxml2::XMLElement & xml)123 bool EffectConfig::parseLibrary(const tinyxml2::XMLElement& xml) {
124     const char* name = xml.Attribute("name");
125     RETURN_VALUE_IF(!name, false, "noNameAttribute");
126     const char* path = xml.Attribute("path");
127     RETURN_VALUE_IF(!path, false, "noPathAttribute");
128 
129     std::string resolvedPath;
130     if (!resolveLibrary(path, &resolvedPath)) {
131         LOG(ERROR) << __func__ << " can't find " << path;
132         return false;
133     }
134     mLibraryMap[name] = resolvedPath;
135     LOG(DEBUG) << __func__ << " " << name << " : " << resolvedPath;
136     return true;
137 }
138 
parseEffect(const tinyxml2::XMLElement & xml)139 bool EffectConfig::parseEffect(const tinyxml2::XMLElement& xml) {
140     struct EffectLibraries effectLibraries;
141     std::vector<Library> libraries;
142     std::string name = xml.Attribute("name");
143     RETURN_VALUE_IF(name == "", false, "effectsNoName");
144 
145     LOG(VERBOSE) << __func__ << dump(xml);
146     struct Library library;
147     if (std::strcmp(xml.Name(), "effectProxy") == 0) {
148         // proxy lib and uuid
149         RETURN_VALUE_IF(!parseLibrary(xml, library, true), false, "parseProxyLibFailed");
150         effectLibraries.proxyLibrary = library;
151         // proxy effect libs and UUID
152         auto xmlProxyLib = xml.FirstChildElement();
153         RETURN_VALUE_IF(!xmlProxyLib, false, "noLibForProxy");
154         while (xmlProxyLib) {
155             struct Library tempLibrary;
156             RETURN_VALUE_IF(!parseLibrary(*xmlProxyLib, tempLibrary), false,
157                             "parseEffectLibFailed");
158             libraries.push_back(std::move(tempLibrary));
159             xmlProxyLib = xmlProxyLib->NextSiblingElement();
160         }
161     } else {
162         // expect only one library if not proxy
163         RETURN_VALUE_IF(!parseLibrary(xml, library), false, "parseEffectLibFailed");
164         libraries.push_back(std::move(library));
165     }
166 
167     effectLibraries.libraries = std::move(libraries);
168     mEffectsMap[name] = std::move(effectLibraries);
169     return true;
170 }
171 
parseLibrary(const tinyxml2::XMLElement & xml,struct Library & library,bool isProxy)172 bool EffectConfig::parseLibrary(const tinyxml2::XMLElement& xml, struct Library& library,
173                                 bool isProxy) {
174     // Retrieve library name only if not effectProxy element
175     if (!isProxy) {
176         const char* name = xml.Attribute("library");
177         RETURN_VALUE_IF(!name, false, "noLibraryAttribute");
178         library.name = name;
179     }
180 
181     const char* uuidStr = xml.Attribute("uuid");
182     RETURN_VALUE_IF(!uuidStr, false, "noUuidAttribute");
183     library.uuid = stringToUuid(uuidStr);
184     if (const char* typeUuidStr = xml.Attribute("type")) {
185         library.type = stringToUuid(typeUuidStr);
186     }
187     RETURN_VALUE_IF((library.uuid == getEffectUuidZero()), false, "invalidUuidAttribute");
188 
189     LOG(VERBOSE) << __func__ << (isProxy ? " proxy " : library.name) << " : uuid "
190                  << ::android::audio::utils::toString(library.uuid)
191                  << (library.type.has_value()
192                              ? ::android::audio::utils::toString(library.type.value())
193                              : "");
194     return true;
195 }
196 
stringToProcessingType(Processing::Type::Tag typeTag,const std::string & type)197 std::optional<Processing::Type> EffectConfig::stringToProcessingType(Processing::Type::Tag typeTag,
198                                                                      const std::string& type) {
199     // see list of audio stream types in audio_stream_type_t:
200     // system/media/audio/include/system/audio_effects/audio_effects_conf.h
201     // AUDIO_STREAM_DEFAULT_TAG is not listed here because according to SYS_RESERVED_DEFAULT in
202     // AudioStreamType.aidl: "Value reserved for system use only. HALs must never return this value
203     // to the system or accept it from the system".
204     static const std::map<const std::string, AudioStreamType> sAudioStreamTypeTable = {
205             {AUDIO_STREAM_VOICE_CALL_TAG, AudioStreamType::VOICE_CALL},
206             {AUDIO_STREAM_SYSTEM_TAG, AudioStreamType::SYSTEM},
207             {AUDIO_STREAM_RING_TAG, AudioStreamType::RING},
208             {AUDIO_STREAM_MUSIC_TAG, AudioStreamType::MUSIC},
209             {AUDIO_STREAM_ALARM_TAG, AudioStreamType::ALARM},
210             {AUDIO_STREAM_NOTIFICATION_TAG, AudioStreamType::NOTIFICATION},
211             {AUDIO_STREAM_BLUETOOTH_SCO_TAG, AudioStreamType::BLUETOOTH_SCO},
212             {AUDIO_STREAM_ENFORCED_AUDIBLE_TAG, AudioStreamType::ENFORCED_AUDIBLE},
213             {AUDIO_STREAM_DTMF_TAG, AudioStreamType::DTMF},
214             {AUDIO_STREAM_TTS_TAG, AudioStreamType::TTS},
215             {AUDIO_STREAM_ASSISTANT_TAG, AudioStreamType::ASSISTANT}};
216 
217     // see list of audio sources in audio_source_t:
218     // system/media/audio/include/system/audio_effects/audio_effects_conf.h
219     static const std::map<const std::string, AudioSource> sAudioSourceTable = {
220             {MIC_SRC_TAG, AudioSource::MIC},
221             {VOICE_UL_SRC_TAG, AudioSource::VOICE_UPLINK},
222             {VOICE_DL_SRC_TAG, AudioSource::VOICE_DOWNLINK},
223             {VOICE_CALL_SRC_TAG, AudioSource::VOICE_CALL},
224             {CAMCORDER_SRC_TAG, AudioSource::CAMCORDER},
225             {VOICE_REC_SRC_TAG, AudioSource::VOICE_RECOGNITION},
226             {VOICE_COMM_SRC_TAG, AudioSource::VOICE_COMMUNICATION},
227             {REMOTE_SUBMIX_SRC_TAG, AudioSource::REMOTE_SUBMIX},
228             {UNPROCESSED_SRC_TAG, AudioSource::UNPROCESSED},
229             {VOICE_PERFORMANCE_SRC_TAG, AudioSource::VOICE_PERFORMANCE}};
230 
231     if (typeTag == Processing::Type::streamType) {
232         auto typeIter = sAudioStreamTypeTable.find(type);
233         if (typeIter != sAudioStreamTypeTable.end()) {
234             return typeIter->second;
235         }
236     } else if (typeTag == Processing::Type::source) {
237         auto typeIter = sAudioSourceTable.find(type);
238         if (typeIter != sAudioSourceTable.end()) {
239             return typeIter->second;
240         }
241     }
242 
243     return std::nullopt;
244 }
245 
parseProcessing(Processing::Type::Tag typeTag,const tinyxml2::XMLElement & xml)246 bool EffectConfig::parseProcessing(Processing::Type::Tag typeTag, const tinyxml2::XMLElement& xml) {
247     LOG(VERBOSE) << __func__ << dump(xml);
248     const char* typeStr = xml.Attribute("type");
249     auto aidlType = stringToProcessingType(typeTag, typeStr);
250     RETURN_VALUE_IF(!aidlType.has_value(), false, "illegalStreamType");
251     RETURN_VALUE_IF(0 != mProcessingMap.count(aidlType.value()), false, "duplicateStreamType");
252 
253     for (auto& apply : getChildren(xml, "apply")) {
254         const char* name = apply.get().Attribute("effect");
255         if (mEffectsMap.find(name) == mEffectsMap.end()) {
256             LOG(ERROR) << __func__ << " effect " << name << " doesn't exist, skipping";
257             continue;
258         }
259         RETURN_VALUE_IF(!name, false, "noEffectAttribute");
260         mProcessingMap[aidlType.value()].emplace_back(mEffectsMap[name]);
261     }
262     return true;
263 }
264 
265 const std::map<Processing::Type, std::vector<EffectConfig::EffectLibraries>>&
getProcessingMap() const266 EffectConfig::getProcessingMap() const {
267     return mProcessingMap;
268 }
269 
findUuid(const std::pair<std::string,struct EffectLibraries> & effectElem,AudioUuid * uuid)270 bool EffectConfig::findUuid(const std::pair<std::string, struct EffectLibraries>& effectElem,
271                             AudioUuid* uuid) {
272 // Difference from EFFECT_TYPE_LIST_DEF, there could be multiple name mapping to same Effect Type
273 #define EFFECT_XML_TYPE_LIST_DEF(V)                        \
274     V("acoustic_echo_canceler", AcousticEchoCanceler)      \
275     V("automatic_gain_control_v1", AutomaticGainControlV1) \
276     V("automatic_gain_control_v2", AutomaticGainControlV2) \
277     V("bassboost", BassBoost)                              \
278     V("downmix", Downmix)                                  \
279     V("dynamics_processing", DynamicsProcessing)           \
280     V("equalizer", Equalizer)                              \
281     V("extensioneffect", Extension)                        \
282     V("haptic_generator", HapticGenerator)                 \
283     V("loudness_enhancer", LoudnessEnhancer)               \
284     V("env_reverb", EnvReverb)                             \
285     V("reverb_env_aux", EnvReverb)                         \
286     V("reverb_env_ins", EnvReverb)                         \
287     V("preset_reverb", PresetReverb)                       \
288     V("reverb_pre_aux", PresetReverb)                      \
289     V("reverb_pre_ins", PresetReverb)                      \
290     V("noise_suppression", NoiseSuppression)               \
291     V("spatializer", Spatializer)                          \
292     V("virtualizer", Virtualizer)                          \
293     V("visualizer", Visualizer)                            \
294     V("volume", Volume)
295 
296 #define GENERATE_MAP_ENTRY_V(s, symbol) {s, &getEffectTypeUuid##symbol},
297 
298     const std::string xmlEffectName = effectElem.first;
299     typedef const AudioUuid& (*UuidGetter)(void);
300     static const std::map<std::string, UuidGetter> uuidMap{
301             // std::make_pair("s", &getEffectTypeUuidExtension)};
302             {EFFECT_XML_TYPE_LIST_DEF(GENERATE_MAP_ENTRY_V)}};
303     if (auto it = uuidMap.find(xmlEffectName); it != uuidMap.end()) {
304         *uuid = (*it->second)();
305         return true;
306     }
307 
308     const auto& libs = effectElem.second.libraries;
309     for (const auto& lib : libs) {
310         if (lib.type.has_value()) {
311             *uuid = lib.type.value();
312             return true;
313         }
314     }
315     return false;
316 }
317 
dump(const tinyxml2::XMLElement & element,tinyxml2::XMLPrinter && printer) const318 const char* EffectConfig::dump(const tinyxml2::XMLElement& element,
319                                tinyxml2::XMLPrinter&& printer) const {
320     element.Accept(&printer);
321     return printer.CStr();
322 }
323 
324 }  // namespace aidl::android::hardware::audio::effect
325