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 <algorithm>
18 #include <cstddef>
19 #include <cstdint>
20 #include <iterator>
21 #include <memory>
22 #define LOG_TAG "EffectsFactoryHalAidl"
23 //#define LOG_NDEBUG 0
24 
25 #include <error/expected_utils.h>
26 #include <aidl/android/media/audio/common/AudioStreamType.h>
27 #include <android/binder_manager.h>
28 #include <media/AidlConversionCppNdk.h>
29 #include <media/AidlConversionEffect.h>
30 #include <system/audio.h>
31 #include <system/audio_aidl_utils.h>
32 #include <utils/Log.h>
33 
34 #include "AidlUtils.h"
35 #include "EffectBufferHalAidl.h"
36 #include "EffectHalAidl.h"
37 #include "EffectProxy.h"
38 #include "EffectsFactoryHalAidl.h"
39 
40 using ::aidl::android::legacy2aidl_audio_uuid_t_AudioUuid;
41 using ::aidl::android::aidl_utils::statusTFromBinderStatus;
42 using ::aidl::android::hardware::audio::effect::Descriptor;
43 using ::aidl::android::hardware::audio::effect::IFactory;
44 using ::aidl::android::hardware::audio::effect::Processing;
45 using ::aidl::android::media::audio::common::AudioSource;
46 using ::aidl::android::media::audio::common::AudioStreamType;
47 using ::aidl::android::media::audio::common::AudioUuid;
48 using ::android::audio::utils::toString;
49 using ::android::base::unexpected;
50 using ::android::detail::AudioHalVersionInfo;
51 
52 namespace android {
53 namespace effect {
54 
EffectsFactoryHalAidl(std::shared_ptr<IFactory> effectsFactory)55 EffectsFactoryHalAidl::EffectsFactoryHalAidl(std::shared_ptr<IFactory> effectsFactory)
56     : mFactory(effectsFactory),
57       mHalVersion(AudioHalVersionInfo(
58               AudioHalVersionInfo::Type::AIDL,
59               [this]() {
60                   int32_t majorVersion = 0;
61                   return (mFactory && mFactory->getInterfaceVersion(&majorVersion).isOk())
62                                  ? majorVersion
63                                  : 0;
64               }())),
__anonb7f55f2a0202() 65       mHalDescList([this]() {
66           std::vector<Descriptor> list;
67           if (mFactory) {
68               mFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &list).isOk();
69           }
70           return list;
71       }()),
__anonb7f55f2a0302() 72       mProxyUuidDescriptorMap([this]() {
73           std::map<AudioUuid, std::vector<Descriptor>> proxyUuidMap;
74           for (const auto& desc : mHalDescList) {
75               if (desc.common.id.proxy.has_value()) {
76                   const auto& uuid = desc.common.id.proxy.value();
77                   if (proxyUuidMap.count(uuid) == 0) {
78                       proxyUuidMap.insert({uuid, {desc}});
79                   } else {
80                       proxyUuidMap[uuid].emplace_back(desc);
81                   }
82               }
83           }
84           return proxyUuidMap;
85       }()),
__anonb7f55f2a0402() 86       mProxyDescList([this]() {
87           std::vector<Descriptor> list;
88           for (const auto& proxy : mProxyUuidDescriptorMap) {
89               if (Descriptor desc;
90                   EffectProxy::buildDescriptor(proxy.first /* uuid */,
91                                                proxy.second /* sub-effect descriptor list */,
92                                                &desc /* proxy descriptor */)
93                           .isOk()) {
94                   list.emplace_back(std::move(desc));
95               }
96           }
97           return list;
98       }()),
__anonb7f55f2a0502() 99       mNonProxyDescList([this]() {
100           std::vector<Descriptor> list;
101           std::copy_if(mHalDescList.begin(), mHalDescList.end(), std::back_inserter(list),
102                        [](const Descriptor& desc) { return !desc.common.id.proxy.has_value(); });
103           return list;
104       }()),
105       mEffectCount(mNonProxyDescList.size() + mProxyDescList.size()),
__anonb7f55f2a0702() 106       mAidlProcessings([this]() -> std::vector<Processing> {
107           std::vector<Processing> processings;
108           if (!mFactory || !mFactory->queryProcessing(std::nullopt, &processings).isOk()) {
109               ALOGE("%s queryProcessing failed", __func__);
110           }
111           return processings;
112       }()) {
113     ALOG_ASSERT(mFactory != nullptr, "Provided IEffectsFactory service is NULL");
114     ALOGI("%s with %zu nonProxyEffects and %zu proxyEffects", __func__, mNonProxyDescList.size(),
115           mProxyDescList.size());
116 }
117 
queryNumberEffects(uint32_t * pNumEffects)118 status_t EffectsFactoryHalAidl::queryNumberEffects(uint32_t *pNumEffects) {
119     if (pNumEffects == nullptr) {
120         return BAD_VALUE;
121     }
122 
123     *pNumEffects = mEffectCount;
124     return OK;
125 }
126 
getDescriptor(uint32_t index,effect_descriptor_t * pDescriptor)127 status_t EffectsFactoryHalAidl::getDescriptor(uint32_t index, effect_descriptor_t* pDescriptor) {
128     if (pDescriptor == nullptr) {
129         return BAD_VALUE;
130     }
131 
132     if (index >= mEffectCount) {
133         ALOGE("%s index %d exceed max number %zu", __func__, index, mEffectCount);
134         return INVALID_OPERATION;
135     }
136 
137     if (index >= mNonProxyDescList.size()) {
138         *pDescriptor =
139                 VALUE_OR_RETURN_STATUS(::aidl::android::aidl2legacy_Descriptor_effect_descriptor(
140                         mProxyDescList.at(index - mNonProxyDescList.size())));
141     } else {
142         *pDescriptor =
143                 VALUE_OR_RETURN_STATUS(::aidl::android::aidl2legacy_Descriptor_effect_descriptor(
144                         mNonProxyDescList.at(index)));
145     }
146     return OK;
147 }
148 
getDescriptor(const effect_uuid_t * halUuid,effect_descriptor_t * pDescriptor)149 status_t EffectsFactoryHalAidl::getDescriptor(const effect_uuid_t* halUuid,
150                                               effect_descriptor_t* pDescriptor) {
151     if (halUuid == nullptr) {
152         return BAD_VALUE;
153     }
154 
155     AudioUuid uuid =
156             VALUE_OR_RETURN_STATUS(::aidl::android::legacy2aidl_audio_uuid_t_AudioUuid(*halUuid));
157     return getHalDescriptorWithImplUuid(uuid, pDescriptor);
158 }
159 
getDescriptors(const effect_uuid_t * halType,std::vector<effect_descriptor_t> * descriptors)160 status_t EffectsFactoryHalAidl::getDescriptors(const effect_uuid_t* halType,
161                                                std::vector<effect_descriptor_t>* descriptors) {
162     if (halType == nullptr) {
163         return BAD_VALUE;
164     }
165 
166     AudioUuid type =
167             VALUE_OR_RETURN_STATUS(::aidl::android::legacy2aidl_audio_uuid_t_AudioUuid(*halType));
168     return getHalDescriptorWithTypeUuid(type, descriptors);
169 }
170 
createEffect(const effect_uuid_t * uuid,int32_t sessionId,int32_t ioId,int32_t deviceId __unused,sp<EffectHalInterface> * effect)171 status_t EffectsFactoryHalAidl::createEffect(const effect_uuid_t* uuid, int32_t sessionId,
172                                              int32_t ioId, int32_t deviceId __unused,
173                                              sp<EffectHalInterface>* effect) {
174     if (uuid == nullptr || effect == nullptr) {
175         return BAD_VALUE;
176     }
177     if (sessionId == AUDIO_SESSION_DEVICE && ioId == AUDIO_IO_HANDLE_NONE) {
178         return INVALID_OPERATION;
179     }
180     ALOGV("%s session %d ioId %d", __func__, sessionId, ioId);
181 
182     AudioUuid aidlUuid =
183             VALUE_OR_RETURN_STATUS(::aidl::android::legacy2aidl_audio_uuid_t_AudioUuid(*uuid));
184     std::shared_ptr<IEffect> aidlEffect;
185     // Use EffectProxy interface instead of IFactory to create
186     const bool isProxy = isProxyEffect(aidlUuid);
187     if (isProxy) {
188         aidlEffect = ndk::SharedRefBase::make<EffectProxy>(
189                 aidlUuid, mProxyUuidDescriptorMap.at(aidlUuid) /* sub-effect descriptor list */,
190                 mFactory);
191     } else {
192         RETURN_STATUS_IF_ERROR(
193                 statusTFromBinderStatus(mFactory->createEffect(aidlUuid, &aidlEffect)));
194     }
195     if (aidlEffect == nullptr) {
196         ALOGE("%s failed to create effect with UUID: %s", __func__, toString(aidlUuid).c_str());
197         return NAME_NOT_FOUND;
198     }
199     Descriptor desc;
200     RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(aidlEffect->getDescriptor(&desc)));
201 
202     *effect = sp<EffectHalAidl>::make(mFactory, aidlEffect, sessionId, ioId, desc, isProxy);
203     return OK;
204 }
205 
dumpEffects(int fd)206 status_t EffectsFactoryHalAidl::dumpEffects(int fd) {
207     // TODO: b/333803769 improve the effect dump implementation
208     RETURN_STATUS_IF_ERROR(mFactory->dump(fd, nullptr, 0));
209     return OK;
210 }
211 
allocateBuffer(size_t size,sp<EffectBufferHalInterface> * buffer)212 status_t EffectsFactoryHalAidl::allocateBuffer(size_t size, sp<EffectBufferHalInterface>* buffer) {
213     return EffectBufferHalAidl::allocate(size, buffer);
214 }
215 
mirrorBuffer(void * external,size_t size,sp<EffectBufferHalInterface> * buffer)216 status_t EffectsFactoryHalAidl::mirrorBuffer(void* external, size_t size,
217                                              sp<EffectBufferHalInterface>* buffer) {
218     return EffectBufferHalAidl::mirror(external, size, buffer);
219 }
220 
getHalVersion() const221 AudioHalVersionInfo EffectsFactoryHalAidl::getHalVersion() const {
222     return mHalVersion;
223 }
224 
getHalDescriptorWithImplUuid(const AudioUuid & uuid,effect_descriptor_t * pDescriptor)225 status_t EffectsFactoryHalAidl::getHalDescriptorWithImplUuid(const AudioUuid& uuid,
226                                                              effect_descriptor_t* pDescriptor) {
227     if (pDescriptor == nullptr) {
228         return BAD_VALUE;
229     }
230 
231     const auto& list = isProxyEffect(uuid) ? mProxyDescList : mNonProxyDescList;
232     auto matchIt = std::find_if(list.begin(), list.end(),
233                                 [&](const auto& desc) { return desc.common.id.uuid == uuid; });
234     if (matchIt == list.end()) {
235         ALOGE("%s UUID not found in HAL and proxy list %s", __func__, toString(uuid).c_str());
236         return NAME_NOT_FOUND;
237     }
238 
239     *pDescriptor = VALUE_OR_RETURN_STATUS(
240             ::aidl::android::aidl2legacy_Descriptor_effect_descriptor(*matchIt));
241     return OK;
242 }
243 
getHalDescriptorWithTypeUuid(const AudioUuid & type,std::vector<effect_descriptor_t> * descriptors)244 status_t EffectsFactoryHalAidl::getHalDescriptorWithTypeUuid(
245         const AudioUuid& type, std::vector<effect_descriptor_t>* descriptors) {
246     if (descriptors == nullptr) {
247         return BAD_VALUE;
248     }
249 
250     std::vector<Descriptor> result;
251     std::copy_if(mNonProxyDescList.begin(), mNonProxyDescList.end(), std::back_inserter(result),
252                  [&](auto& desc) { return desc.common.id.type == type; });
253     std::copy_if(mProxyDescList.begin(), mProxyDescList.end(), std::back_inserter(result),
254                  [&](auto& desc) { return desc.common.id.type == type; });
255     if (result.empty()) {
256         ALOGW("%s UUID type not found in HAL and proxy list %s", __func__, toString(type).c_str());
257         return BAD_VALUE;
258     }
259 
260     *descriptors = VALUE_OR_RETURN_STATUS(
261             aidl::android::convertContainer<std::vector<effect_descriptor_t>>(
262                     result, ::aidl::android::aidl2legacy_Descriptor_effect_descriptor));
263     return OK;
264 }
265 
isProxyEffect(const AudioUuid & uuid) const266 bool EffectsFactoryHalAidl::isProxyEffect(const AudioUuid& uuid) const {
267     return 0 != mProxyUuidDescriptorMap.count(uuid);
268 }
269 
getProcessings() const270 std::shared_ptr<const effectsConfig::Processings> EffectsFactoryHalAidl::getProcessings() const {
271 
272     auto getConfigEffectWithDescriptor =
273             [](const auto& desc) -> std::shared_ptr<const effectsConfig::Effect> {
274         effectsConfig::Effect effect = {.name = desc.common.name, .isProxy = false};
275         if (const auto uuid =
276                     ::aidl::android::aidl2legacy_AudioUuid_audio_uuid_t(desc.common.id.uuid);
277             uuid.ok()) {
278             static_cast<effectsConfig::EffectImpl&>(effect).uuid = uuid.value();
279             return std::make_shared<const effectsConfig::Effect>(effect);
280         } else {
281             return nullptr;
282         }
283     };
284 
285     auto getConfigProcessingWithAidlProcessing =
286             [&](const auto& aidlProcess, std::vector<effectsConfig::InputStream>& preprocess,
287                 std::vector<effectsConfig::OutputStream>& postprocess) {
288                 if (aidlProcess.type.getTag() == Processing::Type::streamType) {
289                     AudioStreamType aidlType =
290                             aidlProcess.type.template get<Processing::Type::streamType>();
291                     const auto type =
292                             ::aidl::android::aidl2legacy_AudioStreamType_audio_stream_type_t(
293                                     aidlType);
294                     if (!type.ok()) {
295                         return;
296                     }
297 
298                     std::vector<std::shared_ptr<const effectsConfig::Effect>> effects;
299                     std::transform(aidlProcess.ids.begin(), aidlProcess.ids.end(),
300                                    std::back_inserter(effects), getConfigEffectWithDescriptor);
301                     effectsConfig::OutputStream stream = {.type = type.value(),
302                                                           .effects = std::move(effects)};
303                     postprocess.emplace_back(stream);
304                 } else if (aidlProcess.type.getTag() == Processing::Type::source) {
305                     AudioSource aidlType =
306                             aidlProcess.type.template get<Processing::Type::source>();
307                     const auto type =
308                             ::aidl::android::aidl2legacy_AudioSource_audio_source_t(aidlType);
309                     if (!type.ok()) {
310                         return;
311                     }
312 
313                     std::vector<std::shared_ptr<const effectsConfig::Effect>> effects;
314                     std::transform(aidlProcess.ids.begin(), aidlProcess.ids.end(),
315                                    std::back_inserter(effects), getConfigEffectWithDescriptor);
316                     effectsConfig::InputStream stream = {.type = type.value(),
317                                                          .effects = std::move(effects)};
318                     preprocess.emplace_back(stream);
319                 }
320             };
321 
322     static std::shared_ptr<const effectsConfig::Processings> processings(
323             [&]() -> std::shared_ptr<const effectsConfig::Processings> {
324                 std::vector<effectsConfig::InputStream> preprocess;
325                 std::vector<effectsConfig::OutputStream> postprocess;
326                 for (const auto& processing : mAidlProcessings) {
327                     getConfigProcessingWithAidlProcessing(processing, preprocess, postprocess);
328                 }
329 
330                 if (0 == preprocess.size() && 0 == postprocess.size()) {
331                     return nullptr;
332                 }
333 
334                 return std::make_shared<const effectsConfig::Processings>(
335                         effectsConfig::Processings({.preprocess = std::move(preprocess),
336                                                     .postprocess = std::move(postprocess)}));
337             }());
338 
339     return processings;
340 }
341 
342 // Return 0 for AIDL, as the AIDL interface is not aware of the configuration file.
getSkippedElements() const343 ::android::error::Result<size_t> EffectsFactoryHalAidl::getSkippedElements() const {
344     return 0;
345 }
346 
347 } // namespace effect
348 
349 // When a shared library is built from a static library, even explicit
350 // exports from a static library are optimized out unless actually used by
351 // the shared library. See EffectsFactoryHalEntry.cpp.
createIEffectsFactoryImpl()352 extern "C" void* createIEffectsFactoryImpl() {
353     return new effect::EffectsFactoryHalAidl(getServiceInstance<IFactory>("default"));
354 }
355 
356 } // namespace android
357