1 /*
2  * Copyright 2019 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_NDEBUG 0
18 #define LOG_TAG "Codec2-ComponentStore@1.1"
19 #include <android-base/logging.h>
20 
21 #include <codec2/hidl/1.1/ComponentStore.h>
22 #include <codec2/hidl/1.1/InputSurface.h>
23 #include <codec2/hidl/1.1/types.h>
24 
25 #include <android-base/file.h>
26 #include <media/stagefright/bqhelper/GraphicBufferSource.h>
27 #include <utils/Errors.h>
28 
29 #include <C2PlatformSupport.h>
30 #include <util/C2InterfaceHelper.h>
31 
32 #include <chrono>
33 #include <ctime>
34 #include <iomanip>
35 #include <ostream>
36 #include <sstream>
37 
38 #ifndef __ANDROID_APEX__
39 #include <codec2/hidl/plugin/FilterPlugin.h>
40 #include <dlfcn.h>
41 #include <C2Config.h>
42 #include <DefaultFilterPlugin.h>
43 #include <FilterWrapper.h>
44 #endif
45 
46 namespace android {
47 namespace hardware {
48 namespace media {
49 namespace c2 {
50 namespace V1_1 {
51 namespace utils {
52 
53 using namespace ::android;
54 using ::android::GraphicBufferSource;
55 using namespace ::android::hardware::media::bufferpool::V2_0::implementation;
56 
57 namespace /* unnamed */ {
58 
59 struct StoreIntf : public ConfigurableC2Intf {
StoreIntfandroid::hardware::media::c2::V1_1::utils::__anona2458b470111::StoreIntf60     StoreIntf(const std::shared_ptr<C2ComponentStore>& store)
61           : ConfigurableC2Intf{store ? store->getName() : "", 0},
62             mStore{store} {
63     }
64 
configandroid::hardware::media::c2::V1_1::utils::__anona2458b470111::StoreIntf65     virtual c2_status_t config(
66             const std::vector<C2Param*> &params,
67             c2_blocking_t mayBlock,
68             std::vector<std::unique_ptr<C2SettingResult>> *const failures
69             ) override {
70         // Assume all params are blocking
71         // TODO: Filter for supported params
72         if (mayBlock == C2_DONT_BLOCK && params.size() != 0) {
73             return C2_BLOCKING;
74         }
75         return mStore->config_sm(params, failures);
76     }
77 
queryandroid::hardware::media::c2::V1_1::utils::__anona2458b470111::StoreIntf78     virtual c2_status_t query(
79             const std::vector<C2Param::Index> &indices,
80             c2_blocking_t mayBlock,
81             std::vector<std::unique_ptr<C2Param>> *const params) const override {
82         // Assume all params are blocking
83         // TODO: Filter for supported params
84         if (mayBlock == C2_DONT_BLOCK && indices.size() != 0) {
85             return C2_BLOCKING;
86         }
87         return mStore->query_sm({}, indices, params);
88     }
89 
querySupportedParamsandroid::hardware::media::c2::V1_1::utils::__anona2458b470111::StoreIntf90     virtual c2_status_t querySupportedParams(
91             std::vector<std::shared_ptr<C2ParamDescriptor>> *const params
92             ) const override {
93         return mStore->querySupportedParams_nb(params);
94     }
95 
querySupportedValuesandroid::hardware::media::c2::V1_1::utils::__anona2458b470111::StoreIntf96     virtual c2_status_t querySupportedValues(
97             std::vector<C2FieldSupportedValuesQuery> &fields,
98             c2_blocking_t mayBlock) const override {
99         // Assume all params are blocking
100         // TODO: Filter for supported params
101         if (mayBlock == C2_DONT_BLOCK && fields.size() != 0) {
102             return C2_BLOCKING;
103         }
104         return mStore->querySupportedValues_sm(fields);
105     }
106 
107 protected:
108     std::shared_ptr<C2ComponentStore> mStore;
109 };
110 
111 } // unnamed namespace
112 
113 struct ComponentStore::StoreParameterCache : public ParameterCache {
114     std::mutex mStoreMutex;
115     ComponentStore* mStore;
116 
StoreParameterCacheandroid::hardware::media::c2::V1_1::utils::ComponentStore::StoreParameterCache117     StoreParameterCache(ComponentStore* store): mStore{store} {
118     }
119 
validateandroid::hardware::media::c2::V1_1::utils::ComponentStore::StoreParameterCache120     virtual c2_status_t validate(
121             const std::vector<std::shared_ptr<C2ParamDescriptor>>& params
122             ) override {
123         std::scoped_lock _lock(mStoreMutex);
124         return mStore ? mStore->validateSupportedParams(params) : C2_NO_INIT;
125     }
126 
onStoreDestroyedandroid::hardware::media::c2::V1_1::utils::ComponentStore::StoreParameterCache127     void onStoreDestroyed() {
128         std::scoped_lock _lock(mStoreMutex);
129         mStore = nullptr;
130     }
131 };
132 
ComponentStore(const std::shared_ptr<C2ComponentStore> & store)133 ComponentStore::ComponentStore(const std::shared_ptr<C2ComponentStore>& store)
134       : mConfigurable{new CachedConfigurable(std::make_unique<StoreIntf>(store))},
135         mParameterCache{std::make_shared<StoreParameterCache>(this)},
136         mStore{store} {
137 
138     std::shared_ptr<C2ComponentStore> platformStore = android::GetCodec2PlatformComponentStore();
139     SetPreferredCodec2ComponentStore(store);
140 
141     // Retrieve struct descriptors
142     mParamReflectors.push_back(mStore->getParamReflector());
143 #ifndef __ANDROID_APEX__
144     std::shared_ptr<C2ParamReflector> paramReflector =
145         GetFilterWrapper()->getParamReflector();
146     if (paramReflector != nullptr) {
147         ALOGD("[%s] added param reflector from filter wrapper", mStore->getName().c_str());
148         mParamReflectors.push_back(paramReflector);
149     }
150 #endif
151 
152     // Retrieve supported parameters from store
153     using namespace std::placeholders;
154     mInit = mConfigurable->init(mParameterCache);
155 }
156 
~ComponentStore()157 ComponentStore::~ComponentStore() {
158     mParameterCache->onStoreDestroyed();
159 }
160 
status() const161 c2_status_t ComponentStore::status() const {
162     return mInit;
163 }
164 
validateSupportedParams(const std::vector<std::shared_ptr<C2ParamDescriptor>> & params)165 c2_status_t ComponentStore::validateSupportedParams(
166         const std::vector<std::shared_ptr<C2ParamDescriptor>>& params) {
167     c2_status_t res = C2_OK;
168 
169     for (const std::shared_ptr<C2ParamDescriptor> &desc : params) {
170         if (!desc) {
171             // All descriptors should be valid
172             res = res ? res : C2_BAD_VALUE;
173             continue;
174         }
175         C2Param::CoreIndex coreIndex = desc->index().coreIndex();
176         std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
177         auto it = mStructDescriptors.find(coreIndex);
178         if (it == mStructDescriptors.end()) {
179             std::shared_ptr<C2StructDescriptor> structDesc = describe(coreIndex);
180             if (!structDesc) {
181                 // All supported params must be described
182                 res = C2_BAD_INDEX;
183             }
184             mStructDescriptors.insert({ coreIndex, structDesc });
185         }
186     }
187     return res;
188 }
189 
getParameterCache() const190 std::shared_ptr<ParameterCache> ComponentStore::getParameterCache() const {
191     return mParameterCache;
192 }
193 
194 #ifndef __ANDROID_APEX__
195 // static
GetFilterWrapper()196 std::shared_ptr<FilterWrapper> ComponentStore::GetFilterWrapper() {
197     constexpr const char kPluginPath[] = "libc2filterplugin.so";
198     static std::shared_ptr<FilterWrapper> wrapper = FilterWrapper::Create(
199             std::make_unique<DefaultFilterPlugin>(kPluginPath));
200     return wrapper;
201 }
202 #endif
203 
tryCreateMultiAccessUnitInterface(const std::shared_ptr<C2ComponentInterface> & c2interface)204 std::shared_ptr<MultiAccessUnitInterface> ComponentStore::tryCreateMultiAccessUnitInterface(
205         const std::shared_ptr<C2ComponentInterface> &c2interface) {
206     std::shared_ptr<MultiAccessUnitInterface> multiAccessUnitIntf = nullptr;
207     if (c2interface == nullptr) {
208         return nullptr;
209     }
210     if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
211         c2_status_t err = C2_OK;
212         C2ComponentDomainSetting domain;
213         std::vector<std::unique_ptr<C2Param>> heapParams;
214         err = c2interface->query_vb({&domain}, {}, C2_MAY_BLOCK, &heapParams);
215         if (err == C2_OK && (domain.value == C2Component::DOMAIN_AUDIO)) {
216             std::vector<std::shared_ptr<C2ParamDescriptor>> params;
217             bool isComponentSupportsLargeAudioFrame = false;
218             c2interface->querySupportedParams_nb(&params);
219             for (const auto &paramDesc : params) {
220                 if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
221                     isComponentSupportsLargeAudioFrame = true;
222                     break;
223                 }
224             }
225 
226             if (!isComponentSupportsLargeAudioFrame) {
227                 multiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
228                         c2interface,
229                         std::static_pointer_cast<C2ReflectorHelper>(mParamReflectors[0]));
230             }
231         }
232     }
233     return multiAccessUnitIntf;
234 }
235 
236 // Methods from ::android::hardware::media::c2::V1_0::IComponentStore
createComponent(const hidl_string & name,const sp<IComponentListener> & listener,const sp<IClientManager> & pool,createComponent_cb _hidl_cb)237 Return<void> ComponentStore::createComponent(
238         const hidl_string& name,
239         const sp<IComponentListener>& listener,
240         const sp<IClientManager>& pool,
241         createComponent_cb _hidl_cb) {
242 
243     sp<Component> component;
244     std::shared_ptr<C2Component> c2component;
245     Status status = static_cast<Status>(
246             mStore->createComponent(name, &c2component));
247 
248     if (status == Status::OK) {
249 #ifndef __ANDROID_APEX__
250         c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
251 #endif
252         onInterfaceLoaded(c2component->intf());
253         component = new Component(c2component, listener, this, pool);
254         if (!component) {
255             status = Status::CORRUPTED;
256         } else {
257             reportComponentBirth(component.get());
258             if (component->status() != C2_OK) {
259                 status = static_cast<Status>(component->status());
260             } else {
261                 component->initListener(component);
262                 if (component->status() != C2_OK) {
263                     status = static_cast<Status>(component->status());
264                 }
265             }
266         }
267     }
268     _hidl_cb(status, component);
269     return Void();
270 }
271 
createInterface(const hidl_string & name,createInterface_cb _hidl_cb)272 Return<void> ComponentStore::createInterface(
273         const hidl_string& name,
274         createInterface_cb _hidl_cb) {
275     std::shared_ptr<C2ComponentInterface> c2interface;
276     c2_status_t res = mStore->createInterface(name, &c2interface);
277     sp<IComponentInterface> interface;
278     if (res == C2_OK) {
279 #ifndef __ANDROID_APEX__
280         c2interface = GetFilterWrapper()->maybeWrapInterface(c2interface);
281 #endif
282         onInterfaceLoaded(c2interface);
283         std::shared_ptr<MultiAccessUnitInterface> multiAccessUnitIntf =
284                 tryCreateMultiAccessUnitInterface(c2interface);
285         interface = new ComponentInterface(
286                 c2interface, multiAccessUnitIntf, mParameterCache);
287     }
288     _hidl_cb(static_cast<Status>(res), interface);
289     return Void();
290 }
291 
listComponents(listComponents_cb _hidl_cb)292 Return<void> ComponentStore::listComponents(listComponents_cb _hidl_cb) {
293     std::vector<std::shared_ptr<const C2Component::Traits>> c2traits =
294             mStore->listComponents();
295     hidl_vec<IComponentStore::ComponentTraits> traits(c2traits.size());
296     size_t ix = 0;
297     for (const std::shared_ptr<const C2Component::Traits> &c2trait : c2traits) {
298         if (c2trait) {
299             if (objcpy(&traits[ix], *c2trait)) {
300                 ++ix;
301             } else {
302                 break;
303             }
304         }
305     }
306     traits.resize(ix);
307     _hidl_cb(Status::OK, traits);
308     return Void();
309 }
310 
createInputSurface(createInputSurface_cb _hidl_cb)311 Return<void> ComponentStore::createInputSurface(createInputSurface_cb _hidl_cb) {
312     sp<GraphicBufferSource> source = new GraphicBufferSource();
313     if (source->initCheck() != OK) {
314         _hidl_cb(Status::CORRUPTED, nullptr);
315         return Void();
316     }
317     using namespace std::placeholders;
318     sp<InputSurface> inputSurface = new InputSurface(
319             mParameterCache,
320             std::make_shared<C2ReflectorHelper>(),
321             source->getHGraphicBufferProducer(),
322             source);
323     _hidl_cb(inputSurface ? Status::OK : Status::NO_MEMORY,
324              inputSurface);
325     return Void();
326 }
327 
onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> & intf)328 void ComponentStore::onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> &intf) {
329     // invalidate unsupported struct descriptors if a new interface is loaded as it may have
330     // exposed new descriptors
331     std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
332     if (!mLoadedInterfaces.count(intf->getName())) {
333         mUnsupportedStructDescriptors.clear();
334         mLoadedInterfaces.emplace(intf->getName());
335     }
336 }
337 
getStructDescriptors(const hidl_vec<uint32_t> & indices,getStructDescriptors_cb _hidl_cb)338 Return<void> ComponentStore::getStructDescriptors(
339         const hidl_vec<uint32_t>& indices,
340         getStructDescriptors_cb _hidl_cb) {
341     hidl_vec<StructDescriptor> descriptors(indices.size());
342     size_t dstIx = 0;
343     Status res = Status::OK;
344     for (size_t srcIx = 0; srcIx < indices.size(); ++srcIx) {
345         std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
346         const C2Param::CoreIndex coreIndex = C2Param::CoreIndex(indices[srcIx]).coreIndex();
347         const auto item = mStructDescriptors.find(coreIndex);
348         if (item == mStructDescriptors.end()) {
349             // not in the cache, and not known to be unsupported, query local reflector
350             if (!mUnsupportedStructDescriptors.count(coreIndex)) {
351                 std::shared_ptr<C2StructDescriptor> structDesc = describe(coreIndex);
352                 if (!structDesc) {
353                     mUnsupportedStructDescriptors.emplace(coreIndex);
354                 } else {
355                     mStructDescriptors.insert({ coreIndex, structDesc });
356                     if (objcpy(&descriptors[dstIx], *structDesc)) {
357                         ++dstIx;
358                         continue;
359                     }
360                     res = Status::CORRUPTED;
361                     break;
362                 }
363             }
364             res = Status::NOT_FOUND;
365         } else if (item->second) {
366             if (objcpy(&descriptors[dstIx], *item->second)) {
367                 ++dstIx;
368                 continue;
369             }
370             res = Status::CORRUPTED;
371             break;
372         } else {
373             res = Status::NO_MEMORY;
374             break;
375         }
376     }
377     descriptors.resize(dstIx);
378     _hidl_cb(res, descriptors);
379     return Void();
380 }
381 
getPoolClientManager()382 Return<sp<IClientManager>> ComponentStore::getPoolClientManager() {
383     return ClientManager::getInstance();
384 }
385 
copyBuffer(const Buffer & src,const Buffer & dst)386 Return<Status> ComponentStore::copyBuffer(const Buffer& src, const Buffer& dst) {
387     // TODO implement
388     (void)src;
389     (void)dst;
390     return Status::OMITTED;
391 }
392 
getConfigurable()393 Return<sp<IConfigurable>> ComponentStore::getConfigurable() {
394     return mConfigurable;
395 }
396 
397 // Methods from ::android::hardware::media::c2::V1_1::IComponentStore
createComponent_1_1(const hidl_string & name,const sp<IComponentListener> & listener,const sp<IClientManager> & pool,createComponent_1_1_cb _hidl_cb)398 Return<void> ComponentStore::createComponent_1_1(
399         const hidl_string& name,
400         const sp<IComponentListener>& listener,
401         const sp<IClientManager>& pool,
402         createComponent_1_1_cb _hidl_cb) {
403 
404     sp<Component> component;
405     std::shared_ptr<C2Component> c2component;
406     Status status = static_cast<Status>(
407             mStore->createComponent(name, &c2component));
408 
409     if (status == Status::OK) {
410 #ifndef __ANDROID_APEX__
411         c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
412 #endif
413         onInterfaceLoaded(c2component->intf());
414         component = new Component(c2component, listener, this, pool);
415         if (!component) {
416             status = Status::CORRUPTED;
417         } else {
418             reportComponentBirth(component.get());
419             if (component->status() != C2_OK) {
420                 status = static_cast<Status>(component->status());
421             } else {
422                 component->initListener(component);
423                 if (component->status() != C2_OK) {
424                     status = static_cast<Status>(component->status());
425                 }
426             }
427         }
428     }
429     _hidl_cb(status, component);
430     return Void();
431 }
432 
describe(const C2Param::CoreIndex & index)433 std::shared_ptr<C2StructDescriptor> ComponentStore::describe(const C2Param::CoreIndex &index) {
434     for (const std::shared_ptr<C2ParamReflector> &reflector : mParamReflectors) {
435         std::shared_ptr<C2StructDescriptor> desc = reflector->describe(index);
436         if (desc) {
437             return desc;
438         }
439     }
440     return nullptr;
441 }
442 
443 // Called from createComponent() after a successful creation of `component`.
reportComponentBirth(Component * component)444 void ComponentStore::reportComponentBirth(Component* component) {
445     ComponentStatus componentStatus;
446     componentStatus.c2Component = component->mComponent;
447     componentStatus.birthTime = std::chrono::system_clock::now();
448 
449     std::lock_guard<std::mutex> lock(mComponentRosterMutex);
450     mComponentRoster.emplace(component, componentStatus);
451 }
452 
453 // Called from within the destructor of `component`. No virtual function calls
454 // are made on `component` here.
reportComponentDeath(Component * component)455 void ComponentStore::reportComponentDeath(Component* component) {
456     std::lock_guard<std::mutex> lock(mComponentRosterMutex);
457     mComponentRoster.erase(component);
458 }
459 
460 // Dumps component traits.
dump(std::ostream & out,const std::shared_ptr<const C2Component::Traits> & comp)461 std::ostream& ComponentStore::dump(
462         std::ostream& out,
463         const std::shared_ptr<const C2Component::Traits>& comp) {
464 
465     constexpr const char indent[] = "    ";
466 
467     out << indent << "name: " << comp->name << std::endl;
468     out << indent << "domain: " << comp->domain << std::endl;
469     out << indent << "kind: " << comp->kind << std::endl;
470     out << indent << "rank: " << comp->rank << std::endl;
471     out << indent << "mediaType: " << comp->mediaType << std::endl;
472     out << indent << "aliases:";
473     for (const auto& alias : comp->aliases) {
474         out << ' ' << alias;
475     }
476     out << std::endl;
477 
478     return out;
479 }
480 
481 // Dumps component status.
dump(std::ostream & out,ComponentStatus & compStatus)482 std::ostream& ComponentStore::dump(
483         std::ostream& out,
484         ComponentStatus& compStatus) {
485 
486     constexpr const char indent[] = "    ";
487 
488     // Print birth time.
489     std::chrono::milliseconds ms =
490             std::chrono::duration_cast<std::chrono::milliseconds>(
491                 compStatus.birthTime.time_since_epoch());
492     std::time_t birthTime = std::chrono::system_clock::to_time_t(
493             compStatus.birthTime);
494     std::tm tm = *std::localtime(&birthTime);
495     out << indent << "Creation time: "
496         << std::put_time(&tm, "%Y-%m-%d %H:%M:%S")
497         << '.' << std::setfill('0') << std::setw(3) << ms.count() % 1000
498         << std::endl;
499 
500     // Print name and id.
501     std::shared_ptr<C2ComponentInterface> intf = compStatus.c2Component->intf();
502     if (!intf) {
503         out << indent << "Unknown component -- null interface" << std::endl;
504         return out;
505     }
506     out << indent << "Name: " << intf->getName() << std::endl;
507     out << indent << "Id: " << intf->getId() << std::endl;
508 
509     return out;
510 }
511 
512 // Dumps information when lshal is called.
debug(const hidl_handle & handle,const hidl_vec<hidl_string> &)513 Return<void> ComponentStore::debug(
514         const hidl_handle& handle,
515         const hidl_vec<hidl_string>& /* args */) {
516     LOG(INFO) << "debug -- dumping...";
517     const native_handle_t *h = handle.getNativeHandle();
518     if (!h || h->numFds != 1) {
519        LOG(ERROR) << "debug -- dumping failed -- "
520                "invalid file descriptor to dump to";
521        return Void();
522     }
523     std::ostringstream out;
524 
525     { // Populate "out".
526 
527         constexpr const char indent[] = "  ";
528 
529         // Show name.
530         out << "Beginning of dump -- C2ComponentStore: "
531                 << mStore->getName() << std::endl << std::endl;
532 
533         // Retrieve the list of supported components.
534         std::vector<std::shared_ptr<const C2Component::Traits>> traitsList =
535                 mStore->listComponents();
536 
537         // Dump the traits of supported components.
538         out << indent << "Supported components:" << std::endl << std::endl;
539         if (traitsList.size() == 0) {
540             out << indent << indent << "NONE" << std::endl << std::endl;
541         } else {
542             for (const auto& traits : traitsList) {
543                 dump(out, traits) << std::endl;
544             }
545         }
546 
547         // Dump active components.
548         {
549             out << indent << "Active components:" << std::endl << std::endl;
550             std::lock_guard<std::mutex> lock(mComponentRosterMutex);
551             if (mComponentRoster.size() == 0) {
552                 out << indent << indent << "NONE" << std::endl << std::endl;
553             } else {
554                 for (auto& pair : mComponentRoster) {
555                     dump(out, pair.second) << std::endl;
556                 }
557             }
558         }
559 
560         out << "End of dump -- C2ComponentStore: "
561                 << mStore->getName() << std::endl;
562     }
563 
564     if (!android::base::WriteStringToFd(out.str(), h->data[0])) {
565         PLOG(WARNING) << "debug -- dumping failed -- write()";
566     } else {
567         LOG(INFO) << "debug -- dumping succeeded";
568     }
569     return Void();
570 }
571 
572 } // namespace utils
573 } // namespace V1_1
574 } // namespace c2
575 } // namespace media
576 } // namespace hardware
577 } // namespace android
578