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::__anon15b830fd0111::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::__anon15b830fd0111::StoreIntf65 virtual c2_status_t config(
66 const std::vector<C2Param*> ¶ms,
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::__anon15b830fd0111::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::__anon15b830fd0111::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::__anon15b830fd0111::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 // MultiAccessUnit reflector helper is allocated once per store.
153 // All components in this store can reuse this reflector helper.
154 if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
155 std::shared_ptr<C2ReflectorHelper> helper = std::make_shared<C2ReflectorHelper>();
156 mParamReflectors.push_back(helper);
157 mMultiAccessUnitReflector = helper;
158 }
159
160 // Retrieve supported parameters from store
161 using namespace std::placeholders;
162 mInit = mConfigurable->init(mParameterCache);
163 }
164
~ComponentStore()165 ComponentStore::~ComponentStore() {
166 mParameterCache->onStoreDestroyed();
167 }
168
status() const169 c2_status_t ComponentStore::status() const {
170 return mInit;
171 }
172
validateSupportedParams(const std::vector<std::shared_ptr<C2ParamDescriptor>> & params)173 c2_status_t ComponentStore::validateSupportedParams(
174 const std::vector<std::shared_ptr<C2ParamDescriptor>>& params) {
175 c2_status_t res = C2_OK;
176
177 for (const std::shared_ptr<C2ParamDescriptor> &desc : params) {
178 if (!desc) {
179 // All descriptors should be valid
180 res = res ? res : C2_BAD_VALUE;
181 continue;
182 }
183 C2Param::CoreIndex coreIndex = desc->index().coreIndex();
184 std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
185 auto it = mStructDescriptors.find(coreIndex);
186 if (it == mStructDescriptors.end()) {
187 std::shared_ptr<C2StructDescriptor> structDesc = describe(coreIndex);
188 if (!structDesc) {
189 // All supported params must be described
190 res = C2_BAD_INDEX;
191 }
192 mStructDescriptors.insert({ coreIndex, structDesc });
193 }
194 }
195 return res;
196 }
197
getParameterCache() const198 std::shared_ptr<ParameterCache> ComponentStore::getParameterCache() const {
199 return mParameterCache;
200 }
201
202 #ifndef __ANDROID_APEX__
203 // static
GetFilterWrapper()204 std::shared_ptr<FilterWrapper> ComponentStore::GetFilterWrapper() {
205 constexpr const char kPluginPath[] = "libc2filterplugin.so";
206 static std::shared_ptr<FilterWrapper> wrapper = FilterWrapper::Create(
207 std::make_unique<DefaultFilterPlugin>(kPluginPath));
208 return wrapper;
209 }
210 #endif
211
tryCreateMultiAccessUnitInterface(const std::shared_ptr<C2ComponentInterface> & c2interface)212 std::shared_ptr<MultiAccessUnitInterface> ComponentStore::tryCreateMultiAccessUnitInterface(
213 const std::shared_ptr<C2ComponentInterface> &c2interface) {
214 std::shared_ptr<MultiAccessUnitInterface> multiAccessUnitIntf = nullptr;
215 if (c2interface == nullptr) {
216 return nullptr;
217 }
218 // Framework support for Large audio frame feature depends on:
219 // 1. All feature flags enabled on platform
220 // 2. The capability of the implementation to use the same input buffer
221 // for different C2Work (C2Config::api_feature_t::API_SAME_INPUT_BUFFER)
222 // 3. Implementation does not inherently support C2LargeFrame::output::PARAM_TYPE param.
223 if (MultiAccessUnitHelper::isEnabledOnPlatform()) {
224 c2_status_t err = C2_OK;
225 C2ComponentDomainSetting domain;
226 std::vector<std::unique_ptr<C2Param>> heapParams;
227 C2ApiFeaturesSetting features = (C2Config::api_feature_t)0;
228 err = c2interface->query_vb({&domain, &features}, {}, C2_MAY_BLOCK, &heapParams);
229 if (err == C2_OK
230 && (domain.value == C2Component::DOMAIN_AUDIO)
231 && ((features.value & C2Config::api_feature_t::API_SAME_INPUT_BUFFER) != 0)) {
232 std::vector<std::shared_ptr<C2ParamDescriptor>> params;
233 bool isComponentSupportsLargeAudioFrame = false;
234 c2interface->querySupportedParams_nb(¶ms);
235 for (const auto ¶mDesc : params) {
236 if (paramDesc->name().compare(C2_PARAMKEY_OUTPUT_LARGE_FRAME) == 0) {
237 isComponentSupportsLargeAudioFrame = true;
238 break;
239 }
240 }
241 if (!isComponentSupportsLargeAudioFrame) {
242 multiAccessUnitIntf = std::make_shared<MultiAccessUnitInterface>(
243 c2interface,
244 mMultiAccessUnitReflector);
245 }
246 }
247 }
248 return multiAccessUnitIntf;
249 }
250
251 // 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)252 Return<void> ComponentStore::createComponent(
253 const hidl_string& name,
254 const sp<IComponentListener>& listener,
255 const sp<IClientManager>& pool,
256 createComponent_cb _hidl_cb) {
257
258 sp<Component> component;
259 std::shared_ptr<C2Component> c2component;
260 Status status = static_cast<Status>(
261 mStore->createComponent(name, &c2component));
262
263 if (status == Status::OK) {
264 #ifndef __ANDROID_APEX__
265 c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
266 #endif
267 onInterfaceLoaded(c2component->intf());
268 component = new Component(c2component, listener, this, pool);
269 if (!component) {
270 status = Status::CORRUPTED;
271 } else {
272 reportComponentBirth(component.get());
273 if (component->status() != C2_OK) {
274 status = static_cast<Status>(component->status());
275 } else {
276 component->initListener(component);
277 if (component->status() != C2_OK) {
278 status = static_cast<Status>(component->status());
279 }
280 }
281 }
282 }
283 _hidl_cb(status, component);
284 return Void();
285 }
286
createInterface(const hidl_string & name,createInterface_cb _hidl_cb)287 Return<void> ComponentStore::createInterface(
288 const hidl_string& name,
289 createInterface_cb _hidl_cb) {
290 std::shared_ptr<C2ComponentInterface> c2interface;
291 c2_status_t res = mStore->createInterface(name, &c2interface);
292 sp<IComponentInterface> interface;
293 if (res == C2_OK) {
294 #ifndef __ANDROID_APEX__
295 c2interface = GetFilterWrapper()->maybeWrapInterface(c2interface);
296 #endif
297 onInterfaceLoaded(c2interface);
298 std::shared_ptr<MultiAccessUnitInterface> multiAccessUnitIntf =
299 tryCreateMultiAccessUnitInterface(c2interface);
300 interface = new ComponentInterface(
301 c2interface, multiAccessUnitIntf, mParameterCache);
302 }
303 _hidl_cb(static_cast<Status>(res), interface);
304 return Void();
305 }
306
listComponents(listComponents_cb _hidl_cb)307 Return<void> ComponentStore::listComponents(listComponents_cb _hidl_cb) {
308 std::vector<std::shared_ptr<const C2Component::Traits>> c2traits =
309 mStore->listComponents();
310 hidl_vec<IComponentStore::ComponentTraits> traits(c2traits.size());
311 size_t ix = 0;
312 for (const std::shared_ptr<const C2Component::Traits> &c2trait : c2traits) {
313 if (c2trait) {
314 if (objcpy(&traits[ix], *c2trait)) {
315 ++ix;
316 } else {
317 break;
318 }
319 }
320 }
321 traits.resize(ix);
322 _hidl_cb(Status::OK, traits);
323 return Void();
324 }
325
createInputSurface(createInputSurface_cb _hidl_cb)326 Return<void> ComponentStore::createInputSurface(createInputSurface_cb _hidl_cb) {
327 sp<GraphicBufferSource> source = new GraphicBufferSource();
328 if (source->initCheck() != OK) {
329 _hidl_cb(Status::CORRUPTED, nullptr);
330 return Void();
331 }
332 using namespace std::placeholders;
333 sp<InputSurface> inputSurface = new InputSurface(
334 mParameterCache,
335 std::make_shared<C2ReflectorHelper>(),
336 source->getHGraphicBufferProducer(),
337 source);
338 _hidl_cb(inputSurface ? Status::OK : Status::NO_MEMORY,
339 inputSurface);
340 return Void();
341 }
342
onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> & intf)343 void ComponentStore::onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> &intf) {
344 // invalidate unsupported struct descriptors if a new interface is loaded as it may have
345 // exposed new descriptors
346 std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
347 if (!mLoadedInterfaces.count(intf->getName())) {
348 mUnsupportedStructDescriptors.clear();
349 mLoadedInterfaces.emplace(intf->getName());
350 }
351 }
352
getStructDescriptors(const hidl_vec<uint32_t> & indices,getStructDescriptors_cb _hidl_cb)353 Return<void> ComponentStore::getStructDescriptors(
354 const hidl_vec<uint32_t>& indices,
355 getStructDescriptors_cb _hidl_cb) {
356 hidl_vec<StructDescriptor> descriptors(indices.size());
357 size_t dstIx = 0;
358 Status res = Status::OK;
359 for (size_t srcIx = 0; srcIx < indices.size(); ++srcIx) {
360 std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
361 const C2Param::CoreIndex coreIndex = C2Param::CoreIndex(indices[srcIx]).coreIndex();
362 const auto item = mStructDescriptors.find(coreIndex);
363 if (item == mStructDescriptors.end()) {
364 // not in the cache, and not known to be unsupported, query local reflector
365 if (!mUnsupportedStructDescriptors.count(coreIndex)) {
366 std::shared_ptr<C2StructDescriptor> structDesc = describe(coreIndex);
367 if (!structDesc) {
368 mUnsupportedStructDescriptors.emplace(coreIndex);
369 } else {
370 mStructDescriptors.insert({ coreIndex, structDesc });
371 if (objcpy(&descriptors[dstIx], *structDesc)) {
372 ++dstIx;
373 continue;
374 }
375 res = Status::CORRUPTED;
376 break;
377 }
378 }
379 res = Status::NOT_FOUND;
380 } else if (item->second) {
381 if (objcpy(&descriptors[dstIx], *item->second)) {
382 ++dstIx;
383 continue;
384 }
385 res = Status::CORRUPTED;
386 break;
387 } else {
388 res = Status::NO_MEMORY;
389 break;
390 }
391 }
392 descriptors.resize(dstIx);
393 _hidl_cb(res, descriptors);
394 return Void();
395 }
396
getPoolClientManager()397 Return<sp<IClientManager>> ComponentStore::getPoolClientManager() {
398 return ClientManager::getInstance();
399 }
400
copyBuffer(const Buffer & src,const Buffer & dst)401 Return<Status> ComponentStore::copyBuffer(const Buffer& src, const Buffer& dst) {
402 // TODO implement
403 (void)src;
404 (void)dst;
405 return Status::OMITTED;
406 }
407
getConfigurable()408 Return<sp<IConfigurable>> ComponentStore::getConfigurable() {
409 return mConfigurable;
410 }
411
412 // 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)413 Return<void> ComponentStore::createComponent_1_1(
414 const hidl_string& name,
415 const sp<IComponentListener>& listener,
416 const sp<IClientManager>& pool,
417 createComponent_1_1_cb _hidl_cb) {
418
419 sp<Component> component;
420 std::shared_ptr<C2Component> c2component;
421 Status status = static_cast<Status>(
422 mStore->createComponent(name, &c2component));
423
424 if (status == Status::OK) {
425 #ifndef __ANDROID_APEX__
426 c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
427 #endif
428 onInterfaceLoaded(c2component->intf());
429 component = new Component(c2component, listener, this, pool);
430 if (!component) {
431 status = Status::CORRUPTED;
432 } else {
433 reportComponentBirth(component.get());
434 if (component->status() != C2_OK) {
435 status = static_cast<Status>(component->status());
436 } else {
437 component->initListener(component);
438 if (component->status() != C2_OK) {
439 status = static_cast<Status>(component->status());
440 }
441 }
442 }
443 }
444 _hidl_cb(status, component);
445 return Void();
446 }
447
describe(const C2Param::CoreIndex & index)448 std::shared_ptr<C2StructDescriptor> ComponentStore::describe(const C2Param::CoreIndex &index) {
449 for (const std::shared_ptr<C2ParamReflector> &reflector : mParamReflectors) {
450 std::shared_ptr<C2StructDescriptor> desc = reflector->describe(index);
451 if (desc) {
452 return desc;
453 }
454 }
455 return nullptr;
456 }
457
458 // Called from createComponent() after a successful creation of `component`.
reportComponentBirth(Component * component)459 void ComponentStore::reportComponentBirth(Component* component) {
460 ComponentStatus componentStatus;
461 componentStatus.c2Component = component->mComponent;
462 componentStatus.birthTime = std::chrono::system_clock::now();
463
464 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
465 mComponentRoster.emplace(component, componentStatus);
466 }
467
468 // Called from within the destructor of `component`. No virtual function calls
469 // are made on `component` here.
reportComponentDeath(Component * component)470 void ComponentStore::reportComponentDeath(Component* component) {
471 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
472 mComponentRoster.erase(component);
473 }
474
475 // Dumps component traits.
dump(std::ostream & out,const std::shared_ptr<const C2Component::Traits> & comp)476 std::ostream& ComponentStore::dump(
477 std::ostream& out,
478 const std::shared_ptr<const C2Component::Traits>& comp) {
479
480 constexpr const char indent[] = " ";
481
482 out << indent << "name: " << comp->name << std::endl;
483 out << indent << "domain: " << comp->domain << std::endl;
484 out << indent << "kind: " << comp->kind << std::endl;
485 out << indent << "rank: " << comp->rank << std::endl;
486 out << indent << "mediaType: " << comp->mediaType << std::endl;
487 out << indent << "aliases:";
488 for (const auto& alias : comp->aliases) {
489 out << ' ' << alias;
490 }
491 out << std::endl;
492
493 return out;
494 }
495
496 // Dumps component status.
dump(std::ostream & out,ComponentStatus & compStatus)497 std::ostream& ComponentStore::dump(
498 std::ostream& out,
499 ComponentStatus& compStatus) {
500
501 constexpr const char indent[] = " ";
502
503 // Print birth time.
504 std::chrono::milliseconds ms =
505 std::chrono::duration_cast<std::chrono::milliseconds>(
506 compStatus.birthTime.time_since_epoch());
507 std::time_t birthTime = std::chrono::system_clock::to_time_t(
508 compStatus.birthTime);
509 std::tm tm = *std::localtime(&birthTime);
510 out << indent << "Creation time: "
511 << std::put_time(&tm, "%Y-%m-%d %H:%M:%S")
512 << '.' << std::setfill('0') << std::setw(3) << ms.count() % 1000
513 << std::endl;
514
515 // Print name and id.
516 std::shared_ptr<C2ComponentInterface> intf = compStatus.c2Component->intf();
517 if (!intf) {
518 out << indent << "Unknown component -- null interface" << std::endl;
519 return out;
520 }
521 out << indent << "Name: " << intf->getName() << std::endl;
522 out << indent << "Id: " << intf->getId() << std::endl;
523
524 return out;
525 }
526
527 // Dumps information when lshal is called.
debug(const hidl_handle & handle,const hidl_vec<hidl_string> &)528 Return<void> ComponentStore::debug(
529 const hidl_handle& handle,
530 const hidl_vec<hidl_string>& /* args */) {
531 LOG(INFO) << "debug -- dumping...";
532 const native_handle_t *h = handle.getNativeHandle();
533 if (!h || h->numFds != 1) {
534 LOG(ERROR) << "debug -- dumping failed -- "
535 "invalid file descriptor to dump to";
536 return Void();
537 }
538 std::ostringstream out;
539
540 { // Populate "out".
541
542 constexpr const char indent[] = " ";
543
544 // Show name.
545 out << "Beginning of dump -- C2ComponentStore: "
546 << mStore->getName() << std::endl << std::endl;
547
548 // Retrieve the list of supported components.
549 std::vector<std::shared_ptr<const C2Component::Traits>> traitsList =
550 mStore->listComponents();
551
552 // Dump the traits of supported components.
553 out << indent << "Supported components:" << std::endl << std::endl;
554 if (traitsList.size() == 0) {
555 out << indent << indent << "NONE" << std::endl << std::endl;
556 } else {
557 for (const auto& traits : traitsList) {
558 dump(out, traits) << std::endl;
559 }
560 }
561
562 // Dump active components.
563 {
564 out << indent << "Active components:" << std::endl << std::endl;
565 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
566 if (mComponentRoster.size() == 0) {
567 out << indent << indent << "NONE" << std::endl << std::endl;
568 } else {
569 for (auto& pair : mComponentRoster) {
570 dump(out, pair.second) << std::endl;
571 }
572 }
573 }
574
575 out << "End of dump -- C2ComponentStore: "
576 << mStore->getName() << std::endl;
577 }
578
579 if (!android::base::WriteStringToFd(out.str(), h->data[0])) {
580 PLOG(WARNING) << "debug -- dumping failed -- write()";
581 } else {
582 LOG(INFO) << "debug -- dumping succeeded";
583 }
584 return Void();
585 }
586
587 } // namespace utils
588 } // namespace V1_1
589 } // namespace c2
590 } // namespace media
591 } // namespace hardware
592 } // namespace android
593