blob: 0b674810fc2a1e56ec1fe4820618635504ece04d [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 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_TAG "C2Store"
18#define LOG_NDEBUG 0
19#include <utils/Log.h>
20
21#include <C2AllocatorGralloc.h>
22#include <C2AllocatorIon.h>
23#include <C2BufferPriv.h>
24#include <C2BqBufferPriv.h>
25#include <C2Component.h>
26#include <C2Config.h>
27#include <C2PlatformStorePluginLoader.h>
28#include <C2PlatformSupport.h>
29#include <util/C2InterfaceHelper.h>
30
31#include <dlfcn.h>
32#include <unistd.h> // getpagesize
33
34#include <map>
35#include <memory>
36#include <mutex>
37
38namespace android {
39
40/**
41 * Returns the preferred component store in this process to access its interface.
42 */
43std::shared_ptr<C2ComponentStore> GetPreferredCodec2ComponentStore();
44
45/**
46 * The platform allocator store provides basic allocator-types for the framework based on ion and
47 * gralloc. Allocators are not meant to be updatable.
48 *
49 * \todo Provide allocator based on ashmem
50 * \todo Move ion allocation into its HIDL or provide some mapping from memory usage to ion flags
51 * \todo Make this allocator store extendable
52 */
53class C2PlatformAllocatorStoreImpl : public C2PlatformAllocatorStore {
54public:
55 C2PlatformAllocatorStoreImpl();
56
57 virtual c2_status_t fetchAllocator(
58 id_t id, std::shared_ptr<C2Allocator> *const allocator) override;
59
60 virtual std::vector<std::shared_ptr<const C2Allocator::Traits>> listAllocators_nb()
61 const override {
62 return std::vector<std::shared_ptr<const C2Allocator::Traits>>(); /// \todo
63 }
64
65 virtual C2String getName() const override {
66 return "android.allocator-store";
67 }
68
69 void setComponentStore(std::shared_ptr<C2ComponentStore> store);
70
71 ~C2PlatformAllocatorStoreImpl() override = default;
72
73private:
74 /// returns a shared-singleton ion allocator
75 std::shared_ptr<C2Allocator> fetchIonAllocator();
76
77 /// returns a shared-singleton gralloc allocator
78 std::shared_ptr<C2Allocator> fetchGrallocAllocator();
79
80 /// returns a shared-singleton bufferqueue supporting gralloc allocator
81 std::shared_ptr<C2Allocator> fetchBufferQueueAllocator();
82
83 /// component store to use
84 std::mutex _mComponentStoreSetLock; // protects the entire updating _mComponentStore and its
85 // dependencies
86 std::mutex _mComponentStoreReadLock; // must protect only read/write of _mComponentStore
87 std::shared_ptr<C2ComponentStore> _mComponentStore;
88};
89
90C2PlatformAllocatorStoreImpl::C2PlatformAllocatorStoreImpl() {
91}
92
93c2_status_t C2PlatformAllocatorStoreImpl::fetchAllocator(
94 id_t id, std::shared_ptr<C2Allocator> *const allocator) {
95 allocator->reset();
96 switch (id) {
97 // TODO: should we implement a generic registry for all, and use that?
98 case C2PlatformAllocatorStore::ION:
99 case C2AllocatorStore::DEFAULT_LINEAR:
100 *allocator = fetchIonAllocator();
101 break;
102
103 case C2PlatformAllocatorStore::GRALLOC:
104 case C2AllocatorStore::DEFAULT_GRAPHIC:
105 *allocator = fetchGrallocAllocator();
106 break;
107
108 case C2PlatformAllocatorStore::BUFFERQUEUE:
109 *allocator = fetchBufferQueueAllocator();
110 break;
111
112 default:
113 // Try to create allocator from platform store plugins.
114 c2_status_t res =
115 C2PlatformStorePluginLoader::GetInstance()->createAllocator(id, allocator);
116 if (res != C2_OK) {
117 return res;
118 }
119 break;
120 }
121 if (*allocator == nullptr) {
122 return C2_NO_MEMORY;
123 }
124 return C2_OK;
125}
126
127namespace {
128
129std::mutex gIonAllocatorMutex;
130std::weak_ptr<C2AllocatorIon> gIonAllocator;
131
132void UseComponentStoreForIonAllocator(
133 const std::shared_ptr<C2AllocatorIon> allocator,
134 std::shared_ptr<C2ComponentStore> store) {
135 C2AllocatorIon::UsageMapperFn mapper;
136 uint64_t minUsage = 0;
137 uint64_t maxUsage = C2MemoryUsage(C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE).expected;
138 size_t blockSize = getpagesize();
139
140 // query min and max usage as well as block size via supported values
141 C2StoreIonUsageInfo usageInfo;
142 std::vector<C2FieldSupportedValuesQuery> query = {
143 C2FieldSupportedValuesQuery::Possible(C2ParamField::Make(usageInfo, usageInfo.usage)),
144 C2FieldSupportedValuesQuery::Possible(C2ParamField::Make(usageInfo, usageInfo.capacity)),
145 };
146 c2_status_t res = store->querySupportedValues_sm(query);
147 if (res == C2_OK) {
148 if (query[0].status == C2_OK) {
149 const C2FieldSupportedValues &fsv = query[0].values;
150 if (fsv.type == C2FieldSupportedValues::FLAGS && !fsv.values.empty()) {
151 minUsage = fsv.values[0].u64;
152 maxUsage = 0;
153 for (C2Value::Primitive v : fsv.values) {
154 maxUsage |= v.u64;
155 }
156 }
157 }
158 if (query[1].status == C2_OK) {
159 const C2FieldSupportedValues &fsv = query[1].values;
160 if (fsv.type == C2FieldSupportedValues::RANGE && fsv.range.step.u32 > 0) {
161 blockSize = fsv.range.step.u32;
162 }
163 }
164
165 mapper = [store](C2MemoryUsage usage, size_t capacity,
166 size_t *align, unsigned *heapMask, unsigned *flags) -> c2_status_t {
167 if (capacity > UINT32_MAX) {
168 return C2_BAD_VALUE;
169 }
170 C2StoreIonUsageInfo usageInfo = { usage.expected, capacity };
171 std::vector<std::unique_ptr<C2SettingResult>> failures; // TODO: remove
172 c2_status_t res = store->config_sm({&usageInfo}, &failures);
173 if (res == C2_OK) {
174 *align = usageInfo.minAlignment;
175 *heapMask = usageInfo.heapMask;
176 *flags = usageInfo.allocFlags;
177 }
178 return res;
179 };
180 }
181
182 allocator->setUsageMapper(mapper, minUsage, maxUsage, blockSize);
183}
184
185}
186
187void C2PlatformAllocatorStoreImpl::setComponentStore(std::shared_ptr<C2ComponentStore> store) {
188 // technically this set lock is not needed, but is here for safety in case we add more
189 // getter orders
190 std::lock_guard<std::mutex> lock(_mComponentStoreSetLock);
191 {
192 std::lock_guard<std::mutex> lock(_mComponentStoreReadLock);
193 _mComponentStore = store;
194 }
195 std::shared_ptr<C2AllocatorIon> allocator;
196 {
197 std::lock_guard<std::mutex> lock(gIonAllocatorMutex);
198 allocator = gIonAllocator.lock();
199 }
200 if (allocator) {
201 UseComponentStoreForIonAllocator(allocator, store);
202 }
203}
204
205std::shared_ptr<C2Allocator> C2PlatformAllocatorStoreImpl::fetchIonAllocator() {
206 std::lock_guard<std::mutex> lock(gIonAllocatorMutex);
207 std::shared_ptr<C2AllocatorIon> allocator = gIonAllocator.lock();
208 if (allocator == nullptr) {
209 std::shared_ptr<C2ComponentStore> componentStore;
210 {
211 std::lock_guard<std::mutex> lock(_mComponentStoreReadLock);
212 componentStore = _mComponentStore;
213 }
214 allocator = std::make_shared<C2AllocatorIon>(C2PlatformAllocatorStore::ION);
215 UseComponentStoreForIonAllocator(allocator, componentStore);
216 gIonAllocator = allocator;
217 }
218 return allocator;
219}
220
221std::shared_ptr<C2Allocator> C2PlatformAllocatorStoreImpl::fetchGrallocAllocator() {
222 static std::mutex mutex;
223 static std::weak_ptr<C2Allocator> grallocAllocator;
224 std::lock_guard<std::mutex> lock(mutex);
225 std::shared_ptr<C2Allocator> allocator = grallocAllocator.lock();
226 if (allocator == nullptr) {
227 allocator = std::make_shared<C2AllocatorGralloc>(C2PlatformAllocatorStore::GRALLOC);
228 grallocAllocator = allocator;
229 }
230 return allocator;
231}
232
233std::shared_ptr<C2Allocator> C2PlatformAllocatorStoreImpl::fetchBufferQueueAllocator() {
234 static std::mutex mutex;
235 static std::weak_ptr<C2Allocator> grallocAllocator;
236 std::lock_guard<std::mutex> lock(mutex);
237 std::shared_ptr<C2Allocator> allocator = grallocAllocator.lock();
238 if (allocator == nullptr) {
239 allocator = std::make_shared<C2AllocatorGralloc>(
240 C2PlatformAllocatorStore::BUFFERQUEUE, true);
241 grallocAllocator = allocator;
242 }
243 return allocator;
244}
245
246namespace {
247 std::mutex gPreferredComponentStoreMutex;
248 std::shared_ptr<C2ComponentStore> gPreferredComponentStore;
249
250 std::mutex gPlatformAllocatorStoreMutex;
251 std::weak_ptr<C2PlatformAllocatorStoreImpl> gPlatformAllocatorStore;
252}
253
254std::shared_ptr<C2AllocatorStore> GetCodec2PlatformAllocatorStore() {
255 std::lock_guard<std::mutex> lock(gPlatformAllocatorStoreMutex);
256 std::shared_ptr<C2PlatformAllocatorStoreImpl> store = gPlatformAllocatorStore.lock();
257 if (store == nullptr) {
258 store = std::make_shared<C2PlatformAllocatorStoreImpl>();
259 store->setComponentStore(GetPreferredCodec2ComponentStore());
260 gPlatformAllocatorStore = store;
261 }
262 return store;
263}
264
265void SetPreferredCodec2ComponentStore(std::shared_ptr<C2ComponentStore> componentStore) {
266 static std::mutex mutex;
267 std::lock_guard<std::mutex> lock(mutex); // don't interleve set-s
268
269 // update preferred store
270 {
271 std::lock_guard<std::mutex> lock(gPreferredComponentStoreMutex);
272 gPreferredComponentStore = componentStore;
273 }
274
275 // update platform allocator's store as well if it is alive
276 std::shared_ptr<C2PlatformAllocatorStoreImpl> allocatorStore;
277 {
278 std::lock_guard<std::mutex> lock(gPlatformAllocatorStoreMutex);
279 allocatorStore = gPlatformAllocatorStore.lock();
280 }
281 if (allocatorStore) {
282 allocatorStore->setComponentStore(componentStore);
283 }
284}
285
286std::shared_ptr<C2ComponentStore> GetPreferredCodec2ComponentStore() {
287 std::lock_guard<std::mutex> lock(gPreferredComponentStoreMutex);
288 return gPreferredComponentStore ? gPreferredComponentStore : GetCodec2PlatformComponentStore();
289}
290
291namespace {
292
293class _C2BlockPoolCache {
294public:
295 _C2BlockPoolCache() : mBlockPoolSeqId(C2BlockPool::PLATFORM_START + 1) {}
296
297 c2_status_t _createBlockPool(
298 C2PlatformAllocatorStore::id_t allocatorId,
299 std::shared_ptr<const C2Component> component,
300 C2BlockPool::local_id_t poolId,
301 std::shared_ptr<C2BlockPool> *pool) {
302 std::shared_ptr<C2AllocatorStore> allocatorStore =
303 GetCodec2PlatformAllocatorStore();
304 std::shared_ptr<C2Allocator> allocator;
305 c2_status_t res = C2_NOT_FOUND;
306
307 switch(allocatorId) {
308 case C2PlatformAllocatorStore::ION:
309 case C2AllocatorStore::DEFAULT_LINEAR:
310 res = allocatorStore->fetchAllocator(
311 C2AllocatorStore::DEFAULT_LINEAR, &allocator);
312 if (res == C2_OK) {
313 std::shared_ptr<C2BlockPool> ptr =
314 std::make_shared<C2PooledBlockPool>(
315 allocator, poolId);
316 *pool = ptr;
317 mBlockPools[poolId] = ptr;
318 mComponents[poolId] = component;
319 }
320 break;
321 case C2PlatformAllocatorStore::GRALLOC:
322 case C2AllocatorStore::DEFAULT_GRAPHIC:
323 res = allocatorStore->fetchAllocator(
324 C2AllocatorStore::DEFAULT_GRAPHIC, &allocator);
325 if (res == C2_OK) {
326 std::shared_ptr<C2BlockPool> ptr =
327 std::make_shared<C2PooledBlockPool>(allocator, poolId);
328 *pool = ptr;
329 mBlockPools[poolId] = ptr;
330 mComponents[poolId] = component;
331 }
332 break;
333 case C2PlatformAllocatorStore::BUFFERQUEUE:
334 res = allocatorStore->fetchAllocator(
335 C2PlatformAllocatorStore::BUFFERQUEUE, &allocator);
336 if (res == C2_OK) {
337 std::shared_ptr<C2BlockPool> ptr =
338 std::make_shared<C2BufferQueueBlockPool>(
339 allocator, poolId);
340 *pool = ptr;
341 mBlockPools[poolId] = ptr;
342 mComponents[poolId] = component;
343 }
344 break;
345 default:
346 // Try to create block pool from platform store plugins.
347 std::shared_ptr<C2BlockPool> ptr;
348 res = C2PlatformStorePluginLoader::GetInstance()->createBlockPool(
349 allocatorId, poolId, &ptr);
350 if (res == C2_OK) {
351 *pool = ptr;
352 mBlockPools[poolId] = ptr;
353 mComponents[poolId] = component;
354 }
355 break;
356 }
357 return res;
358 }
359
360 c2_status_t createBlockPool(
361 C2PlatformAllocatorStore::id_t allocatorId,
362 std::shared_ptr<const C2Component> component,
363 std::shared_ptr<C2BlockPool> *pool) {
364 return _createBlockPool(allocatorId, component, mBlockPoolSeqId++, pool);
365 }
366
367 bool getBlockPool(
368 C2BlockPool::local_id_t blockPoolId,
369 std::shared_ptr<const C2Component> component,
370 std::shared_ptr<C2BlockPool> *pool) {
371 // TODO: use one iterator for multiple blockpool type scalability.
372 std::shared_ptr<C2BlockPool> ptr;
373 auto it = mBlockPools.find(blockPoolId);
374 if (it != mBlockPools.end()) {
375 ptr = it->second.lock();
376 if (!ptr) {
377 mBlockPools.erase(it);
378 mComponents.erase(blockPoolId);
379 } else {
380 auto found = mComponents.find(blockPoolId);
381 if (component == found->second.lock()) {
382 *pool = ptr;
383 return true;
384 }
385 }
386 }
387 return false;
388 }
389
390private:
391 C2BlockPool::local_id_t mBlockPoolSeqId;
392
393 std::map<C2BlockPool::local_id_t, std::weak_ptr<C2BlockPool>> mBlockPools;
394 std::map<C2BlockPool::local_id_t, std::weak_ptr<const C2Component>> mComponents;
395};
396
397static std::unique_ptr<_C2BlockPoolCache> sBlockPoolCache =
398 std::make_unique<_C2BlockPoolCache>();
399static std::mutex sBlockPoolCacheMutex;
400
401} // anynymous namespace
402
403c2_status_t GetCodec2BlockPool(
404 C2BlockPool::local_id_t id, std::shared_ptr<const C2Component> component,
405 std::shared_ptr<C2BlockPool> *pool) {
406 pool->reset();
407 std::lock_guard<std::mutex> lock(sBlockPoolCacheMutex);
408 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
409 std::shared_ptr<C2Allocator> allocator;
410 c2_status_t res = C2_NOT_FOUND;
411
412 if (id >= C2BlockPool::PLATFORM_START) {
413 if (sBlockPoolCache->getBlockPool(id, component, pool)) {
414 return C2_OK;
415 }
416 }
417
418 switch (id) {
419 case C2BlockPool::BASIC_LINEAR:
420 res = allocatorStore->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &allocator);
421 if (res == C2_OK) {
422 *pool = std::make_shared<C2BasicLinearBlockPool>(allocator);
423 }
424 break;
425 case C2BlockPool::BASIC_GRAPHIC:
426 res = allocatorStore->fetchAllocator(C2AllocatorStore::DEFAULT_GRAPHIC, &allocator);
427 if (res == C2_OK) {
428 *pool = std::make_shared<C2BasicGraphicBlockPool>(allocator);
429 }
430 break;
431 // TODO: remove this. this is temporary
432 case C2BlockPool::PLATFORM_START:
433 res = sBlockPoolCache->_createBlockPool(
434 C2PlatformAllocatorStore::BUFFERQUEUE, component, id, pool);
435 break;
436 default:
437 break;
438 }
439 return res;
440}
441
442c2_status_t CreateCodec2BlockPool(
443 C2PlatformAllocatorStore::id_t allocatorId,
444 std::shared_ptr<const C2Component> component,
445 std::shared_ptr<C2BlockPool> *pool) {
446 pool->reset();
447
448 std::lock_guard<std::mutex> lock(sBlockPoolCacheMutex);
449 return sBlockPoolCache->createBlockPool(allocatorId, component, pool);
450}
451
452class C2PlatformComponentStore : public C2ComponentStore {
453public:
454 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() override;
455 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const override;
456 virtual C2String getName() const override;
457 virtual c2_status_t querySupportedValues_sm(
458 std::vector<C2FieldSupportedValuesQuery> &fields) const override;
459 virtual c2_status_t querySupportedParams_nb(
460 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const override;
461 virtual c2_status_t query_sm(
462 const std::vector<C2Param*> &stackParams,
463 const std::vector<C2Param::Index> &heapParamIndices,
464 std::vector<std::unique_ptr<C2Param>> *const heapParams) const override;
465 virtual c2_status_t createInterface(
466 C2String name, std::shared_ptr<C2ComponentInterface> *const interface) override;
467 virtual c2_status_t createComponent(
468 C2String name, std::shared_ptr<C2Component> *const component) override;
469 virtual c2_status_t copyBuffer(
470 std::shared_ptr<C2GraphicBuffer> src, std::shared_ptr<C2GraphicBuffer> dst) override;
471 virtual c2_status_t config_sm(
472 const std::vector<C2Param*> &params,
473 std::vector<std::unique_ptr<C2SettingResult>> *const failures) override;
474 C2PlatformComponentStore();
475
476 virtual ~C2PlatformComponentStore() override = default;
477
478private:
479
480 /**
481 * An object encapsulating a loaded component module.
482 *
483 * \todo provide a way to add traits to known components here to avoid loading the .so-s
484 * for listComponents
485 */
486 struct ComponentModule : public C2ComponentFactory,
487 public std::enable_shared_from_this<ComponentModule> {
488 virtual c2_status_t createComponent(
489 c2_node_id_t id, std::shared_ptr<C2Component> *component,
490 ComponentDeleter deleter = std::default_delete<C2Component>()) override;
491 virtual c2_status_t createInterface(
492 c2_node_id_t id, std::shared_ptr<C2ComponentInterface> *interface,
493 InterfaceDeleter deleter = std::default_delete<C2ComponentInterface>()) override;
494
495 /**
496 * \returns the traits of the component in this module.
497 */
498 std::shared_ptr<const C2Component::Traits> getTraits();
499
500 /**
501 * Creates an uninitialized component module.
502 *
503 * \param name[in] component name.
504 *
505 * \note Only used by ComponentLoader.
506 */
507 ComponentModule()
508 : mInit(C2_NO_INIT),
509 mLibHandle(nullptr),
510 createFactory(nullptr),
511 destroyFactory(nullptr),
512 mComponentFactory(nullptr) {
513 }
514
515 /**
516 * Initializes a component module with a given library path. Must be called exactly once.
517 *
518 * \note Only used by ComponentLoader.
519 *
520 * \param alias[in] module alias
521 * \param libPath[in] library path
522 *
523 * \retval C2_OK the component module has been successfully loaded
524 * \retval C2_NO_MEMORY not enough memory to loading the component module
525 * \retval C2_NOT_FOUND could not locate the component module
526 * \retval C2_CORRUPTED the component module could not be loaded (unexpected)
527 * \retval C2_REFUSED permission denied to load the component module (unexpected)
528 * \retval C2_TIMED_OUT could not load the module within the time limit (unexpected)
529 */
530 c2_status_t init(std::string alias, std::string libPath);
531
532 virtual ~ComponentModule() override;
533
534 protected:
535 std::recursive_mutex mLock; ///< lock protecting mTraits
536 std::shared_ptr<C2Component::Traits> mTraits; ///< cached component traits
537
538 c2_status_t mInit; ///< initialization result
539
540 void *mLibHandle; ///< loaded library handle
541 C2ComponentFactory::CreateCodec2FactoryFunc createFactory; ///< loaded create function
542 C2ComponentFactory::DestroyCodec2FactoryFunc destroyFactory; ///< loaded destroy function
543 C2ComponentFactory *mComponentFactory; ///< loaded/created component factory
544 };
545
546 /**
547 * An object encapsulating a loadable component module.
548 *
549 * \todo make this also work for enumerations
550 */
551 struct ComponentLoader {
552 /**
553 * Load the component module.
554 *
555 * This method simply returns the component module if it is already currently loaded, or
556 * attempts to load it if it is not.
557 *
558 * \param module[out] pointer to the shared pointer where the loaded module shall be stored.
559 * This will be nullptr on error.
560 *
561 * \retval C2_OK the component module has been successfully loaded
562 * \retval C2_NO_MEMORY not enough memory to loading the component module
563 * \retval C2_NOT_FOUND could not locate the component module
564 * \retval C2_CORRUPTED the component module could not be loaded
565 * \retval C2_REFUSED permission denied to load the component module
566 */
567 c2_status_t fetchModule(std::shared_ptr<ComponentModule> *module) {
568 c2_status_t res = C2_OK;
569 std::lock_guard<std::mutex> lock(mMutex);
570 std::shared_ptr<ComponentModule> localModule = mModule.lock();
571 if (localModule == nullptr) {
572 localModule = std::make_shared<ComponentModule>();
573 res = localModule->init(mAlias, mLibPath);
574 if (res == C2_OK) {
575 mModule = localModule;
576 }
577 }
578 *module = localModule;
579 return res;
580 }
581
582 /**
583 * Creates a component loader for a specific library path (or name).
584 */
585 ComponentLoader(std::string alias, std::string libPath)
586 : mAlias(alias), mLibPath(libPath) {}
587
588 private:
589 std::mutex mMutex; ///< mutex guarding the module
590 std::weak_ptr<ComponentModule> mModule; ///< weak reference to the loaded module
591 std::string mAlias; ///< component alias
592 std::string mLibPath; ///< library path
593 };
594
595 struct Interface : public C2InterfaceHelper {
596 std::shared_ptr<C2StoreIonUsageInfo> mIonUsageInfo;
597
598 Interface(std::shared_ptr<C2ReflectorHelper> reflector)
599 : C2InterfaceHelper(reflector) {
600 setDerivedInstance(this);
601
602 struct Setter {
603 static C2R setIonUsage(bool /* mayBlock */, C2P<C2StoreIonUsageInfo> &me) {
604 me.set().heapMask = ~0;
605 me.set().allocFlags = 0;
606 me.set().minAlignment = 0;
607 return C2R::Ok();
608 }
609 };
610
611 addParameter(
612 DefineParam(mIonUsageInfo, "ion-usage")
613 .withDefault(new C2StoreIonUsageInfo())
614 .withFields({
615 C2F(mIonUsageInfo, usage).flags({C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE}),
616 C2F(mIonUsageInfo, capacity).inRange(0, UINT32_MAX, 1024),
617 C2F(mIonUsageInfo, heapMask).any(),
618 C2F(mIonUsageInfo, allocFlags).flags({}),
619 C2F(mIonUsageInfo, minAlignment).equalTo(0)
620 })
621 .withSetter(Setter::setIonUsage)
622 .build());
623 }
624 };
625
626 /**
627 * Retrieves the component loader for a component.
628 *
629 * \return a non-ref-holding pointer to the component loader.
630 *
631 * \retval C2_OK the component loader has been successfully retrieved
632 * \retval C2_NO_MEMORY not enough memory to locate the component loader
633 * \retval C2_NOT_FOUND could not locate the component to be loaded
634 * \retval C2_CORRUPTED the component loader could not be identified due to some modules being
635 * corrupted (this can happen if the name does not refer to an already
636 * identified component but some components could not be loaded due to
637 * bad library)
638 * \retval C2_REFUSED permission denied to find the component loader for the named component
639 * (this can happen if the name does not refer to an already identified
640 * component but some components could not be loaded due to lack of
641 * permissions)
642 */
643 c2_status_t findComponent(C2String name, ComponentLoader **loader);
644
645 std::map<C2String, ComponentLoader> mComponents; ///< map of name -> components
646 std::vector<C2String> mComponentsList; ///< list of components
647 std::shared_ptr<C2ReflectorHelper> mReflector;
648 Interface mInterface;
649};
650
651c2_status_t C2PlatformComponentStore::ComponentModule::init(
652 std::string alias, std::string libPath) {
653 ALOGV("in %s", __func__);
654 ALOGV("loading dll");
655 mLibHandle = dlopen(libPath.c_str(), RTLD_NOW|RTLD_NODELETE);
656 if (mLibHandle == nullptr) {
657 // could be access/symbol or simply not being there
658 ALOGD("could not dlopen %s: %s", libPath.c_str(), dlerror());
659 mInit = C2_CORRUPTED;
660 } else {
661 createFactory =
662 (C2ComponentFactory::CreateCodec2FactoryFunc)dlsym(mLibHandle, "CreateCodec2Factory");
663 destroyFactory =
664 (C2ComponentFactory::DestroyCodec2FactoryFunc)dlsym(mLibHandle, "DestroyCodec2Factory");
665
666 mComponentFactory = createFactory();
667 if (mComponentFactory == nullptr) {
668 ALOGD("could not create factory in %s", libPath.c_str());
669 mInit = C2_NO_MEMORY;
670 } else {
671 mInit = C2_OK;
672 }
673 }
674 if (mInit != C2_OK) {
675 return mInit;
676 }
677
678 std::shared_ptr<C2ComponentInterface> intf;
679 c2_status_t res = createInterface(0, &intf);
680 if (res != C2_OK) {
681 ALOGD("failed to create interface: %d", res);
682 return mInit;
683 }
684
685 std::shared_ptr<C2Component::Traits> traits(new (std::nothrow) C2Component::Traits);
686 if (traits) {
687 if (alias != intf->getName()) {
688 ALOGV("%s is alias to %s", alias.c_str(), intf->getName().c_str());
689 }
Lajos Molnar62d62d62019-01-31 16:26:46 -0800690 traits->name = alias; // TODO: this needs to be intf->getName() once aliases are supported
691
692 C2ComponentKindSetting kind;
693 C2ComponentDomainSetting domain;
694 res = intf->query_vb({ &kind, &domain }, {}, C2_MAY_BLOCK, nullptr);
695 bool fixDomain = res != C2_OK;
696 if (res == C2_OK) {
697 traits->kind = kind.value;
698 traits->domain = domain.value;
699 } else {
700 // TODO: remove this fall-back
701 ALOGD("failed to query interface for kind and domain: %d", res);
702
703 traits->kind =
704 (traits->name.find("encoder") != std::string::npos) ? C2Component::KIND_ENCODER :
705 (traits->name.find("decoder") != std::string::npos) ? C2Component::KIND_DECODER :
706 C2Component::KIND_OTHER;
707 }
708
709 uint32_t mediaTypeIndex =
710 traits->kind == C2Component::KIND_ENCODER ? C2PortMimeConfig::output::PARAM_TYPE
Pawin Vongmasa36653902018-11-15 00:10:25 -0800711 : C2PortMimeConfig::input::PARAM_TYPE;
712 std::vector<std::unique_ptr<C2Param>> params;
713 res = intf->query_vb({}, { mediaTypeIndex }, C2_MAY_BLOCK, &params);
714 if (res != C2_OK) {
715 ALOGD("failed to query interface: %d", res);
716 return mInit;
717 }
718 if (params.size() != 1u) {
719 ALOGD("failed to query interface: unexpected vector size: %zu", params.size());
720 return mInit;
721 }
Lajos Molnar62d62d62019-01-31 16:26:46 -0800722 C2PortMimeConfig *mediaTypeConfig = C2PortMimeConfig::From(params[0].get());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800723 if (mediaTypeConfig == nullptr) {
724 ALOGD("failed to query media type");
725 return mInit;
726 }
Lajos Molnar62d62d62019-01-31 16:26:46 -0800727 traits->mediaType =
728 std::string(mediaTypeConfig->m.value,
729 strnlen(mediaTypeConfig->m.value, mediaTypeConfig->flexCount()));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800730
Lajos Molnar62d62d62019-01-31 16:26:46 -0800731 if (fixDomain) {
732 if (strncmp(traits->mediaType.c_str(), "audio/", 6) == 0) {
733 traits->domain = C2Component::DOMAIN_AUDIO;
734 } else if (strncmp(traits->mediaType.c_str(), "video/", 6) == 0) {
735 traits->domain = C2Component::DOMAIN_VIDEO;
736 } else if (strncmp(traits->mediaType.c_str(), "image/", 6) == 0) {
737 traits->domain = C2Component::DOMAIN_IMAGE;
738 } else {
739 traits->domain = C2Component::DOMAIN_OTHER;
740 }
741 }
742
743 // TODO: get this properly from the store during emplace
744 switch (traits->domain) {
745 case C2Component::DOMAIN_AUDIO:
746 traits->rank = 8;
747 break;
748 default:
749 traits->rank = 512;
750 }
751
752 params.clear();
753 res = intf->query_vb({}, { C2ComponentAliasesSetting::PARAM_TYPE }, C2_MAY_BLOCK, &params);
754 if (res == C2_OK && params.size() == 1u) {
755 C2ComponentAliasesSetting *aliasesSetting =
756 C2ComponentAliasesSetting::From(params[0].get());
757 if (aliasesSetting) {
758 // Split aliases on ','
759 // This looks simpler in plain C and even std::string would still make a copy.
760 char *aliases = ::strndup(aliasesSetting->m.value, aliasesSetting->flexCount());
761 ALOGD("'%s' has aliases: '%s'", intf->getName().c_str(), aliases);
762
763 for (char *tok, *ptr, *str = aliases; (tok = ::strtok_r(str, ",", &ptr));
764 str = nullptr) {
765 traits->aliases.push_back(tok);
766 ALOGD("adding alias: '%s'", tok);
767 }
768 free(aliases);
769 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 }
771 }
772 mTraits = traits;
773
774 return mInit;
775}
776
777C2PlatformComponentStore::ComponentModule::~ComponentModule() {
778 ALOGV("in %s", __func__);
779 if (destroyFactory && mComponentFactory) {
780 destroyFactory(mComponentFactory);
781 }
782 if (mLibHandle) {
783 ALOGV("unloading dll");
784 dlclose(mLibHandle);
785 }
786}
787
788c2_status_t C2PlatformComponentStore::ComponentModule::createInterface(
789 c2_node_id_t id, std::shared_ptr<C2ComponentInterface> *interface,
790 std::function<void(::C2ComponentInterface*)> deleter) {
791 interface->reset();
792 if (mInit != C2_OK) {
793 return mInit;
794 }
795 std::shared_ptr<ComponentModule> module = shared_from_this();
796 c2_status_t res = mComponentFactory->createInterface(
797 id, interface, [module, deleter](C2ComponentInterface *p) mutable {
798 // capture module so that we ensure we still have it while deleting interface
799 deleter(p); // delete interface first
800 module.reset(); // remove module ref (not technically needed)
801 });
802 return res;
803}
804
805c2_status_t C2PlatformComponentStore::ComponentModule::createComponent(
806 c2_node_id_t id, std::shared_ptr<C2Component> *component,
807 std::function<void(::C2Component*)> deleter) {
808 component->reset();
809 if (mInit != C2_OK) {
810 return mInit;
811 }
812 std::shared_ptr<ComponentModule> module = shared_from_this();
813 c2_status_t res = mComponentFactory->createComponent(
814 id, component, [module, deleter](C2Component *p) mutable {
815 // capture module so that we ensure we still have it while deleting component
816 deleter(p); // delete component first
817 module.reset(); // remove module ref (not technically needed)
818 });
819 return res;
820}
821
822std::shared_ptr<const C2Component::Traits> C2PlatformComponentStore::ComponentModule::getTraits() {
823 std::unique_lock<std::recursive_mutex> lock(mLock);
824 return mTraits;
825}
826
827C2PlatformComponentStore::C2PlatformComponentStore()
828 : mReflector(std::make_shared<C2ReflectorHelper>()),
829 mInterface(mReflector) {
830
831 auto emplace = [this](const char *alias, const char *libPath) {
832 // ComponentLoader is neither copiable nor movable, so it must be
833 // constructed in-place. Now ComponentLoader takes two arguments in
834 // constructor, so we need to use piecewise_construct to achieve this
835 // behavior.
836 mComponents.emplace(
837 std::piecewise_construct,
838 std::forward_as_tuple(alias),
839 std::forward_as_tuple(alias, libPath));
840 mComponentsList.emplace_back(alias);
841 };
842 // TODO: move this also into a .so so it can be updated
Pawin Vongmasae55ed3f2018-11-28 03:39:57 -0800843 emplace("c2.android.avc.decoder", "libcodec2_soft_avcdec.so");
844 emplace("c2.android.avc.encoder", "libcodec2_soft_avcenc.so");
845 emplace("c2.android.aac.decoder", "libcodec2_soft_aacdec.so");
846 emplace("c2.android.aac.encoder", "libcodec2_soft_aacenc.so");
847 emplace("c2.android.amrnb.decoder", "libcodec2_soft_amrnbdec.so");
848 emplace("c2.android.amrnb.encoder", "libcodec2_soft_amrnbenc.so");
849 emplace("c2.android.amrwb.decoder", "libcodec2_soft_amrwbdec.so");
850 emplace("c2.android.amrwb.encoder", "libcodec2_soft_amrwbenc.so");
851 emplace("c2.android.hevc.decoder", "libcodec2_soft_hevcdec.so");
852 emplace("c2.android.g711.alaw.decoder", "libcodec2_soft_g711alawdec.so");
853 emplace("c2.android.g711.mlaw.decoder", "libcodec2_soft_g711mlawdec.so");
854 emplace("c2.android.mpeg2.decoder", "libcodec2_soft_mpeg2dec.so");
855 emplace("c2.android.h263.decoder", "libcodec2_soft_h263dec.so");
856 emplace("c2.android.h263.encoder", "libcodec2_soft_h263enc.so");
857 emplace("c2.android.mpeg4.decoder", "libcodec2_soft_mpeg4dec.so");
858 emplace("c2.android.mpeg4.encoder", "libcodec2_soft_mpeg4enc.so");
859 emplace("c2.android.mp3.decoder", "libcodec2_soft_mp3dec.so");
860 emplace("c2.android.vorbis.decoder", "libcodec2_soft_vorbisdec.so");
861 emplace("c2.android.opus.decoder", "libcodec2_soft_opusdec.so");
Manisha Jajooc237cbc2018-11-16 18:56:20 +0530862 emplace("c2.android.opus.encoder", "libcodec2_soft_opusenc.so");
Pawin Vongmasae55ed3f2018-11-28 03:39:57 -0800863 emplace("c2.android.vp8.decoder", "libcodec2_soft_vp8dec.so");
864 emplace("c2.android.vp9.decoder", "libcodec2_soft_vp9dec.so");
865 emplace("c2.android.vp8.encoder", "libcodec2_soft_vp8enc.so");
866 emplace("c2.android.vp9.encoder", "libcodec2_soft_vp9enc.so");
Ray Essick707c1462018-12-05 15:21:35 -0800867 emplace("c2.android.av1.decoder", "libcodec2_soft_av1dec.so");
Pawin Vongmasae55ed3f2018-11-28 03:39:57 -0800868 emplace("c2.android.raw.decoder", "libcodec2_soft_rawdec.so");
869 emplace("c2.android.flac.decoder", "libcodec2_soft_flacdec.so");
870 emplace("c2.android.flac.encoder", "libcodec2_soft_flacenc.so");
871 emplace("c2.android.gsm.decoder", "libcodec2_soft_gsmdec.so");
872 emplace("c2.android.xaac.decoder", "libcodec2_soft_xaacdec.so");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873
874 // "Aliases"
875 // TODO: use aliases proper from C2Component::Traits
Pawin Vongmasae55ed3f2018-11-28 03:39:57 -0800876 emplace("OMX.google.h264.decoder", "libcodec2_soft_avcdec.so");
877 emplace("OMX.google.h264.encoder", "libcodec2_soft_avcenc.so");
878 emplace("OMX.google.aac.decoder", "libcodec2_soft_aacdec.so");
879 emplace("OMX.google.aac.encoder", "libcodec2_soft_aacenc.so");
880 emplace("OMX.google.amrnb.decoder", "libcodec2_soft_amrnbdec.so");
881 emplace("OMX.google.amrnb.encoder", "libcodec2_soft_amrnbenc.so");
882 emplace("OMX.google.amrwb.decoder", "libcodec2_soft_amrwbdec.so");
883 emplace("OMX.google.amrwb.encoder", "libcodec2_soft_amrwbenc.so");
884 emplace("OMX.google.hevc.decoder", "libcodec2_soft_hevcdec.so");
885 emplace("OMX.google.g711.alaw.decoder", "libcodec2_soft_g711alawdec.so");
886 emplace("OMX.google.g711.mlaw.decoder", "libcodec2_soft_g711mlawdec.so");
887 emplace("OMX.google.mpeg2.decoder", "libcodec2_soft_mpeg2dec.so");
888 emplace("OMX.google.h263.decoder", "libcodec2_soft_h263dec.so");
889 emplace("OMX.google.h263.encoder", "libcodec2_soft_h263enc.so");
890 emplace("OMX.google.mpeg4.decoder", "libcodec2_soft_mpeg4dec.so");
891 emplace("OMX.google.mpeg4.encoder", "libcodec2_soft_mpeg4enc.so");
892 emplace("OMX.google.mp3.decoder", "libcodec2_soft_mp3dec.so");
893 emplace("OMX.google.vorbis.decoder", "libcodec2_soft_vorbisdec.so");
894 emplace("OMX.google.opus.decoder", "libcodec2_soft_opusdec.so");
895 emplace("OMX.google.vp8.decoder", "libcodec2_soft_vp8dec.so");
896 emplace("OMX.google.vp9.decoder", "libcodec2_soft_vp9dec.so");
897 emplace("OMX.google.vp8.encoder", "libcodec2_soft_vp8enc.so");
898 emplace("OMX.google.vp9.encoder", "libcodec2_soft_vp9enc.so");
899 emplace("OMX.google.raw.decoder", "libcodec2_soft_rawdec.so");
900 emplace("OMX.google.flac.decoder", "libcodec2_soft_flacdec.so");
901 emplace("OMX.google.flac.encoder", "libcodec2_soft_flacenc.so");
902 emplace("OMX.google.gsm.decoder", "libcodec2_soft_gsmdec.so");
903 emplace("OMX.google.xaac.decoder", "libcodec2_soft_xaacdec.so");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800904}
905
906c2_status_t C2PlatformComponentStore::copyBuffer(
907 std::shared_ptr<C2GraphicBuffer> src, std::shared_ptr<C2GraphicBuffer> dst) {
908 (void)src;
909 (void)dst;
910 return C2_OMITTED;
911}
912
913c2_status_t C2PlatformComponentStore::query_sm(
914 const std::vector<C2Param*> &stackParams,
915 const std::vector<C2Param::Index> &heapParamIndices,
916 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
917 return mInterface.query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
918}
919
920c2_status_t C2PlatformComponentStore::config_sm(
921 const std::vector<C2Param*> &params,
922 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
923 return mInterface.config(params, C2_MAY_BLOCK, failures);
924}
925
926std::vector<std::shared_ptr<const C2Component::Traits>> C2PlatformComponentStore::listComponents() {
927 // This method SHALL return within 500ms.
928 std::vector<std::shared_ptr<const C2Component::Traits>> list;
929 for (const C2String &alias : mComponentsList) {
930 ComponentLoader &loader = mComponents.at(alias);
931 std::shared_ptr<ComponentModule> module;
932 c2_status_t res = loader.fetchModule(&module);
933 if (res == C2_OK) {
934 std::shared_ptr<const C2Component::Traits> traits = module->getTraits();
935 if (traits) {
936 list.push_back(traits);
937 }
938 }
939 }
940 return list;
941}
942
943c2_status_t C2PlatformComponentStore::findComponent(C2String name, ComponentLoader **loader) {
944 *loader = nullptr;
945 auto pos = mComponents.find(name);
946 // TODO: check aliases
947 if (pos == mComponents.end()) {
948 return C2_NOT_FOUND;
949 }
950 *loader = &pos->second;
951 return C2_OK;
952}
953
954c2_status_t C2PlatformComponentStore::createComponent(
955 C2String name, std::shared_ptr<C2Component> *const component) {
956 // This method SHALL return within 100ms.
957 component->reset();
958 ComponentLoader *loader;
959 c2_status_t res = findComponent(name, &loader);
960 if (res == C2_OK) {
961 std::shared_ptr<ComponentModule> module;
962 res = loader->fetchModule(&module);
963 if (res == C2_OK) {
964 // TODO: get a unique node ID
965 res = module->createComponent(0, component);
966 }
967 }
968 return res;
969}
970
971c2_status_t C2PlatformComponentStore::createInterface(
972 C2String name, std::shared_ptr<C2ComponentInterface> *const interface) {
973 // This method SHALL return within 100ms.
974 interface->reset();
975 ComponentLoader *loader;
976 c2_status_t res = findComponent(name, &loader);
977 if (res == C2_OK) {
978 std::shared_ptr<ComponentModule> module;
979 res = loader->fetchModule(&module);
980 if (res == C2_OK) {
981 // TODO: get a unique node ID
982 res = module->createInterface(0, interface);
983 }
984 }
985 return res;
986}
987
988c2_status_t C2PlatformComponentStore::querySupportedParams_nb(
989 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
990 return mInterface.querySupportedParams(params);
991}
992
993c2_status_t C2PlatformComponentStore::querySupportedValues_sm(
994 std::vector<C2FieldSupportedValuesQuery> &fields) const {
995 return mInterface.querySupportedValues(fields, C2_MAY_BLOCK);
996}
997
998C2String C2PlatformComponentStore::getName() const {
999 return "android.componentStore.platform";
1000}
1001
1002std::shared_ptr<C2ParamReflector> C2PlatformComponentStore::getParamReflector() const {
1003 return mReflector;
1004}
1005
1006std::shared_ptr<C2ComponentStore> GetCodec2PlatformComponentStore() {
1007 static std::mutex mutex;
1008 static std::weak_ptr<C2ComponentStore> platformStore;
1009 std::lock_guard<std::mutex> lock(mutex);
1010 std::shared_ptr<C2ComponentStore> store = platformStore.lock();
1011 if (store == nullptr) {
1012 store = std::make_shared<C2PlatformComponentStore>();
1013 platformStore = store;
1014 }
1015 return store;
1016}
1017
1018} // namespace android