1 /*
2  * Copyright (C) 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 <log/log.h>
20 
21 #include <codec2/hidl/1.0/ComponentStore.h>
22 #include <codec2/hidl/1.0/InputSurface.h>
23 #include <codec2/hidl/1.0/Component.h>
24 #include <codec2/hidl/1.0/ConfigurableC2Intf.h>
25 #include <codec2/hidl/1.0/types.h>
26 
27 #include <gui/bufferqueue/1.0/WGraphicBufferProducer.h>
28 #include <media/stagefright/bqhelper/GraphicBufferSource.h>
29 
30 #include <C2PlatformSupport.h>
31 #include <util/C2InterfaceHelper.h>
32 
33 #include <utils/Errors.h>
34 
35 #include <android-base/file.h>
36 
37 #ifdef LOG
38 #undef LOG
39 #endif
40 
41 #ifdef PLOG
42 #undef PLOG
43 #endif
44 
45 #include <android-base/logging.h>
46 
47 #include <ostream>
48 #include <sstream>
49 #include <iomanip>
50 
51 namespace hardware {
52 namespace google {
53 namespace media {
54 namespace c2 {
55 namespace V1_0 {
56 namespace utils {
57 
58 using namespace ::android;
59 using ::android::GraphicBufferSource;
60 using namespace ::android::hardware::media::bufferpool::V1_0::implementation;
61 
62 namespace /* unnamed */ {
63 
64 struct StoreIntf : public ConfigurableC2Intf {
StoreIntfhardware::google::media::c2::V1_0::utils::__anon66409a0c0111::StoreIntf65     StoreIntf(const std::shared_ptr<C2ComponentStore>& store) :
66         ConfigurableC2Intf(store ? store->getName() : ""),
67         mStore(store) {
68     }
69 
confighardware::google::media::c2::V1_0::utils::__anon66409a0c0111::StoreIntf70     c2_status_t config(
71             const std::vector<C2Param*> &params,
72             c2_blocking_t mayBlock,
73             std::vector<std::unique_ptr<C2SettingResult>> *const failures
74             ) override {
75         // Assume all params are blocking
76         // TODO: Filter for supported params
77         if (mayBlock == C2_DONT_BLOCK && params.size() != 0) {
78             return C2_BLOCKING;
79         }
80         return mStore->config_sm(params, failures);
81     }
82 
queryhardware::google::media::c2::V1_0::utils::__anon66409a0c0111::StoreIntf83     c2_status_t query(
84             const std::vector<C2Param::Index> &indices,
85             c2_blocking_t mayBlock,
86             std::vector<std::unique_ptr<C2Param>> *const params) const override {
87         // Assume all params are blocking
88         // TODO: Filter for supported params
89         if (mayBlock == C2_DONT_BLOCK && indices.size() != 0) {
90             return C2_BLOCKING;
91         }
92         return mStore->query_sm({}, indices, params);
93     }
94 
querySupportedParamshardware::google::media::c2::V1_0::utils::__anon66409a0c0111::StoreIntf95     c2_status_t querySupportedParams(
96             std::vector<std::shared_ptr<C2ParamDescriptor>> *const params
97             ) const override {
98         return mStore->querySupportedParams_nb(params);
99     }
100 
querySupportedValueshardware::google::media::c2::V1_0::utils::__anon66409a0c0111::StoreIntf101     c2_status_t querySupportedValues(
102             std::vector<C2FieldSupportedValuesQuery> &fields,
103             c2_blocking_t mayBlock) const override {
104         // Assume all params are blocking
105         // TODO: Filter for supported params
106         if (mayBlock == C2_DONT_BLOCK && fields.size() != 0) {
107             return C2_BLOCKING;
108         }
109         return mStore->querySupportedValues_sm(fields);
110     }
111 
112 protected:
113     std::shared_ptr<C2ComponentStore> mStore;
114 };
115 
116 } // unnamed namespace
117 
ComponentStore(const std::shared_ptr<C2ComponentStore> & store)118 ComponentStore::ComponentStore(const std::shared_ptr<C2ComponentStore>& store) :
119     Configurable(new CachedConfigurable(std::make_unique<StoreIntf>(store))),
120     mStore(store) {
121 
122     std::shared_ptr<C2ComponentStore> platformStore = android::GetCodec2PlatformComponentStore();
123     SetPreferredCodec2ComponentStore(store);
124 
125     // Retrieve struct descriptors
126     mParamReflector = mStore->getParamReflector();
127 
128     // Retrieve supported parameters from store
129     mInit = init(this);
130 }
131 
validateSupportedParams(const std::vector<std::shared_ptr<C2ParamDescriptor>> & params)132 c2_status_t ComponentStore::validateSupportedParams(
133         const std::vector<std::shared_ptr<C2ParamDescriptor>>& params) {
134     c2_status_t res = C2_OK;
135 
136     for (const std::shared_ptr<C2ParamDescriptor> &desc : params) {
137         if (!desc) {
138             // All descriptors should be valid
139             res = res ? res : C2_BAD_VALUE;
140             continue;
141         }
142         C2Param::CoreIndex coreIndex = desc->index().coreIndex();
143         std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
144         auto it = mStructDescriptors.find(coreIndex);
145         if (it == mStructDescriptors.end()) {
146             std::shared_ptr<C2StructDescriptor> structDesc =
147                     mParamReflector->describe(coreIndex);
148             if (!structDesc) {
149                 // All supported params must be described
150                 res = C2_BAD_INDEX;
151             }
152             mStructDescriptors.insert({ coreIndex, structDesc });
153         }
154     }
155     return res;
156 }
157 
158 // 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)159 Return<void> ComponentStore::createComponent(
160         const hidl_string& name,
161         const sp<IComponentListener>& listener,
162         const sp<IClientManager>& pool,
163         createComponent_cb _hidl_cb) {
164 
165     sp<Component> component;
166     std::shared_ptr<C2Component> c2component;
167     Status status = static_cast<Status>(
168             mStore->createComponent(name, &c2component));
169 
170     if (status == Status::OK) {
171         onInterfaceLoaded(c2component->intf());
172         component = new Component(c2component, listener, this, pool);
173         if (!component) {
174             status = Status::CORRUPTED;
175         } else if (component->status() != C2_OK) {
176             status = static_cast<Status>(component->status());
177         } else {
178             component->initListener(component);
179             if (component->status() != C2_OK) {
180                 status = static_cast<Status>(component->status());
181             } else {
182                 std::lock_guard<std::mutex> lock(mComponentRosterMutex);
183                 component->setLocalId(
184                         mComponentRoster.emplace(
185                             Component::InterfaceKey(component),
186                             c2component)
187                         .first);
188             }
189         }
190     }
191     _hidl_cb(status, component);
192     return Void();
193 }
194 
createInterface(const hidl_string & name,createInterface_cb _hidl_cb)195 Return<void> ComponentStore::createInterface(
196         const hidl_string& name,
197         createInterface_cb _hidl_cb) {
198     std::shared_ptr<C2ComponentInterface> c2interface;
199     c2_status_t res = mStore->createInterface(name, &c2interface);
200     sp<IComponentInterface> interface;
201     if (res == C2_OK) {
202         onInterfaceLoaded(c2interface);
203         interface = new ComponentInterface(c2interface, this);
204     }
205     _hidl_cb((Status)res, interface);
206     return Void();
207 }
208 
listComponents(listComponents_cb _hidl_cb)209 Return<void> ComponentStore::listComponents(listComponents_cb _hidl_cb) {
210     std::vector<std::shared_ptr<const C2Component::Traits>> c2traits =
211             mStore->listComponents();
212     hidl_vec<IComponentStore::ComponentTraits> traits(c2traits.size());
213     size_t ix = 0;
214     for (const std::shared_ptr<const C2Component::Traits> &c2trait : c2traits) {
215         if (c2trait) {
216             objcpy(&traits[ix++], *c2trait);
217         }
218     }
219     traits.resize(ix);
220     _hidl_cb(traits);
221     return Void();
222 }
223 
createInputSurface()224 Return<sp<IInputSurface>> ComponentStore::createInputSurface() {
225     sp<GraphicBufferSource> source = new GraphicBufferSource();
226     if (source->initCheck() != OK) {
227         return nullptr;
228     }
229     typedef ::android::hardware::graphics::bufferqueue::V1_0::
230             IGraphicBufferProducer HGbp;
231     typedef ::android::TWGraphicBufferProducer<HGbp> B2HGbp;
232     return new InputSurface(
233             this,
234             std::make_shared<C2ReflectorHelper>(),
235             new B2HGbp(source->getIGraphicBufferProducer()),
236             source);
237 }
238 
onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> & intf)239 void ComponentStore::onInterfaceLoaded(const std::shared_ptr<C2ComponentInterface> &intf) {
240     // invalidate unsupported struct descriptors if a new interface is loaded as it may have
241     // exposed new descriptors
242     std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
243     if (!mLoadedInterfaces.count(intf->getName())) {
244         mUnsupportedStructDescriptors.clear();
245         mLoadedInterfaces.emplace(intf->getName());
246     }
247 }
248 
getStructDescriptors(const hidl_vec<uint32_t> & indices,getStructDescriptors_cb _hidl_cb)249 Return<void> ComponentStore::getStructDescriptors(
250         const hidl_vec<uint32_t>& indices,
251         getStructDescriptors_cb _hidl_cb) {
252     hidl_vec<StructDescriptor> descriptors(indices.size());
253     size_t dstIx = 0;
254     Status res = Status::OK;
255     for (size_t srcIx = 0; srcIx < indices.size(); ++srcIx) {
256         std::lock_guard<std::mutex> lock(mStructDescriptorsMutex);
257         const C2Param::CoreIndex coreIndex = C2Param::CoreIndex(indices[srcIx]).coreIndex();
258         const auto item = mStructDescriptors.find(coreIndex);
259         if (item == mStructDescriptors.end()) {
260             // not in the cache, and not known to be unsupported, query local reflector
261             if (!mUnsupportedStructDescriptors.count(coreIndex)) {
262                 std::shared_ptr<C2StructDescriptor> structDesc =
263                     mParamReflector->describe(coreIndex);
264                 if (!structDesc) {
265                     mUnsupportedStructDescriptors.emplace(coreIndex);
266                 } else {
267                     mStructDescriptors.insert({ coreIndex, structDesc });
268                     objcpy(&descriptors[dstIx++], *structDesc);
269                     continue;
270                 }
271             }
272             res = Status::NOT_FOUND;
273         } else if (item->second) {
274             objcpy(&descriptors[dstIx++], *item->second);
275         } else {
276             res = Status::NO_MEMORY;
277         }
278     }
279     descriptors.resize(dstIx);
280     _hidl_cb(res, descriptors);
281     return Void();
282 }
283 
getPoolClientManager()284 Return<sp<IClientManager>> ComponentStore::getPoolClientManager() {
285     return ClientManager::getInstance();
286 }
287 
copyBuffer(const Buffer & src,const Buffer & dst)288 Return<Status> ComponentStore::copyBuffer(const Buffer& src, const Buffer& dst) {
289     // TODO implement
290     (void)src;
291     (void)dst;
292     return Status::OMITTED;
293 }
294 
reportComponentDeath(const Component::LocalId & componentLocalId)295 void ComponentStore::reportComponentDeath(
296         const Component::LocalId& componentLocalId) {
297     std::lock_guard<std::mutex> lock(mComponentRosterMutex);
298     mComponentRoster.erase(componentLocalId);
299 }
300 
findC2Component(const sp<IComponent> & component) const301 std::shared_ptr<C2Component> ComponentStore::findC2Component(
302         const sp<IComponent>& component) const {
303     std::lock_guard<std::mutex> lock(mComponentRosterMutex);
304     Component::LocalId it = mComponentRoster.find(
305             Component::InterfaceKey(component));
306     if (it == mComponentRoster.end()) {
307         return std::shared_ptr<C2Component>();
308     }
309     return it->second.lock();
310 }
311 
312 // Debug dump
313 
314 namespace /* unnamed */ {
315 
316 // Dump component traits
dump(std::ostream & out,const std::shared_ptr<const C2Component::Traits> & comp)317 std::ostream& dump(
318         std::ostream& out,
319         const std::shared_ptr<const C2Component::Traits>& comp) {
320 
321     constexpr const char indent[] = "    ";
322 
323     out << indent << "name: " << comp->name << std::endl;
324     out << indent << "domain: " << comp->domain << std::endl;
325     out << indent << "kind: " << comp->kind << std::endl;
326     out << indent << "rank: " << comp->rank << std::endl;
327     out << indent << "mediaType: " << comp->mediaType << std::endl;
328     out << indent << "aliases:";
329     for (const auto& alias : comp->aliases) {
330         out << ' ' << alias;
331     }
332     out << std::endl;
333 
334     return out;
335 }
336 
337 // Dump component
dump(std::ostream & out,const std::shared_ptr<C2Component> & comp)338 std::ostream& dump(
339         std::ostream& out,
340         const std::shared_ptr<C2Component>& comp) {
341 
342     constexpr const char indent[] = "    ";
343 
344     std::shared_ptr<C2ComponentInterface> intf = comp->intf();
345     if (!intf) {
346         out << indent << "Unknown -- null interface" << std::endl;
347         return out;
348     }
349     out << indent << "name: " << intf->getName() << std::endl;
350     out << indent << "id: " << intf->getId() << std::endl;
351     return out;
352 }
353 
354 } // unnamed namespace
355 
debug(const hidl_handle & handle,const hidl_vec<hidl_string> &)356 Return<void> ComponentStore::debug(
357         const hidl_handle& handle,
358         const hidl_vec<hidl_string>& /* args */) {
359     LOG(INFO) << "debug -- dumping...";
360     const native_handle_t *h = handle.getNativeHandle();
361     if (!h || h->numFds != 1) {
362        LOG(ERROR) << "debug -- dumping failed -- "
363                "invalid file descriptor to dump to";
364        return Void();
365     }
366     std::ostringstream out;
367 
368     { // Populate "out".
369 
370         constexpr const char indent[] = "  ";
371 
372         // Show name.
373         out << "Beginning of dump -- C2ComponentStore: "
374                 << mStore->getName() << std::endl << std::endl;
375 
376         // Retrieve the list of supported components.
377         std::vector<std::shared_ptr<const C2Component::Traits>> traitsList =
378                 mStore->listComponents();
379 
380         // Dump the traits of supported components.
381         out << indent << "Supported components:" << std::endl << std::endl;
382         if (traitsList.size() == 0) {
383             out << indent << indent << "NONE" << std::endl << std::endl;
384         } else {
385             for (const auto& traits : traitsList) {
386                 dump(out, traits) << std::endl;
387             }
388         }
389 
390         // Retrieve the list of active components.
391         std::list<std::shared_ptr<C2Component>> activeComps;
392         {
393             std::lock_guard<std::mutex> lock(mComponentRosterMutex);
394             auto i = mComponentRoster.begin();
395             while (i != mComponentRoster.end()) {
396                 std::shared_ptr<C2Component> c2comp = i->second.lock();
397                 if (!c2comp) {
398                     auto j = i;
399                     ++i;
400                     mComponentRoster.erase(j);
401                 } else {
402                     ++i;
403                     activeComps.emplace_back(c2comp);
404                 }
405             }
406         }
407 
408         // Dump active components.
409         out << indent << "Active components:" << std::endl << std::endl;
410         if (activeComps.size() == 0) {
411             out << indent << indent << "NONE" << std::endl << std::endl;
412         } else {
413             for (const std::shared_ptr<C2Component>& c2comp : activeComps) {
414                 dump(out, c2comp) << std::endl;
415             }
416         }
417 
418         out << "End of dump -- C2ComponentStore: "
419                 << mStore->getName() << std::endl;
420     }
421 
422     if (!android::base::WriteStringToFd(out.str(), h->data[0])) {
423         PLOG(WARNING) << "debug -- dumping failed -- write()";
424     } else {
425         LOG(INFO) << "debug -- dumping succeeded";
426     }
427     return Void();
428 }
429 
430 
431 }  // namespace utils
432 }  // namespace V1_0
433 }  // namespace c2
434 }  // namespace media
435 }  // namespace google
436 }  // namespace hardware
437