1 /*
2 * Copyright 2018 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"
19 #include <android-base/logging.h>
20
21 #include <codec2/hidl/1.0/ComponentStore.h>
22 #include <codec2/hidl/1.0/InputSurface.h>
23 #include <codec2/hidl/1.0/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_0 {
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_0::utils::__anone6957ddc0111::StoreIntf60 StoreIntf(const std::shared_ptr<C2ComponentStore>& store)
61 : ConfigurableC2Intf{store ? store->getName() : "", 0},
62 mStore{store} {
63 }
64
configandroid::hardware::media::c2::V1_0::utils::__anone6957ddc0111::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_0::utils::__anone6957ddc0111::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_0::utils::__anone6957ddc0111::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_0::utils::__anone6957ddc0111::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_0::utils::ComponentStore::StoreParameterCache117 StoreParameterCache(ComponentStore* store): mStore{store} {
118 }
119
validateandroid::hardware::media::c2::V1_0::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_0::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
293 sp<IComponentInterface> interface;
294 if (res == C2_OK) {
295 #ifndef __ANDROID_APEX__
296 c2interface = GetFilterWrapper()->maybeWrapInterface(c2interface);
297 #endif
298 onInterfaceLoaded(c2interface);
299 std::shared_ptr<MultiAccessUnitInterface> multiAccessUnitIntf =
300 tryCreateMultiAccessUnitInterface(c2interface);
301 interface = new ComponentInterface(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
describe(const C2Param::CoreIndex & index)412 std::shared_ptr<C2StructDescriptor> ComponentStore::describe(const C2Param::CoreIndex &index) {
413 for (const std::shared_ptr<C2ParamReflector> &reflector : mParamReflectors) {
414 std::shared_ptr<C2StructDescriptor> desc = reflector->describe(index);
415 if (desc) {
416 return desc;
417 }
418 }
419 return nullptr;
420 }
421
422 // Called from createComponent() after a successful creation of `component`.
reportComponentBirth(Component * component)423 void ComponentStore::reportComponentBirth(Component* component) {
424 ComponentStatus componentStatus;
425 componentStatus.c2Component = component->mComponent;
426 componentStatus.birthTime = std::chrono::system_clock::now();
427
428 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
429 mComponentRoster.emplace(component, componentStatus);
430 }
431
432 // Called from within the destructor of `component`. No virtual function calls
433 // are made on `component` here.
reportComponentDeath(Component * component)434 void ComponentStore::reportComponentDeath(Component* component) {
435 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
436 mComponentRoster.erase(component);
437 }
438
439 // Dumps component traits.
dump(std::ostream & out,const std::shared_ptr<const C2Component::Traits> & comp)440 std::ostream& ComponentStore::dump(
441 std::ostream& out,
442 const std::shared_ptr<const C2Component::Traits>& comp) {
443
444 constexpr const char indent[] = " ";
445
446 out << indent << "name: " << comp->name << std::endl;
447 out << indent << "domain: " << comp->domain << std::endl;
448 out << indent << "kind: " << comp->kind << std::endl;
449 out << indent << "rank: " << comp->rank << std::endl;
450 out << indent << "mediaType: " << comp->mediaType << std::endl;
451 out << indent << "aliases:";
452 for (const auto& alias : comp->aliases) {
453 out << ' ' << alias;
454 }
455 out << std::endl;
456
457 return out;
458 }
459
460 // Dumps component status.
dump(std::ostream & out,ComponentStatus & compStatus)461 std::ostream& ComponentStore::dump(
462 std::ostream& out,
463 ComponentStatus& compStatus) {
464
465 constexpr const char indent[] = " ";
466
467 // Print birth time.
468 std::chrono::milliseconds ms =
469 std::chrono::duration_cast<std::chrono::milliseconds>(
470 compStatus.birthTime.time_since_epoch());
471 std::time_t birthTime = std::chrono::system_clock::to_time_t(
472 compStatus.birthTime);
473 std::tm tm = *std::localtime(&birthTime);
474 out << indent << "Creation time: "
475 << std::put_time(&tm, "%Y-%m-%d %H:%M:%S")
476 << '.' << std::setfill('0') << std::setw(3) << ms.count() % 1000
477 << std::endl;
478
479 // Print name and id.
480 std::shared_ptr<C2ComponentInterface> intf = compStatus.c2Component->intf();
481 if (!intf) {
482 out << indent << "Unknown component -- null interface" << std::endl;
483 return out;
484 }
485 out << indent << "Name: " << intf->getName() << std::endl;
486 out << indent << "Id: " << intf->getId() << std::endl;
487
488 return out;
489 }
490
491 // Dumps information when lshal is called.
debug(const hidl_handle & handle,const hidl_vec<hidl_string> &)492 Return<void> ComponentStore::debug(
493 const hidl_handle& handle,
494 const hidl_vec<hidl_string>& /* args */) {
495 LOG(INFO) << "debug -- dumping...";
496 const native_handle_t *h = handle.getNativeHandle();
497 if (!h || h->numFds != 1) {
498 LOG(ERROR) << "debug -- dumping failed -- "
499 "invalid file descriptor to dump to";
500 return Void();
501 }
502 std::ostringstream out;
503
504 { // Populate "out".
505
506 constexpr const char indent[] = " ";
507
508 // Show name.
509 out << "Beginning of dump -- C2ComponentStore: "
510 << mStore->getName() << std::endl << std::endl;
511
512 // Retrieve the list of supported components.
513 std::vector<std::shared_ptr<const C2Component::Traits>> traitsList =
514 mStore->listComponents();
515
516 // Dump the traits of supported components.
517 out << indent << "Supported components:" << std::endl << std::endl;
518 if (traitsList.size() == 0) {
519 out << indent << indent << "NONE" << std::endl << std::endl;
520 } else {
521 for (const auto& traits : traitsList) {
522 dump(out, traits) << std::endl;
523 }
524 }
525
526 // Dump active components.
527 {
528 out << indent << "Active components:" << std::endl << std::endl;
529 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
530 if (mComponentRoster.size() == 0) {
531 out << indent << indent << "NONE" << std::endl << std::endl;
532 } else {
533 for (auto& pair : mComponentRoster) {
534 dump(out, pair.second) << std::endl;
535 }
536 }
537 }
538
539 out << "End of dump -- C2ComponentStore: "
540 << mStore->getName() << std::endl;
541 }
542
543 if (!android::base::WriteStringToFd(out.str(), h->data[0])) {
544 PLOG(WARNING) << "debug -- dumping failed -- write()";
545 } else {
546 LOG(INFO) << "debug -- dumping succeeded";
547 }
548 return Void();
549 }
550
551 } // namespace utils
552 } // namespace V1_0
553 } // namespace c2
554 } // namespace media
555 } // namespace hardware
556 } // namespace android
557
558