1 /*
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_NDEBUG 0
18 #define LOG_TAG "CCodec"
19 #include <utils/Log.h>
20 
21 #include <sstream>
22 #include <thread>
23 
24 #include <C2Config.h>
25 #include <C2Debug.h>
26 #include <C2ParamInternal.h>
27 #include <C2PlatformSupport.h>
28 
29 #include <android/IOMXBufferSource.h>
30 #include <android/hardware/media/c2/1.0/IInputSurface.h>
31 #include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32 #include <android/hardware/media/omx/1.0/IOmx.h>
33 #include <android-base/stringprintf.h>
34 #include <cutils/properties.h>
35 #include <gui/IGraphicBufferProducer.h>
36 #include <gui/Surface.h>
37 #include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
38 #include <media/omx/1.0/WOmxNode.h>
39 #include <media/openmax/OMX_Core.h>
40 #include <media/openmax/OMX_IndexExt.h>
41 #include <media/stagefright/foundation/avc_utils.h>
42 #include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
43 #include <media/stagefright/omx/OmxGraphicBufferSource.h>
44 #include <media/stagefright/CCodec.h>
45 #include <media/stagefright/BufferProducerWrapper.h>
46 #include <media/stagefright/MediaCodecConstants.h>
47 #include <media/stagefright/PersistentSurface.h>
48 #include <utils/NativeHandle.h>
49 
50 #include "C2OMXNode.h"
51 #include "CCodecBufferChannel.h"
52 #include "CCodecConfig.h"
53 #include "Codec2Mapper.h"
54 #include "InputSurfaceWrapper.h"
55 
56 extern "C" android::PersistentSurface *CreateInputSurface();
57 
58 namespace android {
59 
60 using namespace std::chrono_literals;
61 using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
62 using android::base::StringPrintf;
63 using ::android::hardware::media::c2::V1_0::IInputSurface;
64 
65 typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
66 typedef CCodecConfig Config;
67 
68 namespace {
69 
70 class CCodecWatchdog : public AHandler {
71 private:
72     enum {
73         kWhatWatch,
74     };
75     constexpr static int64_t kWatchIntervalUs = 3300000;  // 3.3 secs
76 
77 public:
getInstance()78     static sp<CCodecWatchdog> getInstance() {
79         static sp<CCodecWatchdog> instance(new CCodecWatchdog);
80         static std::once_flag flag;
81         // Call Init() only once.
82         std::call_once(flag, Init, instance);
83         return instance;
84     }
85 
86     ~CCodecWatchdog() = default;
87 
watch(sp<CCodec> codec)88     void watch(sp<CCodec> codec) {
89         bool shouldPost = false;
90         {
91             Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
92             // If a watch message is in flight, piggy-back this instance as well.
93             // Otherwise, post a new watch message.
94             shouldPost = codecs->empty();
95             codecs->emplace(codec);
96         }
97         if (shouldPost) {
98             ALOGV("posting watch message");
99             (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
100         }
101     }
102 
103 protected:
onMessageReceived(const sp<AMessage> & msg)104     void onMessageReceived(const sp<AMessage> &msg) {
105         switch (msg->what()) {
106             case kWhatWatch: {
107                 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
108                 ALOGV("watch for %zu codecs", codecs->size());
109                 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
110                     sp<CCodec> codec = it->promote();
111                     if (codec == nullptr) {
112                         continue;
113                     }
114                     codec->initiateReleaseIfStuck();
115                 }
116                 codecs->clear();
117                 break;
118             }
119 
120             default: {
121                 TRESPASS("CCodecWatchdog: unrecognized message");
122             }
123         }
124     }
125 
126 private:
CCodecWatchdog()127     CCodecWatchdog() : mLooper(new ALooper) {}
128 
Init(const sp<CCodecWatchdog> & thiz)129     static void Init(const sp<CCodecWatchdog> &thiz) {
130         ALOGV("Init");
131         thiz->mLooper->setName("CCodecWatchdog");
132         thiz->mLooper->registerHandler(thiz);
133         thiz->mLooper->start();
134     }
135 
136     sp<ALooper> mLooper;
137 
138     Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
139 };
140 
141 class C2InputSurfaceWrapper : public InputSurfaceWrapper {
142 public:
C2InputSurfaceWrapper(const std::shared_ptr<Codec2Client::InputSurface> & surface)143     explicit C2InputSurfaceWrapper(
144             const std::shared_ptr<Codec2Client::InputSurface> &surface) :
145         mSurface(surface) {
146     }
147 
148     ~C2InputSurfaceWrapper() override = default;
149 
connect(const std::shared_ptr<Codec2Client::Component> & comp)150     status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
151         if (mConnection != nullptr) {
152             return ALREADY_EXISTS;
153         }
154         return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
155     }
156 
disconnect()157     void disconnect() override {
158         if (mConnection != nullptr) {
159             mConnection->disconnect();
160             mConnection = nullptr;
161         }
162     }
163 
start()164     status_t start() override {
165         // InputSurface does not distinguish started state
166         return OK;
167     }
168 
signalEndOfInputStream()169     status_t signalEndOfInputStream() override {
170         C2InputSurfaceEosTuning eos(true);
171         std::vector<std::unique_ptr<C2SettingResult>> failures;
172         c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
173         if (err != C2_OK) {
174             return UNKNOWN_ERROR;
175         }
176         return OK;
177     }
178 
configure(Config & config __unused)179     status_t configure(Config &config __unused) {
180         // TODO
181         return OK;
182     }
183 
184 private:
185     std::shared_ptr<Codec2Client::InputSurface> mSurface;
186     std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
187 };
188 
189 class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
190 public:
191     typedef hardware::media::omx::V1_0::Status OmxStatus;
192 
GraphicBufferSourceWrapper(const sp<HGraphicBufferSource> & source,uint32_t width,uint32_t height,uint64_t usage)193     GraphicBufferSourceWrapper(
194             const sp<HGraphicBufferSource> &source,
195             uint32_t width,
196             uint32_t height,
197             uint64_t usage)
198         : mSource(source), mWidth(width), mHeight(height) {
199         mDataSpace = HAL_DATASPACE_BT709;
200         mConfig.mUsage = usage;
201     }
202     ~GraphicBufferSourceWrapper() override = default;
203 
connect(const std::shared_ptr<Codec2Client::Component> & comp)204     status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
205         mNode = new C2OMXNode(comp);
206         mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
207         mNode->setFrameSize(mWidth, mHeight);
208 
209         // Usage is queried during configure(), so setting it beforehand.
210         OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
211         (void)mNode->setParameter(
212                 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
213                 &usage, sizeof(usage));
214 
215         mSource->configure(
216                 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
217         return OK;
218     }
219 
disconnect()220     void disconnect() override {
221         if (mNode == nullptr) {
222             return;
223         }
224         sp<IOMXBufferSource> source = mNode->getSource();
225         if (source == nullptr) {
226             ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
227             return;
228         }
229         source->onOmxIdle();
230         source->onOmxLoaded();
231         mNode.clear();
232         mOmxNode.clear();
233     }
234 
GetStatus(hardware::Return<OmxStatus> && status)235     status_t GetStatus(hardware::Return<OmxStatus> &&status) {
236         if (status.isOk()) {
237             return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
238         } else if (status.isDeadObject()) {
239             return DEAD_OBJECT;
240         }
241         return UNKNOWN_ERROR;
242     }
243 
start()244     status_t start() override {
245         sp<IOMXBufferSource> source = mNode->getSource();
246         if (source == nullptr) {
247             return NO_INIT;
248         }
249 
250         size_t numSlots = 16;
251         constexpr OMX_U32 kPortIndexInput = 0;
252 
253         OMX_PARAM_PORTDEFINITIONTYPE param;
254         param.nPortIndex = kPortIndexInput;
255         status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
256                                            &param, sizeof(param));
257         if (err == OK) {
258             numSlots = param.nBufferCountActual;
259         }
260 
261         for (size_t i = 0; i < numSlots; ++i) {
262             source->onInputBufferAdded(i);
263         }
264 
265         source->onOmxExecuting();
266         return OK;
267     }
268 
signalEndOfInputStream()269     status_t signalEndOfInputStream() override {
270         return GetStatus(mSource->signalEndOfInputStream());
271     }
272 
configure(Config & config)273     status_t configure(Config &config) {
274         std::stringstream status;
275         status_t err = OK;
276 
277         // handle each configuration granually, in case we need to handle part of the configuration
278         // elsewhere
279 
280         // TRICKY: we do not unset frame delay repeating
281         if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
282             int64_t us = 1e6 / config.mMinFps + 0.5;
283             status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
284             status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
285             if (res != OK) {
286                 status << " (=> " << asString(res) << ")";
287                 err = res;
288             }
289             mConfig.mMinFps = config.mMinFps;
290         }
291 
292         // pts gap
293         if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
294             if (mNode != nullptr) {
295                 OMX_PARAM_U32TYPE ptrGapParam = {};
296                 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
297                 float gap = (config.mMinAdjustedFps > 0)
298                         ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
299                         : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
300                 // float -> uint32_t is undefined if the value is negative.
301                 // First convert to int32_t to ensure the expected behavior.
302                 ptrGapParam.nU32 = int32_t(gap);
303                 (void)mNode->setParameter(
304                         (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
305                         &ptrGapParam, sizeof(ptrGapParam));
306             }
307         }
308 
309         // max fps
310         // TRICKY: we do not unset max fps to 0 unless using fixed fps
311         if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
312                 && config.mMaxFps != mConfig.mMaxFps) {
313             status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
314             status << " maxFps=" << config.mMaxFps;
315             if (res != OK) {
316                 status << " (=> " << asString(res) << ")";
317                 err = res;
318             }
319             mConfig.mMaxFps = config.mMaxFps;
320         }
321 
322         if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
323             status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
324             status << " timeOffset " << config.mTimeOffsetUs << "us";
325             if (res != OK) {
326                 status << " (=> " << asString(res) << ")";
327                 err = res;
328             }
329             mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
330         }
331 
332         if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
333             status_t res =
334                 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
335             status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
336             if (res != OK) {
337                 status << " (=> " << asString(res) << ")";
338                 err = res;
339             }
340             mConfig.mCaptureFps = config.mCaptureFps;
341             mConfig.mCodedFps = config.mCodedFps;
342         }
343 
344         if (config.mStartAtUs != mConfig.mStartAtUs
345                 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
346             status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
347             status << " start at " << config.mStartAtUs << "us";
348             if (res != OK) {
349                 status << " (=> " << asString(res) << ")";
350                 err = res;
351             }
352             mConfig.mStartAtUs = config.mStartAtUs;
353             mConfig.mStopped = config.mStopped;
354         }
355 
356         // suspend-resume
357         if (config.mSuspended != mConfig.mSuspended) {
358             status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
359             status << " " << (config.mSuspended ? "suspend" : "resume")
360                     << " at " << config.mSuspendAtUs << "us";
361             if (res != OK) {
362                 status << " (=> " << asString(res) << ")";
363                 err = res;
364             }
365             mConfig.mSuspended = config.mSuspended;
366             mConfig.mSuspendAtUs = config.mSuspendAtUs;
367         }
368 
369         if (config.mStopped != mConfig.mStopped && config.mStopped) {
370             status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
371             status << " stop at " << config.mStopAtUs << "us";
372             if (res != OK) {
373                 status << " (=> " << asString(res) << ")";
374                 err = res;
375             } else {
376                 status << " delayUs";
377                 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
378                         [&res, &delayUs = config.mInputDelayUs](
379                                 auto status, auto stopTimeOffsetUs) {
380                             res = static_cast<status_t>(status);
381                             delayUs = stopTimeOffsetUs;
382                         });
383                 if (!trans.isOk()) {
384                     res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
385                 }
386                 if (res != OK) {
387                     status << " (=> " << asString(res) << ")";
388                 } else {
389                     status << "=" << config.mInputDelayUs << "us";
390                 }
391                 mConfig.mInputDelayUs = config.mInputDelayUs;
392             }
393             mConfig.mStopAtUs = config.mStopAtUs;
394             mConfig.mStopped = config.mStopped;
395         }
396 
397         // color aspects (android._color-aspects)
398 
399         // consumer usage is queried earlier.
400 
401         // priority
402         if (mConfig.mPriority != config.mPriority) {
403             if (config.mPriority != INT_MAX) {
404                 mNode->setPriority(config.mPriority);
405             }
406             mConfig.mPriority = config.mPriority;
407         }
408 
409         if (status.str().empty()) {
410             ALOGD("ISConfig not changed");
411         } else {
412             ALOGD("ISConfig%s", status.str().c_str());
413         }
414         return err;
415     }
416 
onInputBufferDone(c2_cntr64_t index)417     void onInputBufferDone(c2_cntr64_t index) override {
418         mNode->onInputBufferDone(index);
419     }
420 
getDataspace()421     android_dataspace getDataspace() override {
422         return mNode->getDataspace();
423     }
424 
425 private:
426     sp<HGraphicBufferSource> mSource;
427     sp<C2OMXNode> mNode;
428     sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
429     uint32_t mWidth;
430     uint32_t mHeight;
431     Config mConfig;
432 };
433 
434 class Codec2ClientInterfaceWrapper : public C2ComponentStore {
435     std::shared_ptr<Codec2Client> mClient;
436 
437 public:
Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)438     Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
439         : mClient(client) { }
440 
441     virtual ~Codec2ClientInterfaceWrapper() = default;
442 
config_sm(const std::vector<C2Param * > & params,std::vector<std::unique_ptr<C2SettingResult>> * const failures)443     virtual c2_status_t config_sm(
444             const std::vector<C2Param *> &params,
445             std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
446         return mClient->config(params, C2_MAY_BLOCK, failures);
447     };
448 
copyBuffer(std::shared_ptr<C2GraphicBuffer>,std::shared_ptr<C2GraphicBuffer>)449     virtual c2_status_t copyBuffer(
450             std::shared_ptr<C2GraphicBuffer>,
451             std::shared_ptr<C2GraphicBuffer>) {
452         return C2_OMITTED;
453     }
454 
createComponent(C2String,std::shared_ptr<C2Component> * const component)455     virtual c2_status_t createComponent(
456             C2String, std::shared_ptr<C2Component> *const component) {
457         component->reset();
458         return C2_OMITTED;
459     }
460 
createInterface(C2String,std::shared_ptr<C2ComponentInterface> * const interface)461     virtual c2_status_t createInterface(
462             C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
463         interface->reset();
464         return C2_OMITTED;
465     }
466 
query_sm(const std::vector<C2Param * > & stackParams,const std::vector<C2Param::Index> & heapParamIndices,std::vector<std::unique_ptr<C2Param>> * const heapParams) const467     virtual c2_status_t query_sm(
468             const std::vector<C2Param *> &stackParams,
469             const std::vector<C2Param::Index> &heapParamIndices,
470             std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
471         return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
472     }
473 
querySupportedParams_nb(std::vector<std::shared_ptr<C2ParamDescriptor>> * const params) const474     virtual c2_status_t querySupportedParams_nb(
475             std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
476         return mClient->querySupportedParams(params);
477     }
478 
querySupportedValues_sm(std::vector<C2FieldSupportedValuesQuery> & fields) const479     virtual c2_status_t querySupportedValues_sm(
480             std::vector<C2FieldSupportedValuesQuery> &fields) const {
481         return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
482     }
483 
getName() const484     virtual C2String getName() const {
485         return mClient->getName();
486     }
487 
getParamReflector() const488     virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
489         return mClient->getParamReflector();
490     }
491 
listComponents()492     virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
493         return std::vector<std::shared_ptr<const C2Component::Traits>>();
494     }
495 };
496 
RevertOutputFormatIfNeeded(const sp<AMessage> & oldFormat,sp<AMessage> & currentFormat)497 void RevertOutputFormatIfNeeded(
498         const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
499     // We used to not report changes to these keys to the client.
500     const static std::set<std::string> sIgnoredKeys({
501             KEY_BIT_RATE,
502             KEY_FRAME_RATE,
503             KEY_MAX_BIT_RATE,
504             KEY_MAX_WIDTH,
505             KEY_MAX_HEIGHT,
506             "csd-0",
507             "csd-1",
508             "csd-2",
509     });
510     if (currentFormat == oldFormat) {
511         return;
512     }
513     sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
514     AMessage::Type type;
515     for (size_t i = diff->countEntries(); i > 0; --i) {
516         if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
517             diff->removeEntryAt(i - 1);
518         }
519     }
520     if (diff->countEntries() == 0) {
521         currentFormat = oldFormat;
522     }
523 }
524 
AmendOutputFormatWithCodecSpecificData(const uint8_t * data,size_t size,const std::string & mediaType,const sp<AMessage> & outputFormat)525 void AmendOutputFormatWithCodecSpecificData(
526         const uint8_t *data, size_t size, const std::string &mediaType,
527         const sp<AMessage> &outputFormat) {
528     if (mediaType == MIMETYPE_VIDEO_AVC) {
529         // Codec specific data should be SPS and PPS in a single buffer,
530         // each prefixed by a startcode (0x00 0x00 0x00 0x01).
531         // We separate the two and put them into the output format
532         // under the keys "csd-0" and "csd-1".
533 
534         unsigned csdIndex = 0;
535 
536         const uint8_t *nalStart;
537         size_t nalSize;
538         while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
539             sp<ABuffer> csd = new ABuffer(nalSize + 4);
540             memcpy(csd->data(), "\x00\x00\x00\x01", 4);
541             memcpy(csd->data() + 4, nalStart, nalSize);
542 
543             outputFormat->setBuffer(
544                     AStringPrintf("csd-%u", csdIndex).c_str(), csd);
545 
546             ++csdIndex;
547         }
548 
549         if (csdIndex != 2) {
550             ALOGW("Expected two NAL units from AVC codec config, but %u found",
551                     csdIndex);
552         }
553     } else {
554         // For everything else we just stash the codec specific data into
555         // the output format as a single piece of csd under "csd-0".
556         sp<ABuffer> csd = new ABuffer(size);
557         memcpy(csd->data(), data, size);
558         csd->setRange(0, size);
559         outputFormat->setBuffer("csd-0", csd);
560     }
561 }
562 
563 }  // namespace
564 
565 // CCodec::ClientListener
566 
567 struct CCodec::ClientListener : public Codec2Client::Listener {
568 
ClientListenerandroid::CCodec::ClientListener569     explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
570 
onWorkDoneandroid::CCodec::ClientListener571     virtual void onWorkDone(
572             const std::weak_ptr<Codec2Client::Component>& component,
573             std::list<std::unique_ptr<C2Work>>& workItems) override {
574         (void)component;
575         sp<CCodec> codec(mCodec.promote());
576         if (!codec) {
577             return;
578         }
579         codec->onWorkDone(workItems);
580     }
581 
onTrippedandroid::CCodec::ClientListener582     virtual void onTripped(
583             const std::weak_ptr<Codec2Client::Component>& component,
584             const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
585             ) override {
586         // TODO
587         (void)component;
588         (void)settingResult;
589     }
590 
onErrorandroid::CCodec::ClientListener591     virtual void onError(
592             const std::weak_ptr<Codec2Client::Component>& component,
593             uint32_t errorCode) override {
594         {
595             // Component is only used for reporting as we use a separate listener for each instance
596             std::shared_ptr<Codec2Client::Component> comp = component.lock();
597             if (!comp) {
598                 ALOGD("Component died with error: 0x%x", errorCode);
599             } else {
600                 ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
601             }
602         }
603 
604         // Report to MediaCodec
605         // Note: for now we do not propagate the error code to MediaCodec
606         // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
607         sp<CCodec> codec(mCodec.promote());
608         if (!codec || !codec->mCallback) {
609             return;
610         }
611         codec->mCallback->onError(
612                 errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
613                 ACTION_CODE_FATAL);
614     }
615 
onDeathandroid::CCodec::ClientListener616     virtual void onDeath(
617             const std::weak_ptr<Codec2Client::Component>& component) override {
618         { // Log the death of the component.
619             std::shared_ptr<Codec2Client::Component> comp = component.lock();
620             if (!comp) {
621                 ALOGE("Codec2 component died.");
622             } else {
623                 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
624             }
625         }
626 
627         // Report to MediaCodec.
628         sp<CCodec> codec(mCodec.promote());
629         if (!codec || !codec->mCallback) {
630             return;
631         }
632         codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
633     }
634 
onFrameRenderedandroid::CCodec::ClientListener635     virtual void onFrameRendered(uint64_t bufferQueueId,
636                                  int32_t slotId,
637                                  int64_t timestampNs) override {
638         // TODO: implement
639         (void)bufferQueueId;
640         (void)slotId;
641         (void)timestampNs;
642     }
643 
onInputBufferDoneandroid::CCodec::ClientListener644     virtual void onInputBufferDone(
645             uint64_t frameIndex, size_t arrayIndex) override {
646         sp<CCodec> codec(mCodec.promote());
647         if (codec) {
648             codec->onInputBufferDone(frameIndex, arrayIndex);
649         }
650     }
651 
652 private:
653     wp<CCodec> mCodec;
654 };
655 
656 // CCodecCallbackImpl
657 
658 class CCodecCallbackImpl : public CCodecCallback {
659 public:
CCodecCallbackImpl(CCodec * codec)660     explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
661     ~CCodecCallbackImpl() override = default;
662 
onError(status_t err,enum ActionCode actionCode)663     void onError(status_t err, enum ActionCode actionCode) override {
664         mCodec->mCallback->onError(err, actionCode);
665     }
666 
onOutputFramesRendered(int64_t mediaTimeUs,nsecs_t renderTimeNs)667     void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
668         mCodec->mCallback->onOutputFramesRendered(
669                 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
670     }
671 
onOutputBuffersChanged()672     void onOutputBuffersChanged() override {
673         mCodec->mCallback->onOutputBuffersChanged();
674     }
675 
onFirstTunnelFrameReady()676     void onFirstTunnelFrameReady() override {
677         mCodec->mCallback->onFirstTunnelFrameReady();
678     }
679 
680 private:
681     CCodec *mCodec;
682 };
683 
684 // CCodec
685 
CCodec()686 CCodec::CCodec()
687     : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
688       mConfig(new CCodecConfig) {
689 }
690 
~CCodec()691 CCodec::~CCodec() {
692 }
693 
getBufferChannel()694 std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
695     return mChannel;
696 }
697 
tryAndReportOnError(std::function<status_t ()> job)698 status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
699     status_t err = job();
700     if (err != C2_OK) {
701         mCallback->onError(err, ACTION_CODE_FATAL);
702     }
703     return err;
704 }
705 
initiateAllocateComponent(const sp<AMessage> & msg)706 void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
707     auto setAllocating = [this] {
708         Mutexed<State>::Locked state(mState);
709         if (state->get() != RELEASED) {
710             return INVALID_OPERATION;
711         }
712         state->set(ALLOCATING);
713         return OK;
714     };
715     if (tryAndReportOnError(setAllocating) != OK) {
716         return;
717     }
718 
719     sp<RefBase> codecInfo;
720     CHECK(msg->findObject("codecInfo", &codecInfo));
721     // For Codec 2.0 components, componentName == codecInfo->getCodecName().
722 
723     sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
724     allocMsg->setObject("codecInfo", codecInfo);
725     allocMsg->post();
726 }
727 
allocate(const sp<MediaCodecInfo> & codecInfo)728 void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
729     if (codecInfo == nullptr) {
730         mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
731         return;
732     }
733     ALOGD("allocate(%s)", codecInfo->getCodecName());
734     mClientListener.reset(new ClientListener(this));
735 
736     AString componentName = codecInfo->getCodecName();
737     std::shared_ptr<Codec2Client> client;
738 
739     // set up preferred component store to access vendor store parameters
740     client = Codec2Client::CreateFromService("default");
741     if (client) {
742         ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
743         SetPreferredCodec2ComponentStore(
744                 std::make_shared<Codec2ClientInterfaceWrapper>(client));
745     }
746 
747     std::shared_ptr<Codec2Client::Component> comp;
748     c2_status_t status = Codec2Client::CreateComponentByName(
749             componentName.c_str(),
750             mClientListener,
751             &comp,
752             &client);
753     if (status != C2_OK) {
754         ALOGE("Failed Create component: %s, error=%d", componentName.c_str(), status);
755         Mutexed<State>::Locked state(mState);
756         state->set(RELEASED);
757         state.unlock();
758         mCallback->onError((status == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR), ACTION_CODE_FATAL);
759         state.lock();
760         return;
761     }
762     ALOGI("Created component [%s]", componentName.c_str());
763     mChannel->setComponent(comp);
764     auto setAllocated = [this, comp, client] {
765         Mutexed<State>::Locked state(mState);
766         if (state->get() != ALLOCATING) {
767             state->set(RELEASED);
768             return UNKNOWN_ERROR;
769         }
770         state->set(ALLOCATED);
771         state->comp = comp;
772         mClient = client;
773         return OK;
774     };
775     if (tryAndReportOnError(setAllocated) != OK) {
776         return;
777     }
778 
779     // initialize config here in case setParameters is called prior to configure
780     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
781     const std::unique_ptr<Config> &config = *configLocked;
782     status_t err = config->initialize(mClient->getParamReflector(), comp);
783     if (err != OK) {
784         ALOGW("Failed to initialize configuration support");
785         // TODO: report error once we complete implementation.
786     }
787     config->queryConfiguration(comp);
788 
789     mCallback->onComponentAllocated(componentName.c_str());
790 }
791 
initiateConfigureComponent(const sp<AMessage> & format)792 void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
793     auto checkAllocated = [this] {
794         Mutexed<State>::Locked state(mState);
795         return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
796     };
797     if (tryAndReportOnError(checkAllocated) != OK) {
798         return;
799     }
800 
801     sp<AMessage> msg(new AMessage(kWhatConfigure, this));
802     msg->setMessage("format", format);
803     msg->post();
804 }
805 
configure(const sp<AMessage> & msg)806 void CCodec::configure(const sp<AMessage> &msg) {
807     std::shared_ptr<Codec2Client::Component> comp;
808     auto checkAllocated = [this, &comp] {
809         Mutexed<State>::Locked state(mState);
810         if (state->get() != ALLOCATED) {
811             state->set(RELEASED);
812             return UNKNOWN_ERROR;
813         }
814         comp = state->comp;
815         return OK;
816     };
817     if (tryAndReportOnError(checkAllocated) != OK) {
818         return;
819     }
820 
821     auto doConfig = [msg, comp, this]() -> status_t {
822         AString mime;
823         if (!msg->findString("mime", &mime)) {
824             return BAD_VALUE;
825         }
826 
827         int32_t encoder;
828         if (!msg->findInt32("encoder", &encoder)) {
829             encoder = false;
830         }
831 
832         int32_t flags;
833         if (!msg->findInt32("flags", &flags)) {
834             return BAD_VALUE;
835         }
836 
837         // TODO: read from intf()
838         if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
839             return UNKNOWN_ERROR;
840         }
841 
842         int32_t storeMeta;
843         if (encoder
844                 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
845                 && storeMeta != kMetadataBufferTypeInvalid) {
846             if (storeMeta != kMetadataBufferTypeANWBuffer) {
847                 ALOGD("Only ANW buffers are supported for legacy metadata mode");
848                 return BAD_VALUE;
849             }
850             mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
851         }
852 
853         status_t err = OK;
854         sp<RefBase> obj;
855         sp<Surface> surface;
856         if (msg->findObject("native-window", &obj)) {
857             surface = static_cast<Surface *>(obj.get());
858             // setup tunneled playback
859             if (surface != nullptr) {
860                 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
861                 const std::unique_ptr<Config> &config = *configLocked;
862                 if ((config->mDomain & Config::IS_DECODER)
863                         && (config->mDomain & Config::IS_VIDEO)) {
864                     int32_t tunneled;
865                     if (msg->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
866                         ALOGI("Configuring TUNNELED video playback.");
867 
868                         err = configureTunneledVideoPlayback(comp, &config->mSidebandHandle, msg);
869                         if (err != OK) {
870                             ALOGE("configureTunneledVideoPlayback failed!");
871                             return err;
872                         }
873                         config->mTunneled = true;
874                     }
875                 }
876             }
877             setSurface(surface);
878         }
879 
880         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
881         const std::unique_ptr<Config> &config = *configLocked;
882         config->mUsingSurface = surface != nullptr;
883         config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
884         ALOGD("[%s] buffers are %sbound to CCodec for this session",
885               comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
886 
887         // Enforce required parameters
888         int32_t i32;
889         float flt;
890         if (config->mDomain & Config::IS_AUDIO) {
891             if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
892                 ALOGD("sample rate is missing, which is required for audio components.");
893                 return BAD_VALUE;
894             }
895             if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
896                 ALOGD("channel count is missing, which is required for audio components.");
897                 return BAD_VALUE;
898             }
899             if ((config->mDomain & Config::IS_ENCODER)
900                     && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
901                     && !msg->findInt32(KEY_BIT_RATE, &i32)
902                     && !msg->findFloat(KEY_BIT_RATE, &flt)) {
903                 ALOGD("bitrate is missing, which is required for audio encoders.");
904                 return BAD_VALUE;
905             }
906         }
907         int32_t width = 0;
908         int32_t height = 0;
909         if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
910             if (!msg->findInt32(KEY_WIDTH, &width)) {
911                 ALOGD("width is missing, which is required for image/video components.");
912                 return BAD_VALUE;
913             }
914             if (!msg->findInt32(KEY_HEIGHT, &height)) {
915                 ALOGD("height is missing, which is required for image/video components.");
916                 return BAD_VALUE;
917             }
918             if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
919                 int32_t mode = BITRATE_MODE_VBR;
920                 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
921                     if (!msg->findInt32(KEY_QUALITY, &i32)) {
922                         ALOGD("quality is missing, which is required for video encoders in CQ.");
923                         return BAD_VALUE;
924                     }
925                 } else {
926                     if (!msg->findInt32(KEY_BIT_RATE, &i32)
927                             && !msg->findFloat(KEY_BIT_RATE, &flt)) {
928                         ALOGD("bitrate is missing, which is required for video encoders.");
929                         return BAD_VALUE;
930                     }
931                 }
932                 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
933                         && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
934                     ALOGD("I frame interval is missing, which is required for video encoders.");
935                     return BAD_VALUE;
936                 }
937                 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
938                         && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
939                     ALOGD("frame rate is missing, which is required for video encoders.");
940                     return BAD_VALUE;
941                 }
942             }
943         }
944 
945         /*
946          * Handle input surface configuration
947          */
948         if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
949                 && (config->mDomain & Config::IS_ENCODER)) {
950             config->mISConfig.reset(new InputSurfaceWrapper::Config{});
951             {
952                 config->mISConfig->mMinFps = 0;
953                 int64_t value;
954                 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
955                     config->mISConfig->mMinFps = 1e6 / value;
956                 }
957                 if (!msg->findFloat(
958                         KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
959                     config->mISConfig->mMaxFps = -1;
960                 }
961                 config->mISConfig->mMinAdjustedFps = 0;
962                 config->mISConfig->mFixedAdjustedFps = 0;
963                 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
964                     if (value < 0 && value >= INT32_MIN) {
965                         config->mISConfig->mFixedAdjustedFps = -1e6 / value;
966                         config->mISConfig->mMaxFps = -1;
967                     } else if (value > 0 && value <= INT32_MAX) {
968                         config->mISConfig->mMinAdjustedFps = 1e6 / value;
969                     }
970                 }
971             }
972 
973             {
974                 bool captureFpsFound = false;
975                 double timeLapseFps;
976                 float captureRate;
977                 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
978                     config->mISConfig->mCaptureFps = timeLapseFps;
979                     captureFpsFound = true;
980                 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
981                     config->mISConfig->mCaptureFps = captureRate;
982                     captureFpsFound = true;
983                 }
984                 if (captureFpsFound) {
985                     (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
986                 }
987             }
988 
989             {
990                 config->mISConfig->mSuspended = false;
991                 config->mISConfig->mSuspendAtUs = -1;
992                 int32_t value;
993                 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
994                     config->mISConfig->mSuspended = true;
995                 }
996             }
997             config->mISConfig->mUsage = 0;
998             config->mISConfig->mPriority = INT_MAX;
999         }
1000 
1001         /*
1002          * Handle desired color format.
1003          */
1004         int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
1005         if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1006             int32_t format = 0;
1007             // Query vendor format for Flexible YUV
1008             std::vector<std::unique_ptr<C2Param>> heapParams;
1009             C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
1010             if (mClient->query(
1011                         {},
1012                         {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
1013                         C2_MAY_BLOCK,
1014                         &heapParams) == C2_OK
1015                     && heapParams.size() == 1u) {
1016                 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
1017                         heapParams[0].get());
1018             } else {
1019                 pixelFormatInfo = nullptr;
1020             }
1021             std::optional<uint32_t> flexPixelFormat{};
1022             std::optional<uint32_t> flexPlanarPixelFormat{};
1023             std::optional<uint32_t> flexSemiPlanarPixelFormat{};
1024             if (pixelFormatInfo && *pixelFormatInfo) {
1025                 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
1026                     const C2FlexiblePixelFormatDescriptorStruct &desc =
1027                         pixelFormatInfo->m.values[i];
1028                     if (desc.bitDepth != 8
1029                             || desc.subsampling != C2Color::YUV_420
1030                             // TODO(b/180076105): some device report wrong layout
1031                             // || desc.layout == C2Color::INTERLEAVED_PACKED
1032                             // || desc.layout == C2Color::INTERLEAVED_ALIGNED
1033                             || desc.layout == C2Color::UNKNOWN_LAYOUT) {
1034                         continue;
1035                     }
1036                     if (!flexPixelFormat) {
1037                         flexPixelFormat = desc.pixelFormat;
1038                     }
1039                     if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
1040                         flexPlanarPixelFormat = desc.pixelFormat;
1041                     }
1042                     if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
1043                         flexSemiPlanarPixelFormat = desc.pixelFormat;
1044                     }
1045                 }
1046             }
1047             if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1048                 // Also handle default color format (encoders require color format, so this is only
1049                 // needed for decoders.
1050                 if (!(config->mDomain & Config::IS_ENCODER)) {
1051                     if (surface == nullptr) {
1052                         const char *prefix = "";
1053                         if (flexSemiPlanarPixelFormat) {
1054                             format = COLOR_FormatYUV420SemiPlanar;
1055                             prefix = "semi-";
1056                         } else {
1057                             format = COLOR_FormatYUV420Planar;
1058                         }
1059                         ALOGD("Client requested ByteBuffer mode decoder w/o color format set: "
1060                                 "using default %splanar color format", prefix);
1061                     } else {
1062                         format = COLOR_FormatSurface;
1063                     }
1064                     defaultColorFormat = format;
1065                 }
1066             } else {
1067                 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
1068                     switch (format) {
1069                         case COLOR_FormatYUV420Flexible:
1070                             format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
1071                             break;
1072                         case COLOR_FormatYUV420Planar:
1073                         case COLOR_FormatYUV420PackedPlanar:
1074                             format = flexPlanarPixelFormat.value_or(
1075                                     flexPixelFormat.value_or(format));
1076                             break;
1077                         case COLOR_FormatYUV420SemiPlanar:
1078                         case COLOR_FormatYUV420PackedSemiPlanar:
1079                             format = flexSemiPlanarPixelFormat.value_or(
1080                                     flexPixelFormat.value_or(format));
1081                             break;
1082                         default:
1083                             // No-op
1084                             break;
1085                     }
1086                 }
1087             }
1088 
1089             if (format != 0) {
1090                 msg->setInt32("android._color-format", format);
1091             }
1092         }
1093 
1094         /*
1095          * Handle dataspace
1096          */
1097         int32_t usingRecorder;
1098         if (msg->findInt32("android._using-recorder", &usingRecorder) && usingRecorder) {
1099             android_dataspace dataSpace = HAL_DATASPACE_BT709;
1100             int32_t width, height;
1101             if (msg->findInt32("width", &width)
1102                     && msg->findInt32("height", &height)) {
1103                 ColorAspects aspects;
1104                 getColorAspectsFromFormat(msg, aspects);
1105                 setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
1106                 // TODO: read dataspace / color aspect from the component
1107                 setColorAspectsIntoFormat(aspects, const_cast<sp<AMessage> &>(msg));
1108                 dataSpace = getDataSpaceForColorAspects(aspects, true /* mayexpand */);
1109             }
1110             msg->setInt32("android._dataspace", (int32_t)dataSpace);
1111             ALOGD("setting dataspace to %x", dataSpace);
1112         }
1113 
1114         int32_t subscribeToAllVendorParams;
1115         if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
1116             if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
1117                 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
1118             }
1119         }
1120 
1121         std::vector<std::unique_ptr<C2Param>> configUpdate;
1122         // NOTE: We used to ignore "video-bitrate" at configure; replicate
1123         //       the behavior here.
1124         sp<AMessage> sdkParams = msg;
1125         int32_t videoBitrate;
1126         if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
1127             sdkParams = msg->dup();
1128             sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
1129         }
1130         err = config->getConfigUpdateFromSdkParams(
1131                 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
1132         if (err != OK) {
1133             ALOGW("failed to convert configuration to c2 params");
1134         }
1135 
1136         int32_t maxBframes = 0;
1137         if ((config->mDomain & Config::IS_ENCODER)
1138                 && (config->mDomain & Config::IS_VIDEO)
1139                 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
1140                 && maxBframes > 0) {
1141             std::unique_ptr<C2StreamGopTuning::output> gop =
1142                 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
1143             gop->m.values[0] = { P_FRAME, UINT32_MAX };
1144             gop->m.values[1] = {
1145                 C2Config::picture_type_t(P_FRAME | B_FRAME),
1146                 uint32_t(maxBframes)
1147             };
1148             configUpdate.push_back(std::move(gop));
1149         }
1150 
1151         if ((config->mDomain & Config::IS_ENCODER)
1152                 && (config->mDomain & Config::IS_VIDEO)) {
1153             // we may not use all 3 of these entries
1154             std::unique_ptr<C2StreamPictureQuantizationTuning::output> qp =
1155                 C2StreamPictureQuantizationTuning::output::AllocUnique(3 /* flexCount */,
1156                                                                        0u /* stream */);
1157 
1158             int ix = 0;
1159 
1160             int32_t iMax = INT32_MAX;
1161             int32_t iMin = INT32_MIN;
1162             (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MAX, &iMax);
1163             (void) sdkParams->findInt32(KEY_VIDEO_QP_I_MIN, &iMin);
1164             if (iMax != INT32_MAX || iMin != INT32_MIN) {
1165                 qp->m.values[ix++] = {I_FRAME, iMin, iMax};
1166             }
1167 
1168             int32_t pMax = INT32_MAX;
1169             int32_t pMin = INT32_MIN;
1170             (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MAX, &pMax);
1171             (void) sdkParams->findInt32(KEY_VIDEO_QP_P_MIN, &pMin);
1172             if (pMax != INT32_MAX || pMin != INT32_MIN) {
1173                 qp->m.values[ix++] = {P_FRAME, pMin, pMax};
1174             }
1175 
1176             int32_t bMax = INT32_MAX;
1177             int32_t bMin = INT32_MIN;
1178             (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MAX, &bMax);
1179             (void) sdkParams->findInt32(KEY_VIDEO_QP_B_MIN, &bMin);
1180             if (bMax != INT32_MAX || bMin != INT32_MIN) {
1181                 qp->m.values[ix++] = {B_FRAME, bMin, bMax};
1182             }
1183 
1184             // adjust to reflect actual use.
1185             qp->setFlexCount(ix);
1186 
1187             configUpdate.push_back(std::move(qp));
1188         }
1189 
1190         int32_t background = 0;
1191         if ((config->mDomain & Config::IS_VIDEO)
1192                 && msg->findInt32("android._background-mode", &background)
1193                 && background) {
1194             androidSetThreadPriority(gettid(), ANDROID_PRIORITY_BACKGROUND);
1195             if (config->mISConfig) {
1196                 config->mISConfig->mPriority = ANDROID_PRIORITY_BACKGROUND;
1197             }
1198         }
1199 
1200         err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1201         if (err != OK) {
1202             ALOGW("failed to configure c2 params");
1203             return err;
1204         }
1205 
1206         std::vector<std::unique_ptr<C2Param>> params;
1207         C2StreamUsageTuning::input usage(0u, 0u);
1208         C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
1209         C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
1210 
1211         C2Param::Index colorAspectsRequestIndex =
1212             C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
1213         std::initializer_list<C2Param::Index> indices {
1214             colorAspectsRequestIndex.withStream(0u),
1215         };
1216         c2_status_t c2err = comp->query(
1217                 { &usage, &maxInputSize, &prepend },
1218                 indices,
1219                 C2_DONT_BLOCK,
1220                 &params);
1221         if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1222             ALOGE("Failed to query component interface: %d", c2err);
1223             return UNKNOWN_ERROR;
1224         }
1225         if (usage) {
1226             if (usage.value & C2MemoryUsage::CPU_READ) {
1227                 config->mInputFormat->setInt32("using-sw-read-often", true);
1228             }
1229             if (config->mISConfig) {
1230                 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1231                 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1232             }
1233             config->mInputFormat->setInt64("android._C2MemoryUsage", usage.value);
1234         }
1235 
1236         // NOTE: we don't blindly use client specified input size if specified as clients
1237         // at times specify too small size. Instead, mimic the behavior from OMX, where the
1238         // client specified size is only used to ask for bigger buffers than component suggested
1239         // size.
1240         int32_t clientInputSize = 0;
1241         bool clientSpecifiedInputSize =
1242             msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1243         // TEMP: enforce minimum buffer size of 1MB for video decoders
1244         // and 16K / 4K for audio encoders/decoders
1245         if (maxInputSize.value == 0) {
1246             if (config->mDomain & Config::IS_AUDIO) {
1247                 maxInputSize.value = encoder ? 16384 : 4096;
1248             } else if (!encoder) {
1249                 maxInputSize.value = 1048576u;
1250             }
1251         }
1252 
1253         // verify that CSD fits into this size (if defined)
1254         if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1255             sp<ABuffer> csd;
1256             for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1257                 if (csd && csd->size() > maxInputSize.value) {
1258                     maxInputSize.value = csd->size();
1259                 }
1260             }
1261         }
1262 
1263         // TODO: do this based on component requiring linear allocator for input
1264         if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1265             if (clientSpecifiedInputSize) {
1266                 // Warn that we're overriding client's max input size if necessary.
1267                 if ((uint32_t)clientInputSize < maxInputSize.value) {
1268                     ALOGD("client requested max input size %d, which is smaller than "
1269                           "what component recommended (%u); overriding with component "
1270                           "recommendation.", clientInputSize, maxInputSize.value);
1271                     ALOGW("This behavior is subject to change. It is recommended that "
1272                           "app developers double check whether the requested "
1273                           "max input size is in reasonable range.");
1274                 } else {
1275                     maxInputSize.value = clientInputSize;
1276                 }
1277             }
1278             // Pass max input size on input format to the buffer channel (if supplied by the
1279             // component or by a default)
1280             if (maxInputSize.value) {
1281                 config->mInputFormat->setInt32(
1282                         KEY_MAX_INPUT_SIZE,
1283                         (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1284             }
1285         }
1286 
1287         int32_t clientPrepend;
1288         if ((config->mDomain & Config::IS_VIDEO)
1289                 && (config->mDomain & Config::IS_ENCODER)
1290                 && msg->findInt32(KEY_PREPEND_HEADER_TO_SYNC_FRAMES, &clientPrepend)
1291                 && clientPrepend
1292                 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1293             ALOGE("Failed to set KEY_PREPEND_HEADER_TO_SYNC_FRAMES");
1294             return BAD_VALUE;
1295         }
1296 
1297         int32_t componentColorFormat = 0;
1298         if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1299             // propagate HDR static info to output format for both encoders and decoders
1300             // if component supports this info, we will update from component, but only the raw port,
1301             // so don't propagate if component already filled it in.
1302             sp<ABuffer> hdrInfo;
1303             if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1304                     && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1305                 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1306             }
1307 
1308             // Set desired color format from configuration parameter
1309             int32_t format;
1310             if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1311                 format = defaultColorFormat;
1312             }
1313             if (config->mDomain & Config::IS_ENCODER) {
1314                 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1315                 if (msg->findInt32("android._color-format", &componentColorFormat)) {
1316                     config->mInputFormat->setInt32("android._color-format", componentColorFormat);
1317                 }
1318             } else {
1319                 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1320             }
1321         }
1322 
1323         // propagate encoder delay and padding to output format
1324         if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1325             int delay = 0;
1326             if (msg->findInt32("encoder-delay", &delay)) {
1327                 config->mOutputFormat->setInt32("encoder-delay", delay);
1328             }
1329             int padding = 0;
1330             if (msg->findInt32("encoder-padding", &padding)) {
1331                 config->mOutputFormat->setInt32("encoder-padding", padding);
1332             }
1333         }
1334 
1335         // set channel-mask
1336         if (config->mDomain & Config::IS_AUDIO) {
1337             int32_t mask;
1338             if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1339                 if (config->mDomain & Config::IS_ENCODER) {
1340                     config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1341                 } else {
1342                     config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1343                 }
1344             }
1345         }
1346 
1347         std::unique_ptr<C2Param> colorTransferRequestParam;
1348         for (std::unique_ptr<C2Param> &param : params) {
1349             if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
1350                 ALOGI("found color transfer request param");
1351                 colorTransferRequestParam = std::move(param);
1352             }
1353         }
1354         int32_t colorTransferRequest = 0;
1355         if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
1356                 && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
1357             colorTransferRequest = 0;
1358         }
1359 
1360         if (colorTransferRequest != 0) {
1361             if (colorTransferRequestParam && *colorTransferRequestParam) {
1362                 C2StreamColorAspectsInfo::output *info =
1363                     static_cast<C2StreamColorAspectsInfo::output *>(
1364                             colorTransferRequestParam.get());
1365                 if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
1366                     colorTransferRequest = 0;
1367                 }
1368             } else {
1369                 colorTransferRequest = 0;
1370             }
1371             config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
1372         }
1373 
1374         if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
1375             // Need to get stride/vstride
1376             uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1377             if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
1378                 // TODO: retrieve these values without allocating a buffer.
1379                 //       Currently allocating a buffer is necessary to retrieve the layout.
1380                 int64_t blockUsage =
1381                     usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
1382                 std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
1383                         width, height, pixelFormat, blockUsage, {comp->getName()});
1384                 sp<GraphicBlockBuffer> buffer;
1385                 if (block) {
1386                     buffer = GraphicBlockBuffer::Allocate(
1387                             config->mInputFormat,
1388                             block,
1389                             [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
1390                 } else {
1391                     ALOGD("Failed to allocate a graphic block "
1392                             "(width=%d height=%d pixelFormat=%u usage=%llx)",
1393                             width, height, pixelFormat, (long long)blockUsage);
1394                     // This means that byte buffer mode is not supported in this configuration
1395                     // anyway. Skip setting stride/vstride to input format.
1396                 }
1397                 if (buffer) {
1398                     sp<ABuffer> imageData = buffer->getImageData();
1399                     MediaImage2 *img = nullptr;
1400                     if (imageData && imageData->data()
1401                             && imageData->size() >= sizeof(MediaImage2)) {
1402                         img = (MediaImage2*)imageData->data();
1403                     }
1404                     if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
1405                         int32_t stride = img->mPlane[0].mRowInc;
1406                         config->mInputFormat->setInt32(KEY_STRIDE, stride);
1407                         if (img->mNumPlanes > 1 && stride > 0) {
1408                             int64_t offsetDelta =
1409                                 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
1410                             if (offsetDelta % stride == 0) {
1411                                 int32_t vstride = int32_t(offsetDelta / stride);
1412                                 config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
1413                             } else {
1414                                 ALOGD("Cannot report accurate slice height: "
1415                                         "offsetDelta = %lld stride = %d",
1416                                         (long long)offsetDelta, stride);
1417                             }
1418                         }
1419                     }
1420                 }
1421             }
1422         }
1423 
1424         ALOGD("setup formats input: %s",
1425                 config->mInputFormat->debugString().c_str());
1426         ALOGD("setup formats output: %s",
1427                 config->mOutputFormat->debugString().c_str());
1428         return OK;
1429     };
1430     if (tryAndReportOnError(doConfig) != OK) {
1431         return;
1432     }
1433 
1434     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1435     const std::unique_ptr<Config> &config = *configLocked;
1436 
1437     config->queryConfiguration(comp);
1438 
1439     mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1440 }
1441 
initiateCreateInputSurface()1442 void CCodec::initiateCreateInputSurface() {
1443     status_t err = [this] {
1444         Mutexed<State>::Locked state(mState);
1445         if (state->get() != ALLOCATED) {
1446             return UNKNOWN_ERROR;
1447         }
1448         // TODO: read it from intf() properly.
1449         if (state->comp->getName().find("encoder") == std::string::npos) {
1450             return INVALID_OPERATION;
1451         }
1452         return OK;
1453     }();
1454     if (err != OK) {
1455         mCallback->onInputSurfaceCreationFailed(err);
1456         return;
1457     }
1458 
1459     (new AMessage(kWhatCreateInputSurface, this))->post();
1460 }
1461 
CreateOmxInputSurface()1462 sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1463     using namespace android::hardware::media::omx::V1_0;
1464     using namespace android::hardware::media::omx::V1_0::utils;
1465     using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1466     typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1467     android::sp<IOmx> omx = IOmx::getService();
1468     typedef android::hardware::graphics::bufferqueue::V1_0::
1469             IGraphicBufferProducer HGraphicBufferProducer;
1470     typedef android::hardware::media::omx::V1_0::
1471             IGraphicBufferSource HGraphicBufferSource;
1472     OmxStatus s;
1473     android::sp<HGraphicBufferProducer> gbp;
1474     android::sp<HGraphicBufferSource> gbs;
1475 
1476     using ::android::hardware::Return;
1477     Return<void> transStatus = omx->createInputSurface(
1478             [&s, &gbp, &gbs](
1479                     OmxStatus status,
1480                     const android::sp<HGraphicBufferProducer>& producer,
1481                     const android::sp<HGraphicBufferSource>& source) {
1482                 s = status;
1483                 gbp = producer;
1484                 gbs = source;
1485             });
1486     if (transStatus.isOk() && s == OmxStatus::OK) {
1487         return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
1488     }
1489 
1490     return nullptr;
1491 }
1492 
CreateCompatibleInputSurface()1493 sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1494     sp<PersistentSurface> surface(CreateInputSurface());
1495 
1496     if (surface == nullptr) {
1497         surface = CreateOmxInputSurface();
1498     }
1499 
1500     return surface;
1501 }
1502 
createInputSurface()1503 void CCodec::createInputSurface() {
1504     status_t err;
1505     sp<IGraphicBufferProducer> bufferProducer;
1506 
1507     sp<AMessage> outputFormat;
1508     uint64_t usage = 0;
1509     {
1510         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1511         const std::unique_ptr<Config> &config = *configLocked;
1512         outputFormat = config->mOutputFormat;
1513         usage = config->mISConfig ? config->mISConfig->mUsage : 0;
1514     }
1515 
1516     sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
1517     sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1518     sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1519     sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1520 
1521     if (hidlInputSurface) {
1522         std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1523                 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
1524         err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1525                 inputSurface));
1526         bufferProducer = inputSurface->getGraphicBufferProducer();
1527     } else if (gbs) {
1528         int32_t width = 0;
1529         (void)outputFormat->findInt32("width", &width);
1530         int32_t height = 0;
1531         (void)outputFormat->findInt32("height", &height);
1532         err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1533                 gbs, width, height, usage));
1534         bufferProducer = persistentSurface->getBufferProducer();
1535     } else {
1536         ALOGE("Corrupted input surface");
1537         mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1538         return;
1539     }
1540 
1541     if (err != OK) {
1542         ALOGE("Failed to set up input surface: %d", err);
1543         mCallback->onInputSurfaceCreationFailed(err);
1544         return;
1545     }
1546 
1547     // Formats can change after setupInputSurface
1548     sp<AMessage> inputFormat;
1549     {
1550         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1551         const std::unique_ptr<Config> &config = *configLocked;
1552         inputFormat = config->mInputFormat;
1553         outputFormat = config->mOutputFormat;
1554     }
1555     mCallback->onInputSurfaceCreated(
1556             inputFormat,
1557             outputFormat,
1558             new BufferProducerWrapper(bufferProducer));
1559 }
1560 
setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> & surface)1561 status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1562     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1563     const std::unique_ptr<Config> &config = *configLocked;
1564     config->mUsingSurface = true;
1565 
1566     // we are now using surface - apply default color aspects to input format - as well as
1567     // get dataspace
1568     bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
1569 
1570     // configure dataspace
1571     static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1572 
1573     // The output format contains app-configured color aspects, and the input format
1574     // has the default color aspects. Use the default for the unspecified params.
1575     ColorAspects inputColorAspects, colorAspects;
1576     getColorAspectsFromFormat(config->mOutputFormat, colorAspects);
1577     getColorAspectsFromFormat(config->mInputFormat, inputColorAspects);
1578     if (colorAspects.mRange == ColorAspects::RangeUnspecified) {
1579         colorAspects.mRange = inputColorAspects.mRange;
1580     }
1581     if (colorAspects.mPrimaries == ColorAspects::PrimariesUnspecified) {
1582         colorAspects.mPrimaries = inputColorAspects.mPrimaries;
1583     }
1584     if (colorAspects.mTransfer == ColorAspects::TransferUnspecified) {
1585         colorAspects.mTransfer = inputColorAspects.mTransfer;
1586     }
1587     if (colorAspects.mMatrixCoeffs == ColorAspects::MatrixUnspecified) {
1588         colorAspects.mMatrixCoeffs = inputColorAspects.mMatrixCoeffs;
1589     }
1590     android_dataspace dataSpace = getDataSpaceForColorAspects(
1591             colorAspects, /* mayExtend = */ false);
1592     surface->setDataSpace(dataSpace);
1593     setColorAspectsIntoFormat(colorAspects, config->mInputFormat, /* force = */ true);
1594     config->mInputFormat->setInt32("android._dataspace", int32_t(dataSpace));
1595 
1596     ALOGD("input format %s to %s",
1597             inputFormatChanged ? "changed" : "unchanged",
1598             config->mInputFormat->debugString().c_str());
1599 
1600     status_t err = mChannel->setInputSurface(surface);
1601     if (err != OK) {
1602         // undo input format update
1603         config->mUsingSurface = false;
1604         (void)config->updateFormats(Config::IS_INPUT);
1605         return err;
1606     }
1607     config->mInputSurface = surface;
1608 
1609     if (config->mISConfig) {
1610         surface->configure(*config->mISConfig);
1611     } else {
1612         ALOGD("ISConfig: no configuration");
1613     }
1614 
1615     return OK;
1616 }
1617 
initiateSetInputSurface(const sp<PersistentSurface> & surface)1618 void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1619     sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1620     msg->setObject("surface", surface);
1621     msg->post();
1622 }
1623 
setInputSurface(const sp<PersistentSurface> & surface)1624 void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1625     sp<AMessage> outputFormat;
1626     uint64_t usage = 0;
1627     {
1628         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1629         const std::unique_ptr<Config> &config = *configLocked;
1630         outputFormat = config->mOutputFormat;
1631         usage = config->mISConfig ? config->mISConfig->mUsage : 0;
1632     }
1633     sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1634     sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1635     sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1636     if (inputSurface) {
1637         status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1638                 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1639         if (err != OK) {
1640             ALOGE("Failed to set up input surface: %d", err);
1641             mCallback->onInputSurfaceDeclined(err);
1642             return;
1643         }
1644     } else if (gbs) {
1645         int32_t width = 0;
1646         (void)outputFormat->findInt32("width", &width);
1647         int32_t height = 0;
1648         (void)outputFormat->findInt32("height", &height);
1649         status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1650                 gbs, width, height, usage));
1651         if (err != OK) {
1652             ALOGE("Failed to set up input surface: %d", err);
1653             mCallback->onInputSurfaceDeclined(err);
1654             return;
1655         }
1656     } else {
1657         ALOGE("Failed to set input surface: Corrupted surface.");
1658         mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1659         return;
1660     }
1661     // Formats can change after setupInputSurface
1662     sp<AMessage> inputFormat;
1663     {
1664         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1665         const std::unique_ptr<Config> &config = *configLocked;
1666         inputFormat = config->mInputFormat;
1667         outputFormat = config->mOutputFormat;
1668     }
1669     mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1670 }
1671 
initiateStart()1672 void CCodec::initiateStart() {
1673     auto setStarting = [this] {
1674         Mutexed<State>::Locked state(mState);
1675         if (state->get() != ALLOCATED) {
1676             return UNKNOWN_ERROR;
1677         }
1678         state->set(STARTING);
1679         return OK;
1680     };
1681     if (tryAndReportOnError(setStarting) != OK) {
1682         return;
1683     }
1684 
1685     (new AMessage(kWhatStart, this))->post();
1686 }
1687 
start()1688 void CCodec::start() {
1689     std::shared_ptr<Codec2Client::Component> comp;
1690     auto checkStarting = [this, &comp] {
1691         Mutexed<State>::Locked state(mState);
1692         if (state->get() != STARTING) {
1693             return UNKNOWN_ERROR;
1694         }
1695         comp = state->comp;
1696         return OK;
1697     };
1698     if (tryAndReportOnError(checkStarting) != OK) {
1699         return;
1700     }
1701 
1702     c2_status_t err = comp->start();
1703     if (err != C2_OK) {
1704         mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1705                            ACTION_CODE_FATAL);
1706         return;
1707     }
1708     sp<AMessage> inputFormat;
1709     sp<AMessage> outputFormat;
1710     status_t err2 = OK;
1711     bool buffersBoundToCodec = false;
1712     {
1713         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1714         const std::unique_ptr<Config> &config = *configLocked;
1715         inputFormat = config->mInputFormat;
1716         // start triggers format dup
1717         outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
1718         if (config->mInputSurface) {
1719             err2 = config->mInputSurface->start();
1720             config->mInputSurfaceDataspace = config->mInputSurface->getDataspace();
1721         }
1722         buffersBoundToCodec = config->mBuffersBoundToCodec;
1723     }
1724     if (err2 != OK) {
1725         mCallback->onError(err2, ACTION_CODE_FATAL);
1726         return;
1727     }
1728     err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
1729     if (err2 != OK) {
1730         mCallback->onError(err2, ACTION_CODE_FATAL);
1731         return;
1732     }
1733 
1734     auto setRunning = [this] {
1735         Mutexed<State>::Locked state(mState);
1736         if (state->get() != STARTING) {
1737             return UNKNOWN_ERROR;
1738         }
1739         state->set(RUNNING);
1740         return OK;
1741     };
1742     if (tryAndReportOnError(setRunning) != OK) {
1743         return;
1744     }
1745     mCallback->onStartCompleted();
1746 
1747     (void)mChannel->requestInitialInputBuffers();
1748 }
1749 
initiateShutdown(bool keepComponentAllocated)1750 void CCodec::initiateShutdown(bool keepComponentAllocated) {
1751     if (keepComponentAllocated) {
1752         initiateStop();
1753     } else {
1754         initiateRelease();
1755     }
1756 }
1757 
initiateStop()1758 void CCodec::initiateStop() {
1759     {
1760         Mutexed<State>::Locked state(mState);
1761         if (state->get() == ALLOCATED
1762                 || state->get()  == RELEASED
1763                 || state->get() == STOPPING
1764                 || state->get() == RELEASING) {
1765             // We're already stopped, released, or doing it right now.
1766             state.unlock();
1767             mCallback->onStopCompleted();
1768             state.lock();
1769             return;
1770         }
1771         state->set(STOPPING);
1772     }
1773 
1774     mChannel->reset();
1775     (new AMessage(kWhatStop, this))->post();
1776 }
1777 
stop()1778 void CCodec::stop() {
1779     std::shared_ptr<Codec2Client::Component> comp;
1780     {
1781         Mutexed<State>::Locked state(mState);
1782         if (state->get() == RELEASING) {
1783             state.unlock();
1784             // We're already stopped or release is in progress.
1785             mCallback->onStopCompleted();
1786             state.lock();
1787             return;
1788         } else if (state->get() != STOPPING) {
1789             state.unlock();
1790             mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1791             state.lock();
1792             return;
1793         }
1794         comp = state->comp;
1795     }
1796     status_t err = comp->stop();
1797     if (err != C2_OK) {
1798         // TODO: convert err into status_t
1799         mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1800     }
1801 
1802     {
1803         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1804         const std::unique_ptr<Config> &config = *configLocked;
1805         if (config->mInputSurface) {
1806             config->mInputSurface->disconnect();
1807             config->mInputSurface = nullptr;
1808             config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
1809         }
1810     }
1811     {
1812         Mutexed<State>::Locked state(mState);
1813         if (state->get() == STOPPING) {
1814             state->set(ALLOCATED);
1815         }
1816     }
1817     mCallback->onStopCompleted();
1818 }
1819 
initiateRelease(bool sendCallback)1820 void CCodec::initiateRelease(bool sendCallback /* = true */) {
1821     bool clearInputSurfaceIfNeeded = false;
1822     {
1823         Mutexed<State>::Locked state(mState);
1824         if (state->get() == RELEASED || state->get() == RELEASING) {
1825             // We're already released or doing it right now.
1826             if (sendCallback) {
1827                 state.unlock();
1828                 mCallback->onReleaseCompleted();
1829                 state.lock();
1830             }
1831             return;
1832         }
1833         if (state->get() == ALLOCATING) {
1834             state->set(RELEASING);
1835             // With the altered state allocate() would fail and clean up.
1836             if (sendCallback) {
1837                 state.unlock();
1838                 mCallback->onReleaseCompleted();
1839                 state.lock();
1840             }
1841             return;
1842         }
1843         if (state->get() == STARTING
1844                 || state->get() == RUNNING
1845                 || state->get() == STOPPING) {
1846             // Input surface may have been started, so clean up is needed.
1847             clearInputSurfaceIfNeeded = true;
1848         }
1849         state->set(RELEASING);
1850     }
1851 
1852     if (clearInputSurfaceIfNeeded) {
1853         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1854         const std::unique_ptr<Config> &config = *configLocked;
1855         if (config->mInputSurface) {
1856             config->mInputSurface->disconnect();
1857             config->mInputSurface = nullptr;
1858             config->mInputSurfaceDataspace = HAL_DATASPACE_UNKNOWN;
1859         }
1860     }
1861 
1862     mChannel->reset();
1863     // thiz holds strong ref to this while the thread is running.
1864     sp<CCodec> thiz(this);
1865     std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1866 }
1867 
release(bool sendCallback)1868 void CCodec::release(bool sendCallback) {
1869     std::shared_ptr<Codec2Client::Component> comp;
1870     {
1871         Mutexed<State>::Locked state(mState);
1872         if (state->get() == RELEASED) {
1873             if (sendCallback) {
1874                 state.unlock();
1875                 mCallback->onReleaseCompleted();
1876                 state.lock();
1877             }
1878             return;
1879         }
1880         comp = state->comp;
1881     }
1882     comp->release();
1883 
1884     {
1885         Mutexed<State>::Locked state(mState);
1886         state->set(RELEASED);
1887         state->comp.reset();
1888     }
1889     (new AMessage(kWhatRelease, this))->post();
1890     if (sendCallback) {
1891         mCallback->onReleaseCompleted();
1892     }
1893 }
1894 
setSurface(const sp<Surface> & surface)1895 status_t CCodec::setSurface(const sp<Surface> &surface) {
1896     {
1897         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1898         const std::unique_ptr<Config> &config = *configLocked;
1899         if (config->mTunneled && config->mSidebandHandle != nullptr) {
1900             sp<ANativeWindow> nativeWindow = static_cast<ANativeWindow *>(surface.get());
1901             status_t err = native_window_set_sideband_stream(
1902                     nativeWindow.get(),
1903                     const_cast<native_handle_t *>(config->mSidebandHandle->handle()));
1904             if (err != OK) {
1905                 ALOGE("NativeWindow(%p) native_window_set_sideband_stream(%p) failed! (err %d).",
1906                         nativeWindow.get(), config->mSidebandHandle->handle(), err);
1907                 return err;
1908             }
1909         }
1910     }
1911     return mChannel->setSurface(surface);
1912 }
1913 
signalFlush()1914 void CCodec::signalFlush() {
1915     status_t err = [this] {
1916         Mutexed<State>::Locked state(mState);
1917         if (state->get() == FLUSHED) {
1918             return ALREADY_EXISTS;
1919         }
1920         if (state->get() != RUNNING) {
1921             return UNKNOWN_ERROR;
1922         }
1923         state->set(FLUSHING);
1924         return OK;
1925     }();
1926     switch (err) {
1927         case ALREADY_EXISTS:
1928             mCallback->onFlushCompleted();
1929             return;
1930         case OK:
1931             break;
1932         default:
1933             mCallback->onError(err, ACTION_CODE_FATAL);
1934             return;
1935     }
1936 
1937     mChannel->stop();
1938     (new AMessage(kWhatFlush, this))->post();
1939 }
1940 
flush()1941 void CCodec::flush() {
1942     std::shared_ptr<Codec2Client::Component> comp;
1943     auto checkFlushing = [this, &comp] {
1944         Mutexed<State>::Locked state(mState);
1945         if (state->get() != FLUSHING) {
1946             return UNKNOWN_ERROR;
1947         }
1948         comp = state->comp;
1949         return OK;
1950     };
1951     if (tryAndReportOnError(checkFlushing) != OK) {
1952         return;
1953     }
1954 
1955     std::list<std::unique_ptr<C2Work>> flushedWork;
1956     c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1957     {
1958         Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1959         flushedWork.splice(flushedWork.end(), *queue);
1960     }
1961     if (err != C2_OK) {
1962         // TODO: convert err into status_t
1963         mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1964     }
1965 
1966     mChannel->flush(flushedWork);
1967 
1968     {
1969         Mutexed<State>::Locked state(mState);
1970         if (state->get() == FLUSHING) {
1971             state->set(FLUSHED);
1972         }
1973     }
1974     mCallback->onFlushCompleted();
1975 }
1976 
signalResume()1977 void CCodec::signalResume() {
1978     std::shared_ptr<Codec2Client::Component> comp;
1979     auto setResuming = [this, &comp] {
1980         Mutexed<State>::Locked state(mState);
1981         if (state->get() != FLUSHED) {
1982             return UNKNOWN_ERROR;
1983         }
1984         state->set(RESUMING);
1985         comp = state->comp;
1986         return OK;
1987     };
1988     if (tryAndReportOnError(setResuming) != OK) {
1989         return;
1990     }
1991 
1992     {
1993         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1994         const std::unique_ptr<Config> &config = *configLocked;
1995         sp<AMessage> outputFormat = config->mOutputFormat;
1996         config->queryConfiguration(comp);
1997         RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
1998     }
1999 
2000     (void)mChannel->start(nullptr, nullptr, [&]{
2001         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2002         const std::unique_ptr<Config> &config = *configLocked;
2003         return config->mBuffersBoundToCodec;
2004     }());
2005 
2006     {
2007         Mutexed<State>::Locked state(mState);
2008         if (state->get() != RESUMING) {
2009             state.unlock();
2010             mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2011             state.lock();
2012             return;
2013         }
2014         state->set(RUNNING);
2015     }
2016 
2017     (void)mChannel->requestInitialInputBuffers();
2018 }
2019 
signalSetParameters(const sp<AMessage> & msg)2020 void CCodec::signalSetParameters(const sp<AMessage> &msg) {
2021     std::shared_ptr<Codec2Client::Component> comp;
2022     auto checkState = [this, &comp] {
2023         Mutexed<State>::Locked state(mState);
2024         if (state->get() == RELEASED) {
2025             return INVALID_OPERATION;
2026         }
2027         comp = state->comp;
2028         return OK;
2029     };
2030     if (tryAndReportOnError(checkState) != OK) {
2031         return;
2032     }
2033 
2034     // NOTE: We used to ignore "bitrate" at setParameters; replicate
2035     //       the behavior here.
2036     sp<AMessage> params = msg;
2037     int32_t bitrate;
2038     if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
2039         params = msg->dup();
2040         params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
2041     }
2042 
2043     int32_t syncId = 0;
2044     if (params->findInt32("audio-hw-sync", &syncId)
2045             || params->findInt32("hw-av-sync-id", &syncId)) {
2046         configureTunneledVideoPlayback(comp, nullptr, params);
2047     }
2048 
2049     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2050     const std::unique_ptr<Config> &config = *configLocked;
2051 
2052     /**
2053      * Handle input surface parameters
2054      */
2055     if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
2056             && (config->mDomain & Config::IS_ENCODER)
2057             && config->mInputSurface && config->mISConfig) {
2058         (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
2059 
2060         if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
2061             config->mISConfig->mStopped = false;
2062         } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
2063             config->mISConfig->mStopped = true;
2064         }
2065 
2066         int32_t value;
2067         if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
2068             config->mISConfig->mSuspended = value;
2069             config->mISConfig->mSuspendAtUs = -1;
2070             (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
2071         }
2072 
2073         (void)config->mInputSurface->configure(*config->mISConfig);
2074         if (config->mISConfig->mStopped) {
2075             config->mInputFormat->setInt64(
2076                     "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
2077         }
2078     }
2079 
2080     std::vector<std::unique_ptr<C2Param>> configUpdate;
2081     (void)config->getConfigUpdateFromSdkParams(
2082             comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
2083     // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
2084     // Parameter synchronization is not defined when using input surface. For now, route
2085     // these directly to the component.
2086     if (config->mInputSurface == nullptr
2087             && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
2088                     || comp->getName().find("c2.android.") == 0)) {
2089         mChannel->setParameters(configUpdate);
2090     } else {
2091         sp<AMessage> outputFormat = config->mOutputFormat;
2092         (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
2093         RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
2094     }
2095 }
2096 
signalEndOfInputStream()2097 void CCodec::signalEndOfInputStream() {
2098     mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
2099 }
2100 
signalRequestIDRFrame()2101 void CCodec::signalRequestIDRFrame() {
2102     std::shared_ptr<Codec2Client::Component> comp;
2103     {
2104         Mutexed<State>::Locked state(mState);
2105         if (state->get() == RELEASED) {
2106             ALOGD("no IDR request sent since component is released");
2107             return;
2108         }
2109         comp = state->comp;
2110     }
2111     ALOGV("request IDR");
2112     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2113     const std::unique_ptr<Config> &config = *configLocked;
2114     std::vector<std::unique_ptr<C2Param>> params;
2115     params.push_back(
2116             std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
2117     config->setParameters(comp, params, C2_MAY_BLOCK);
2118 }
2119 
querySupportedParameters(std::vector<std::string> * names)2120 status_t CCodec::querySupportedParameters(std::vector<std::string> *names) {
2121     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2122     const std::unique_ptr<Config> &config = *configLocked;
2123     return config->querySupportedParameters(names);
2124 }
2125 
describeParameter(const std::string & name,CodecParameterDescriptor * desc)2126 status_t CCodec::describeParameter(
2127         const std::string &name, CodecParameterDescriptor *desc) {
2128     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2129     const std::unique_ptr<Config> &config = *configLocked;
2130     return config->describe(name, desc);
2131 }
2132 
subscribeToParameters(const std::vector<std::string> & names)2133 status_t CCodec::subscribeToParameters(const std::vector<std::string> &names) {
2134     std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2135     if (!comp) {
2136         return INVALID_OPERATION;
2137     }
2138     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2139     const std::unique_ptr<Config> &config = *configLocked;
2140     return config->subscribeToVendorConfigUpdate(comp, names);
2141 }
2142 
unsubscribeFromParameters(const std::vector<std::string> & names)2143 status_t CCodec::unsubscribeFromParameters(const std::vector<std::string> &names) {
2144     std::shared_ptr<Codec2Client::Component> comp = mState.lock()->comp;
2145     if (!comp) {
2146         return INVALID_OPERATION;
2147     }
2148     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2149     const std::unique_ptr<Config> &config = *configLocked;
2150     return config->unsubscribeFromVendorConfigUpdate(comp, names);
2151 }
2152 
onWorkDone(std::list<std::unique_ptr<C2Work>> & workItems)2153 void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
2154     if (!workItems.empty()) {
2155         Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2156         queue->splice(queue->end(), workItems);
2157     }
2158     (new AMessage(kWhatWorkDone, this))->post();
2159 }
2160 
onInputBufferDone(uint64_t frameIndex,size_t arrayIndex)2161 void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
2162     mChannel->onInputBufferDone(frameIndex, arrayIndex);
2163     if (arrayIndex == 0) {
2164         // We always put no more than one buffer per work, if we use an input surface.
2165         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2166         const std::unique_ptr<Config> &config = *configLocked;
2167         if (config->mInputSurface) {
2168             config->mInputSurface->onInputBufferDone(frameIndex);
2169         }
2170     }
2171 }
2172 
onMessageReceived(const sp<AMessage> & msg)2173 void CCodec::onMessageReceived(const sp<AMessage> &msg) {
2174     TimePoint now = std::chrono::steady_clock::now();
2175     CCodecWatchdog::getInstance()->watch(this);
2176     switch (msg->what()) {
2177         case kWhatAllocate: {
2178             // C2ComponentStore::createComponent() should return within 100ms.
2179             setDeadline(now, 1500ms, "allocate");
2180             sp<RefBase> obj;
2181             CHECK(msg->findObject("codecInfo", &obj));
2182             allocate((MediaCodecInfo *)obj.get());
2183             break;
2184         }
2185         case kWhatConfigure: {
2186             // C2Component::commit_sm() should return within 5ms.
2187             setDeadline(now, 1500ms, "configure");
2188             sp<AMessage> format;
2189             CHECK(msg->findMessage("format", &format));
2190             configure(format);
2191             break;
2192         }
2193         case kWhatStart: {
2194             // C2Component::start() should return within 500ms.
2195             setDeadline(now, 1500ms, "start");
2196             start();
2197             break;
2198         }
2199         case kWhatStop: {
2200             // C2Component::stop() should return within 500ms.
2201             setDeadline(now, 1500ms, "stop");
2202             stop();
2203             break;
2204         }
2205         case kWhatFlush: {
2206             // C2Component::flush_sm() should return within 5ms.
2207             setDeadline(now, 1500ms, "flush");
2208             flush();
2209             break;
2210         }
2211         case kWhatRelease: {
2212             mChannel->release();
2213             mClient.reset();
2214             mClientListener.reset();
2215             break;
2216         }
2217         case kWhatCreateInputSurface: {
2218             // Surface operations may be briefly blocking.
2219             setDeadline(now, 1500ms, "createInputSurface");
2220             createInputSurface();
2221             break;
2222         }
2223         case kWhatSetInputSurface: {
2224             // Surface operations may be briefly blocking.
2225             setDeadline(now, 1500ms, "setInputSurface");
2226             sp<RefBase> obj;
2227             CHECK(msg->findObject("surface", &obj));
2228             sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
2229             setInputSurface(surface);
2230             break;
2231         }
2232         case kWhatWorkDone: {
2233             std::unique_ptr<C2Work> work;
2234             bool shouldPost = false;
2235             {
2236                 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
2237                 if (queue->empty()) {
2238                     break;
2239                 }
2240                 work.swap(queue->front());
2241                 queue->pop_front();
2242                 shouldPost = !queue->empty();
2243             }
2244             if (shouldPost) {
2245                 (new AMessage(kWhatWorkDone, this))->post();
2246             }
2247 
2248             // handle configuration changes in work done
2249             std::shared_ptr<const C2StreamInitDataInfo::output> initData;
2250             sp<AMessage> outputFormat = nullptr;
2251             {
2252                 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2253                 const std::unique_ptr<Config> &config = *configLocked;
2254                 Config::Watcher<C2StreamInitDataInfo::output> initDataWatcher =
2255                     config->watch<C2StreamInitDataInfo::output>();
2256                 if (!work->worklets.empty()
2257                         && (work->worklets.front()->output.flags
2258                                 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
2259 
2260                     // copy buffer info to config
2261                     std::vector<std::unique_ptr<C2Param>> updates;
2262                     for (const std::unique_ptr<C2Param> &param
2263                             : work->worklets.front()->output.configUpdate) {
2264                         updates.push_back(C2Param::Copy(*param));
2265                     }
2266                     unsigned stream = 0;
2267                     std::vector<std::shared_ptr<C2Buffer>> &outputBuffers =
2268                         work->worklets.front()->output.buffers;
2269                     for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2270                         for (const std::shared_ptr<const C2Info> &info : buf->info()) {
2271                             // move all info into output-stream #0 domain
2272                             updates.emplace_back(
2273                                     C2Param::CopyAsStream(*info, true /* output */, stream));
2274                         }
2275 
2276                         const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
2277                         // for now only do the first block
2278                         if (!blocks.empty()) {
2279                             // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
2280                             //      block.crop().left, block.crop().top,
2281                             //      block.crop().width, block.crop().height,
2282                             //      block.width(), block.height());
2283                             const C2ConstGraphicBlock &block = blocks[0];
2284                             updates.emplace_back(new C2StreamCropRectInfo::output(
2285                                     stream, block.crop()));
2286                         }
2287                         ++stream;
2288                     }
2289 
2290                     sp<AMessage> oldFormat = config->mOutputFormat;
2291                     config->updateConfiguration(updates, config->mOutputDomain);
2292                     RevertOutputFormatIfNeeded(oldFormat, config->mOutputFormat);
2293 
2294                     // copy standard infos to graphic buffers if not already present (otherwise, we
2295                     // may overwrite the actual intermediate value with a final value)
2296                     stream = 0;
2297                     const static C2Param::Index stdGfxInfos[] = {
2298                         C2StreamRotationInfo::output::PARAM_TYPE,
2299                         C2StreamColorAspectsInfo::output::PARAM_TYPE,
2300                         C2StreamDataSpaceInfo::output::PARAM_TYPE,
2301                         C2StreamHdrStaticInfo::output::PARAM_TYPE,
2302                         C2StreamHdr10PlusInfo::output::PARAM_TYPE,
2303                         C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
2304                         C2StreamSurfaceScalingInfo::output::PARAM_TYPE
2305                     };
2306                     for (const std::shared_ptr<C2Buffer> &buf : outputBuffers) {
2307                         if (buf->data().graphicBlocks().size()) {
2308                             for (C2Param::Index ix : stdGfxInfos) {
2309                                 if (!buf->hasInfo(ix)) {
2310                                     const C2Param *param =
2311                                         config->getConfigParameterValue(ix.withStream(stream));
2312                                     if (param) {
2313                                         std::shared_ptr<C2Param> info(C2Param::Copy(*param));
2314                                         buf->setInfo(std::static_pointer_cast<C2Info>(info));
2315                                     }
2316                                 }
2317                             }
2318                         }
2319                         ++stream;
2320                     }
2321                 }
2322                 if (config->mInputSurface) {
2323                     if (work->worklets.empty()
2324                            || !work->worklets.back()
2325                            || (work->worklets.back()->output.flags
2326                                   & C2FrameData::FLAG_INCOMPLETE) == 0) {
2327                         config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
2328                     }
2329                 }
2330                 if (initDataWatcher.hasChanged()) {
2331                     initData = initDataWatcher.update();
2332                     AmendOutputFormatWithCodecSpecificData(
2333                             initData->m.value, initData->flexCount(), config->mCodingMediaType,
2334                             config->mOutputFormat);
2335                 }
2336                 outputFormat = config->mOutputFormat;
2337             }
2338             mChannel->onWorkDone(
2339                     std::move(work), outputFormat, initData ? initData.get() : nullptr);
2340             break;
2341         }
2342         case kWhatWatch: {
2343             // watch message already posted; no-op.
2344             break;
2345         }
2346         default: {
2347             ALOGE("unrecognized message");
2348             break;
2349         }
2350     }
2351     setDeadline(TimePoint::max(), 0ms, "none");
2352 }
2353 
setDeadline(const TimePoint & now,const std::chrono::milliseconds & timeout,const char * name)2354 void CCodec::setDeadline(
2355         const TimePoint &now,
2356         const std::chrono::milliseconds &timeout,
2357         const char *name) {
2358     int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
2359     Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2360     deadline->set(now + (timeout * mult), name);
2361 }
2362 
configureTunneledVideoPlayback(std::shared_ptr<Codec2Client::Component> comp,sp<NativeHandle> * sidebandHandle,const sp<AMessage> & msg)2363 status_t CCodec::configureTunneledVideoPlayback(
2364         std::shared_ptr<Codec2Client::Component> comp,
2365         sp<NativeHandle> *sidebandHandle,
2366         const sp<AMessage> &msg) {
2367     std::vector<std::unique_ptr<C2SettingResult>> failures;
2368 
2369     std::unique_ptr<C2PortTunneledModeTuning::output> tunneledPlayback =
2370         C2PortTunneledModeTuning::output::AllocUnique(
2371             1,
2372             C2PortTunneledModeTuning::Struct::SIDEBAND,
2373             C2PortTunneledModeTuning::Struct::REALTIME,
2374             0);
2375     // TODO: use KEY_AUDIO_HW_SYNC, KEY_HARDWARE_AV_SYNC_ID when they are in MediaCodecConstants.h
2376     if (msg->findInt32("audio-hw-sync", &tunneledPlayback->m.syncId[0])) {
2377         tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::AUDIO_HW_SYNC;
2378     } else if (msg->findInt32("hw-av-sync-id", &tunneledPlayback->m.syncId[0])) {
2379         tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::HW_AV_SYNC;
2380     } else {
2381         tunneledPlayback->m.syncType = C2PortTunneledModeTuning::Struct::sync_type_t::REALTIME;
2382         tunneledPlayback->setFlexCount(0);
2383     }
2384     c2_status_t c2err = comp->config({ tunneledPlayback.get() }, C2_MAY_BLOCK, &failures);
2385     if (c2err != C2_OK) {
2386         return UNKNOWN_ERROR;
2387     }
2388 
2389     if (sidebandHandle == nullptr) {
2390         return OK;
2391     }
2392 
2393     std::vector<std::unique_ptr<C2Param>> params;
2394     c2err = comp->query({}, {C2PortTunnelHandleTuning::output::PARAM_TYPE}, C2_DONT_BLOCK, &params);
2395     if (c2err == C2_OK && params.size() == 1u) {
2396         C2PortTunnelHandleTuning::output *videoTunnelSideband =
2397             C2PortTunnelHandleTuning::output::From(params[0].get());
2398         // Currently, Codec2 only supports non-fd case for sideband native_handle.
2399         native_handle_t *handle = native_handle_create(0, videoTunnelSideband->flexCount());
2400         *sidebandHandle = NativeHandle::create(handle, true /* ownsHandle */);
2401         if (handle != nullptr && videoTunnelSideband->flexCount()) {
2402             memcpy(handle->data, videoTunnelSideband->m.values,
2403                     sizeof(int32_t) * videoTunnelSideband->flexCount());
2404             return OK;
2405         } else {
2406             return NO_MEMORY;
2407         }
2408     }
2409     return UNKNOWN_ERROR;
2410 }
2411 
initiateReleaseIfStuck()2412 void CCodec::initiateReleaseIfStuck() {
2413     std::string name;
2414     bool pendingDeadline = false;
2415     {
2416         Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
2417         if (deadline->get() < std::chrono::steady_clock::now()) {
2418             name = deadline->getName();
2419         }
2420         if (deadline->get() != TimePoint::max()) {
2421             pendingDeadline = true;
2422         }
2423     }
2424     bool tunneled = false;
2425     bool isMediaTypeKnown = false;
2426     {
2427         static const std::set<std::string> kKnownMediaTypes{
2428             MIMETYPE_VIDEO_VP8,
2429             MIMETYPE_VIDEO_VP9,
2430             MIMETYPE_VIDEO_AV1,
2431             MIMETYPE_VIDEO_AVC,
2432             MIMETYPE_VIDEO_HEVC,
2433             MIMETYPE_VIDEO_MPEG4,
2434             MIMETYPE_VIDEO_H263,
2435             MIMETYPE_VIDEO_MPEG2,
2436             MIMETYPE_VIDEO_RAW,
2437             MIMETYPE_VIDEO_DOLBY_VISION,
2438 
2439             MIMETYPE_AUDIO_AMR_NB,
2440             MIMETYPE_AUDIO_AMR_WB,
2441             MIMETYPE_AUDIO_MPEG,
2442             MIMETYPE_AUDIO_AAC,
2443             MIMETYPE_AUDIO_QCELP,
2444             MIMETYPE_AUDIO_VORBIS,
2445             MIMETYPE_AUDIO_OPUS,
2446             MIMETYPE_AUDIO_G711_ALAW,
2447             MIMETYPE_AUDIO_G711_MLAW,
2448             MIMETYPE_AUDIO_RAW,
2449             MIMETYPE_AUDIO_FLAC,
2450             MIMETYPE_AUDIO_MSGSM,
2451             MIMETYPE_AUDIO_AC3,
2452             MIMETYPE_AUDIO_EAC3,
2453 
2454             MIMETYPE_IMAGE_ANDROID_HEIC,
2455         };
2456         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
2457         const std::unique_ptr<Config> &config = *configLocked;
2458         tunneled = config->mTunneled;
2459         isMediaTypeKnown = (kKnownMediaTypes.count(config->mCodingMediaType) != 0);
2460     }
2461     if (!tunneled && isMediaTypeKnown && name.empty()) {
2462         constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
2463         std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
2464         if (elapsed >= kWorkDurationThreshold) {
2465             name = "queue";
2466         }
2467         if (elapsed > 0s) {
2468             pendingDeadline = true;
2469         }
2470     }
2471     if (name.empty()) {
2472         // We're not stuck.
2473         if (pendingDeadline) {
2474             // If we are not stuck yet but still has deadline coming up,
2475             // post watch message to check back later.
2476             (new AMessage(kWhatWatch, this))->post();
2477         }
2478         return;
2479     }
2480 
2481     C2String compName;
2482     {
2483         Mutexed<State>::Locked state(mState);
2484         if (!state->comp) {
2485             ALOGD("previous call to %s exceeded timeout "
2486                   "and the component is already released", name.c_str());
2487             return;
2488         }
2489         compName = state->comp->getName();
2490     }
2491     ALOGW("[%s] previous call to %s exceeded timeout", compName.c_str(), name.c_str());
2492 
2493     initiateRelease(false);
2494     mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2495 }
2496 
2497 // static
CreateInputSurface()2498 PersistentSurface *CCodec::CreateInputSurface() {
2499     using namespace android;
2500     using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
2501     // Attempt to create a Codec2's input surface.
2502     std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2503             Codec2Client::CreateInputSurface();
2504     if (!inputSurface) {
2505         if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2506             sp<IGraphicBufferProducer> gbp;
2507             sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2508             status_t err = gbs->initCheck();
2509             if (err != OK) {
2510                 ALOGE("Failed to create persistent input surface: error %d", err);
2511                 return nullptr;
2512             }
2513             return new PersistentSurface(
2514                     gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
2515         } else {
2516             return nullptr;
2517         }
2518     }
2519     return new PersistentSurface(
2520             inputSurface->getGraphicBufferProducer(),
2521             static_cast<sp<android::hidl::base::V1_0::IBase>>(
2522             inputSurface->getHalInterface()));
2523 }
2524 
2525 class IntfCache {
2526 public:
2527     IntfCache() = default;
2528 
init(const std::string & name)2529     status_t init(const std::string &name) {
2530         std::shared_ptr<Codec2Client::Interface> intf{
2531             Codec2Client::CreateInterfaceByName(name.c_str())};
2532         if (!intf) {
2533             ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2534             mInitStatus = NO_INIT;
2535             return NO_INIT;
2536         }
2537         const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2538         mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2539                 C2ParamField{&sUsage, &sUsage.value}));
2540         c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2541         if (err != C2_OK) {
2542             ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2543                     name.c_str(), err);
2544             mFields[0].status = err;
2545         }
2546         std::vector<std::unique_ptr<C2Param>> params;
2547         err = intf->query(
2548                 {&mApiFeatures},
2549                 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2550                 C2_MAY_BLOCK,
2551                 &params);
2552         if (err != C2_OK && err != C2_BAD_INDEX) {
2553             ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2554                     name.c_str(), err);
2555         }
2556         while (!params.empty()) {
2557             C2Param *param = params.back().release();
2558             params.pop_back();
2559             if (!param) {
2560                 continue;
2561             }
2562             if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2563                 mInputAllocators.reset(
2564                         C2PortAllocatorsTuning::input::From(param));
2565             }
2566         }
2567         mInitStatus = OK;
2568         return OK;
2569     }
2570 
initCheck() const2571     status_t initCheck() const { return mInitStatus; }
2572 
getUsageSupportedValues() const2573     const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2574         CHECK_EQ(1u, mFields.size());
2575         return mFields[0];
2576     }
2577 
getApiFeatures() const2578     const C2ApiFeaturesSetting &getApiFeatures() const {
2579         return mApiFeatures;
2580     }
2581 
getInputAllocators() const2582     const C2PortAllocatorsTuning::input &getInputAllocators() const {
2583         static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2584             std::unique_ptr<C2PortAllocatorsTuning::input> param =
2585                 C2PortAllocatorsTuning::input::AllocUnique(0);
2586             param->invalidate();
2587             return param;
2588         }();
2589         return mInputAllocators ? *mInputAllocators : *sInvalidated;
2590     }
2591 
2592 private:
2593     status_t mInitStatus{NO_INIT};
2594 
2595     std::vector<C2FieldSupportedValuesQuery> mFields;
2596     C2ApiFeaturesSetting mApiFeatures;
2597     std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2598 };
2599 
GetIntfCache(const std::string & name)2600 static const IntfCache &GetIntfCache(const std::string &name) {
2601     static IntfCache sNullIntfCache;
2602     static std::mutex sMutex;
2603     static std::map<std::string, IntfCache> sCache;
2604     std::unique_lock<std::mutex> lock{sMutex};
2605     auto it = sCache.find(name);
2606     if (it == sCache.end()) {
2607         lock.unlock();
2608         IntfCache intfCache;
2609         status_t err = intfCache.init(name);
2610         if (err != OK) {
2611             return sNullIntfCache;
2612         }
2613         lock.lock();
2614         it = sCache.insert({name, std::move(intfCache)}).first;
2615     }
2616     return it->second;
2617 }
2618 
GetCommonAllocatorIds(const std::vector<std::string> & names,C2Allocator::type_t type,std::set<C2Allocator::id_t> * ids)2619 static status_t GetCommonAllocatorIds(
2620         const std::vector<std::string> &names,
2621         C2Allocator::type_t type,
2622         std::set<C2Allocator::id_t> *ids) {
2623     int poolMask = GetCodec2PoolMask();
2624     C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2625     C2Allocator::id_t defaultAllocatorId =
2626         (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2627 
2628     ids->clear();
2629     if (names.empty()) {
2630         return OK;
2631     }
2632     bool firstIteration = true;
2633     for (const std::string &name : names) {
2634         const IntfCache &intfCache = GetIntfCache(name);
2635         if (intfCache.initCheck() != OK) {
2636             continue;
2637         }
2638         const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
2639         if (firstIteration) {
2640             firstIteration = false;
2641             if (allocators && allocators.flexCount() > 0) {
2642                 ids->insert(allocators.m.values,
2643                             allocators.m.values + allocators.flexCount());
2644             }
2645             if (ids->empty()) {
2646                 // The component does not advertise allocators. Use default.
2647                 ids->insert(defaultAllocatorId);
2648             }
2649             continue;
2650         }
2651         bool filtered = false;
2652         if (allocators && allocators.flexCount() > 0) {
2653             filtered = true;
2654             for (auto it = ids->begin(); it != ids->end(); ) {
2655                 bool found = false;
2656                 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2657                     if (allocators.m.values[j] == *it) {
2658                         found = true;
2659                         break;
2660                     }
2661                 }
2662                 if (found) {
2663                     ++it;
2664                 } else {
2665                     it = ids->erase(it);
2666                 }
2667             }
2668         }
2669         if (!filtered) {
2670             // The component does not advertise supported allocators. Use default.
2671             bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2672             if (ids->size() != (containsDefault ? 1 : 0)) {
2673                 ids->clear();
2674                 if (containsDefault) {
2675                     ids->insert(defaultAllocatorId);
2676                 }
2677             }
2678         }
2679     }
2680     // Finally, filter with pool masks
2681     for (auto it = ids->begin(); it != ids->end(); ) {
2682         if ((poolMask >> *it) & 1) {
2683             ++it;
2684         } else {
2685             it = ids->erase(it);
2686         }
2687     }
2688     return OK;
2689 }
2690 
CalculateMinMaxUsage(const std::vector<std::string> & names,uint64_t * minUsage,uint64_t * maxUsage)2691 static status_t CalculateMinMaxUsage(
2692         const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2693     static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2694     *minUsage = 0;
2695     *maxUsage = ~0ull;
2696     for (const std::string &name : names) {
2697         const IntfCache &intfCache = GetIntfCache(name);
2698         if (intfCache.initCheck() != OK) {
2699             continue;
2700         }
2701         const C2FieldSupportedValuesQuery &usageSupportedValues =
2702             intfCache.getUsageSupportedValues();
2703         if (usageSupportedValues.status != C2_OK) {
2704             continue;
2705         }
2706         const C2FieldSupportedValues &supported = usageSupportedValues.values;
2707         if (supported.type != C2FieldSupportedValues::FLAGS) {
2708             continue;
2709         }
2710         if (supported.values.empty()) {
2711             *maxUsage = 0;
2712             continue;
2713         }
2714         if (supported.values.size() > 1) {
2715             *minUsage |= supported.values[1].u64;
2716         } else {
2717             *minUsage |= supported.values[0].u64;
2718         }
2719         int64_t currentMaxUsage = 0;
2720         for (const C2Value::Primitive &flags : supported.values) {
2721             currentMaxUsage |= flags.u64;
2722         }
2723         *maxUsage &= currentMaxUsage;
2724     }
2725     return OK;
2726 }
2727 
2728 // static
CanFetchLinearBlock(const std::vector<std::string> & names,const C2MemoryUsage & usage,bool * isCompatible)2729 status_t CCodec::CanFetchLinearBlock(
2730         const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
2731     for (const std::string &name : names) {
2732         const IntfCache &intfCache = GetIntfCache(name);
2733         if (intfCache.initCheck() != OK) {
2734             continue;
2735         }
2736         const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2737         if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2738             *isCompatible = false;
2739             return OK;
2740         }
2741     }
2742     std::set<C2Allocator::id_t> allocators;
2743     GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2744     if (allocators.empty()) {
2745         *isCompatible = false;
2746         return OK;
2747     }
2748 
2749     uint64_t minUsage = 0;
2750     uint64_t maxUsage = ~0ull;
2751     CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2752     minUsage |= usage.expected;
2753     *isCompatible = ((maxUsage & minUsage) == minUsage);
2754     return OK;
2755 }
2756 
GetPool(C2Allocator::id_t allocId)2757 static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2758     static std::mutex sMutex{};
2759     static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2760     std::unique_lock<std::mutex> lock{sMutex};
2761     std::shared_ptr<C2BlockPool> pool;
2762     auto it = sPools.find(allocId);
2763     if (it == sPools.end()) {
2764         c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2765         if (err == OK) {
2766             sPools.emplace(allocId, pool);
2767         } else {
2768             pool.reset();
2769         }
2770     } else {
2771         pool = it->second;
2772     }
2773     return pool;
2774 }
2775 
2776 // static
FetchLinearBlock(size_t capacity,const C2MemoryUsage & usage,const std::vector<std::string> & names)2777 std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2778         size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2779     std::set<C2Allocator::id_t> allocators;
2780     GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2781     if (allocators.empty()) {
2782         allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2783     }
2784 
2785     uint64_t minUsage = 0;
2786     uint64_t maxUsage = ~0ull;
2787     CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2788     minUsage |= usage.expected;
2789     if ((maxUsage & minUsage) != minUsage) {
2790         allocators.clear();
2791         allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2792     }
2793     std::shared_ptr<C2LinearBlock> block;
2794     for (C2Allocator::id_t allocId : allocators) {
2795         std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2796         if (!pool) {
2797             continue;
2798         }
2799         c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2800         if (err != C2_OK || !block) {
2801             block.reset();
2802             continue;
2803         }
2804         break;
2805     }
2806     return block;
2807 }
2808 
2809 // static
CanFetchGraphicBlock(const std::vector<std::string> & names,bool * isCompatible)2810 status_t CCodec::CanFetchGraphicBlock(
2811         const std::vector<std::string> &names, bool *isCompatible) {
2812     uint64_t minUsage = 0;
2813     uint64_t maxUsage = ~0ull;
2814     std::set<C2Allocator::id_t> allocators;
2815     GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2816     if (allocators.empty()) {
2817         *isCompatible = false;
2818         return OK;
2819     }
2820     CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2821     *isCompatible = ((maxUsage & minUsage) == minUsage);
2822     return OK;
2823 }
2824 
2825 // static
FetchGraphicBlock(int32_t width,int32_t height,int32_t format,uint64_t usage,const std::vector<std::string> & names)2826 std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2827         int32_t width,
2828         int32_t height,
2829         int32_t format,
2830         uint64_t usage,
2831         const std::vector<std::string> &names) {
2832     uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2833     if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2834         ALOGD("Unrecognized pixel format: %d", format);
2835         return nullptr;
2836     }
2837     uint64_t minUsage = 0;
2838     uint64_t maxUsage = ~0ull;
2839     std::set<C2Allocator::id_t> allocators;
2840     GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2841     if (allocators.empty()) {
2842         allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2843     }
2844     CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2845     minUsage |= usage;
2846     if ((maxUsage & minUsage) != minUsage) {
2847         allocators.clear();
2848         allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2849     }
2850     std::shared_ptr<C2GraphicBlock> block;
2851     for (C2Allocator::id_t allocId : allocators) {
2852         std::shared_ptr<C2BlockPool> pool;
2853         c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2854         if (err != C2_OK || !pool) {
2855             continue;
2856         }
2857         err = pool->fetchGraphicBlock(
2858                 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2859         if (err != C2_OK || !block) {
2860             block.reset();
2861             continue;
2862         }
2863         break;
2864     }
2865     return block;
2866 }
2867 
2868 }  // namespace android
2869