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 <dlfcn.h>
18 #include <algorithm>
19 #include <iterator>
20 #include <memory>
21 #include <optional>
22 #include <tuple>
23 #include <unordered_set>
24 #define LOG_TAG "AHAL_EffectFactory"
25
26 #include <android-base/logging.h>
27 #include <android/binder_ibinder_platform.h>
28 #include <system/audio_aidl_utils.h>
29 #include <system/audio_effects/effect_uuid.h>
30 #include <system/thread_defs.h>
31
32 #include "effect-impl/EffectTypes.h"
33 #include "effectFactory-impl/EffectFactory.h"
34
35 using aidl::android::media::audio::common::AudioUuid;
36
37 namespace aidl::android::hardware::audio::effect {
38
Factory(const std::string & file)39 Factory::Factory(const std::string& file) : mConfig(EffectConfig(file)) {
40 LOG(DEBUG) << __func__ << " with config file: " << file;
41 loadEffectLibs();
42 }
43
~Factory()44 Factory::~Factory() {
45 if (auto count = mEffectMap.size()) {
46 LOG(WARNING) << __func__ << " remaining " << count
47 << " effect instances not destroyed indicating resource leak!";
48 for (const auto& it : mEffectMap) {
49 if (auto spEffect = it.first.lock()) {
50 LOG(WARNING) << __func__ << " erase remaining instance UUID "
51 << ::android::audio::utils::toString(it.second.first);
52 destroyEffectImpl_l(spEffect);
53 }
54 }
55 }
56 }
57
getDescriptorWithUuid_l(const AudioUuid & uuid,Descriptor * desc)58 ndk::ScopedAStatus Factory::getDescriptorWithUuid_l(const AudioUuid& uuid, Descriptor* desc) {
59 RETURN_IF(!desc, EX_NULL_POINTER, "nullDescriptor");
60
61 if (mEffectLibMap.count(uuid)) {
62 auto& entry = mEffectLibMap[uuid];
63 getDlSyms_l(entry);
64 auto& libInterface = std::get<kMapEntryInterfaceIndex>(entry);
65 RETURN_IF(!libInterface || !libInterface->queryEffectFunc, EX_NULL_POINTER,
66 "dlNullQueryEffectFunc");
67 RETURN_IF_BINDER_EXCEPTION(libInterface->queryEffectFunc(&uuid, desc));
68 return ndk::ScopedAStatus::ok();
69 }
70
71 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
72 }
73
queryEffects(const std::optional<AudioUuid> & in_type_uuid,const std::optional<AudioUuid> & in_impl_uuid,const std::optional<AudioUuid> & in_proxy_uuid,std::vector<Descriptor> * _aidl_return)74 ndk::ScopedAStatus Factory::queryEffects(const std::optional<AudioUuid>& in_type_uuid,
75 const std::optional<AudioUuid>& in_impl_uuid,
76 const std::optional<AudioUuid>& in_proxy_uuid,
77 std::vector<Descriptor>* _aidl_return) {
78 std::lock_guard lg(mMutex);
79 // get the matching list
80 std::vector<Descriptor::Identity> idList;
81 std::copy_if(mIdentitySet.begin(), mIdentitySet.end(), std::back_inserter(idList),
82 [&](auto& id) {
83 return (!in_type_uuid.has_value() || in_type_uuid.value() == id.type) &&
84 (!in_impl_uuid.has_value() || in_impl_uuid.value() == id.uuid) &&
85 (!in_proxy_uuid.has_value() ||
86 (id.proxy.has_value() && in_proxy_uuid.value() == id.proxy.value()));
87 });
88 // query through the matching list
89 for (const auto& id : idList) {
90 if (mEffectLibMap.count(id.uuid)) {
91 Descriptor desc;
92 RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(id.uuid, &desc),
93 "getDescriptorFailed");
94 // update proxy UUID with information from config xml
95 desc.common.id.proxy = id.proxy;
96 _aidl_return->emplace_back(std::move(desc));
97 }
98 }
99 return ndk::ScopedAStatus::ok();
100 }
101
queryProcessing(const std::optional<Processing::Type> & in_type,std::vector<Processing> * _aidl_return)102 ndk::ScopedAStatus Factory::queryProcessing(const std::optional<Processing::Type>& in_type,
103 std::vector<Processing>* _aidl_return) {
104 std::lock_guard lg(mMutex);
105 const auto& processings = mConfig.getProcessingMap();
106 // Processing stream type
107 for (const auto& procIter : processings) {
108 if (!in_type.has_value() || in_type.value() == procIter.first) {
109 Processing process = {.type = procIter.first /* Processing::Type */};
110 for (const auto& libs : procIter.second /* std::vector<struct EffectLibraries> */) {
111 for (const auto& lib : libs.libraries /* std::vector<struct Library> */) {
112 Descriptor desc;
113 if (libs.proxyLibrary.has_value()) {
114 desc.common.id.proxy = libs.proxyLibrary.value().uuid;
115 }
116 RETURN_IF_ASTATUS_NOT_OK(getDescriptorWithUuid_l(lib.uuid, &desc),
117 "getDescriptorFailed");
118 process.ids.emplace_back(desc);
119 }
120 }
121 _aidl_return->emplace_back(process);
122 }
123 }
124
125 return ndk::ScopedAStatus::ok();
126 }
127
createEffect(const AudioUuid & in_impl_uuid,std::shared_ptr<IEffect> * _aidl_return)128 ndk::ScopedAStatus Factory::createEffect(const AudioUuid& in_impl_uuid,
129 std::shared_ptr<IEffect>* _aidl_return) {
130 LOG(DEBUG) << __func__ << ": UUID " << ::android::audio::utils::toString(in_impl_uuid);
131 std::lock_guard lg(mMutex);
132 if (mEffectLibMap.count(in_impl_uuid)) {
133 auto& entry = mEffectLibMap[in_impl_uuid];
134 getDlSyms_l(entry);
135
136 auto& libInterface = std::get<kMapEntryInterfaceIndex>(entry);
137 RETURN_IF(!libInterface || !libInterface->createEffectFunc, EX_NULL_POINTER,
138 "dlNullcreateEffectFunc");
139 std::shared_ptr<IEffect> effectSp;
140 RETURN_IF_BINDER_EXCEPTION(libInterface->createEffectFunc(&in_impl_uuid, &effectSp));
141 if (!effectSp) {
142 LOG(WARNING) << __func__ << ": library created null instance without return error!";
143 return ndk::ScopedAStatus::fromExceptionCode(EX_TRANSACTION_FAILED);
144 }
145 *_aidl_return = effectSp;
146 ndk::SpAIBinder effectBinder = effectSp->asBinder();
147 AIBinder_setMinSchedulerPolicy(effectBinder.get(), SCHED_NORMAL, ANDROID_PRIORITY_AUDIO);
148 AIBinder_setInheritRt(effectBinder.get(), true);
149 mEffectMap[std::weak_ptr<IEffect>(effectSp)] =
150 std::make_pair(in_impl_uuid, std::move(effectBinder));
151 return ndk::ScopedAStatus::ok();
152 } else {
153 LOG(ERROR) << __func__ << ": library doesn't exist";
154 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
155 }
156 return ndk::ScopedAStatus::ok();
157 }
158
destroyEffectImpl_l(const std::shared_ptr<IEffect> & in_handle)159 ndk::ScopedAStatus Factory::destroyEffectImpl_l(const std::shared_ptr<IEffect>& in_handle) {
160 std::weak_ptr<IEffect> wpHandle(in_handle);
161 // find the effect entry with key (std::weak_ptr<IEffect>)
162 if (auto effectIt = mEffectMap.find(wpHandle); effectIt != mEffectMap.end()) {
163 auto& uuid = effectIt->second.first;
164 // find implementation library with UUID
165 if (auto libIt = mEffectLibMap.find(uuid); libIt != mEffectLibMap.end()) {
166 auto& interface = std::get<kMapEntryInterfaceIndex>(libIt->second);
167 RETURN_IF(!interface || !interface->destroyEffectFunc, EX_NULL_POINTER,
168 "dlNulldestroyEffectFunc");
169 RETURN_IF_BINDER_EXCEPTION(interface->destroyEffectFunc(in_handle));
170 } else {
171 LOG(ERROR) << __func__ << ": UUID " << ::android::audio::utils::toString(uuid)
172 << " does not exist in libMap!";
173 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
174 }
175 mEffectMap.erase(effectIt);
176 return ndk::ScopedAStatus::ok();
177 } else {
178 LOG(ERROR) << __func__ << ": instance " << in_handle << " does not exist!";
179 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
180 }
181 }
182
183 // go over the map and cleanup all expired weak_ptrs.
cleanupEffectMap_l()184 void Factory::cleanupEffectMap_l() {
185 for (auto it = mEffectMap.begin(); it != mEffectMap.end();) {
186 if (nullptr == it->first.lock()) {
187 it = mEffectMap.erase(it);
188 } else {
189 ++it;
190 }
191 }
192 }
193
destroyEffect(const std::shared_ptr<IEffect> & in_handle)194 ndk::ScopedAStatus Factory::destroyEffect(const std::shared_ptr<IEffect>& in_handle) {
195 std::lock_guard lg(mMutex);
196 ndk::ScopedAStatus status = destroyEffectImpl_l(in_handle);
197 // always do the cleanup
198 cleanupEffectMap_l();
199 return status;
200 }
201
openEffectLibrary(const AudioUuid & impl,const std::string & path)202 bool Factory::openEffectLibrary(const AudioUuid& impl,
203 const std::string& path) NO_THREAD_SAFETY_ANALYSIS {
204 std::function<void(void*)> dlClose = [](void* handle) -> void {
205 if (handle && dlclose(handle)) {
206 LOG(ERROR) << "dlclose failed " << dlerror();
207 }
208 };
209
210 auto libHandle =
211 std::unique_ptr<void, decltype(dlClose)>{dlopen(path.c_str(), RTLD_LAZY), dlClose};
212 if (!libHandle) {
213 LOG(ERROR) << __func__ << ": dlopen failed, err: " << dlerror();
214 return false;
215 }
216
217 LOG(DEBUG) << __func__ << " dlopen lib: " << path
218 << "\nimpl:" << ::android::audio::utils::toString(impl) << "\nhandle:" << libHandle;
219 auto interface = new effect_dl_interface_s{nullptr, nullptr, nullptr};
220 mEffectLibMap.insert(
221 {impl,
222 std::make_tuple(std::move(libHandle),
223 std::unique_ptr<struct effect_dl_interface_s>(interface), path)});
224 return true;
225 }
226
createIdentityWithConfig(const EffectConfig::Library & configLib,const AudioUuid & typeUuid,const std::optional<AudioUuid> proxyUuid)227 void Factory::createIdentityWithConfig(
228 const EffectConfig::Library& configLib, const AudioUuid& typeUuid,
229 const std::optional<AudioUuid> proxyUuid) NO_THREAD_SAFETY_ANALYSIS {
230 static const auto& libMap = mConfig.getLibraryMap();
231 const std::string& libName = configLib.name;
232 if (auto path = libMap.find(libName); path != libMap.end()) {
233 Descriptor::Identity id;
234 id.type = typeUuid;
235 id.uuid = configLib.uuid;
236 id.proxy = proxyUuid;
237 LOG(WARNING) << __func__ << " loading lib " << path->second << ": typeUuid "
238 << ::android::audio::utils::toString(id.type) << "\nimplUuid "
239 << ::android::audio::utils::toString(id.uuid) << " proxyUuid "
240 << (proxyUuid.has_value()
241 ? ::android::audio::utils::toString(proxyUuid.value())
242 : "null");
243 if (openEffectLibrary(id.uuid, path->second)) {
244 mIdentitySet.insert(std::move(id));
245 }
246 } else {
247 LOG(ERROR) << __func__ << ": library " << libName << " not exist!";
248 return;
249 }
250 }
251
loadEffectLibs()252 void Factory::loadEffectLibs() {
253 const auto& configEffectsMap = mConfig.getEffectsMap();
254 for (const auto& configEffects : configEffectsMap) {
255 if (AudioUuid type; EffectConfig::findUuid(configEffects /* xml effect */, &type)) {
256 const auto& configLibs = configEffects.second;
257 std::optional<AudioUuid> proxyUuid;
258 if (configLibs.proxyLibrary.has_value()) {
259 const auto& proxyLib = configLibs.proxyLibrary.value();
260 proxyUuid = proxyLib.uuid;
261 }
262 for (const auto& configLib : configLibs.libraries) {
263 createIdentityWithConfig(configLib, type, proxyUuid);
264 }
265 } else {
266 LOG(WARNING) << __func__ << ": can not find type UUID for effect "
267 << configEffects.first << " skipping!";
268 }
269 }
270 }
271
getDlSyms_l(DlEntry & entry)272 void Factory::getDlSyms_l(DlEntry& entry) {
273 auto& dlHandle = std::get<kMapEntryHandleIndex>(entry);
274 RETURN_VALUE_IF(!dlHandle, void(), "dlNullHandle");
275 // Get the reference of the DL interfaces in library map tuple.
276 auto& dlInterface = std::get<kMapEntryInterfaceIndex>(entry);
277 // return if interface already exist
278 if (!dlInterface->createEffectFunc) {
279 dlInterface->createEffectFunc = (EffectCreateFunctor)dlsym(dlHandle.get(), "createEffect");
280 }
281 if (!dlInterface->queryEffectFunc) {
282 dlInterface->queryEffectFunc = (EffectQueryFunctor)dlsym(dlHandle.get(), "queryEffect");
283 }
284 if (!dlInterface->destroyEffectFunc) {
285 dlInterface->destroyEffectFunc =
286 (EffectDestroyFunctor)dlsym(dlHandle.get(), "destroyEffect");
287 }
288
289 if (!dlInterface->createEffectFunc || !dlInterface->destroyEffectFunc ||
290 !dlInterface->queryEffectFunc) {
291 LOG(ERROR) << __func__ << ": create (" << dlInterface->createEffectFunc << "), query ("
292 << dlInterface->queryEffectFunc << "), or destroy ("
293 << dlInterface->destroyEffectFunc
294 << ") not exist in library: " << std::get<kMapEntryLibNameIndex>(entry)
295 << " handle: " << dlHandle << " with dlerror: " << dlerror();
296 return;
297 }
298 }
299
300 } // namespace aidl::android::hardware::audio::effect
301