1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #ifdef MPEG4
19   #define LOG_TAG "C2SoftMpeg4Dec"
20 #else
21   #define LOG_TAG "C2SoftH263Dec"
22 #endif
23 #include <log/log.h>
24 
25 #include <media/stagefright/foundation/AUtils.h>
26 #include <media/stagefright/foundation/MediaDefs.h>
27 
28 #include <C2Debug.h>
29 #include <C2PlatformSupport.h>
30 #include <SimpleC2Interface.h>
31 
32 #include "C2SoftMpeg4Dec.h"
33 #include "mp4dec_api.h"
34 
35 namespace android {
36 
37 #ifdef MPEG4
38 constexpr char COMPONENT_NAME[] = "c2.android.mpeg4.decoder";
39 #else
40 constexpr char COMPONENT_NAME[] = "c2.android.h263.decoder";
41 #endif
42 
43 class C2SoftMpeg4Dec::IntfImpl : public SimpleInterface<void>::BaseParams {
44 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)45     explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
46         : SimpleInterface<void>::BaseParams(
47                 helper,
48                 COMPONENT_NAME,
49                 C2Component::KIND_DECODER,
50                 C2Component::DOMAIN_VIDEO,
51 #ifdef MPEG4
52                 MEDIA_MIMETYPE_VIDEO_MPEG4
53 #else
54                 MEDIA_MIMETYPE_VIDEO_H263
55 #endif
56                 ) {
57         noPrivateBuffers(); // TODO: account for our buffers here
58         noInputReferences();
59         noOutputReferences();
60         noInputLatency();
61         noTimeStretch();
62 
63         // TODO: output latency and reordering
64 
65         addParameter(
66                 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
67                 .withConstValue(new C2ComponentAttributesSetting(C2Component::ATTRIB_IS_TEMPORAL))
68                 .build());
69 
70         addParameter(
71                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
72                 .withDefault(new C2StreamPictureSizeInfo::output(0u, 176, 144))
73                 .withFields({
74 #ifdef MPEG4
75                     C2F(mSize, width).inRange(16, 352, 2),
76                     C2F(mSize, height).inRange(16, 288, 2),
77 #else
78                     C2F(mSize, width).inRange(16, 352, 16),
79                     C2F(mSize, height).inRange(16, 288, 16),
80 #endif
81                 })
82                 .withSetter(SizeSetter)
83                 .build());
84 
85 #ifdef MPEG4
86         addParameter(
87                 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
88                 .withDefault(new C2StreamProfileLevelInfo::input(0u,
89                         C2Config::PROFILE_MP4V_SIMPLE, C2Config::LEVEL_MP4V_3))
90                 .withFields({
91                     C2F(mProfileLevel, profile).equalTo(
92                             C2Config::PROFILE_MP4V_SIMPLE),
93                     C2F(mProfileLevel, level).oneOf({
94                             C2Config::LEVEL_MP4V_0,
95                             C2Config::LEVEL_MP4V_0B,
96                             C2Config::LEVEL_MP4V_1,
97                             C2Config::LEVEL_MP4V_2,
98                             C2Config::LEVEL_MP4V_3})
99                 })
100                 .withSetter(ProfileLevelSetter, mSize)
101                 .build());
102 #else
103         addParameter(
104                 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
105                 .withDefault(new C2StreamProfileLevelInfo::input(0u,
106                         C2Config::PROFILE_H263_BASELINE, C2Config::LEVEL_H263_30))
107                 .withFields({
108                     C2F(mProfileLevel, profile).oneOf({
109                             C2Config::PROFILE_H263_BASELINE,
110                             C2Config::PROFILE_H263_ISWV2}),
111                     C2F(mProfileLevel, level).oneOf({
112                             C2Config::LEVEL_H263_10,
113                             C2Config::LEVEL_H263_20,
114                             C2Config::LEVEL_H263_30,
115                             C2Config::LEVEL_H263_40,
116                             C2Config::LEVEL_H263_45})
117                 })
118                 .withSetter(ProfileLevelSetter, mSize)
119                 .build());
120 #endif
121 
122         C2ChromaOffsetStruct locations[1] = { C2ChromaOffsetStruct::ITU_YUV_420_0() };
123         std::shared_ptr<C2StreamColorInfo::output> defaultColorInfo =
124             C2StreamColorInfo::output::AllocShared(
125                     1u, 0u, 8u /* bitDepth */, C2Color::YUV_420);
126         memcpy(defaultColorInfo->m.locations, locations, sizeof(locations));
127 
128         defaultColorInfo =
129             C2StreamColorInfo::output::AllocShared(
130                     { C2ChromaOffsetStruct::ITU_YUV_420_0() },
131                     0u, 8u /* bitDepth */, C2Color::YUV_420);
132         helper->addStructDescriptors<C2ChromaOffsetStruct>();
133 
134         addParameter(
135                 DefineParam(mColorInfo, C2_PARAMKEY_CODED_COLOR_INFO)
136                 .withConstValue(defaultColorInfo)
137                 .build());
138 
139         // TODO: support more formats?
140         addParameter(
141                 DefineParam(mPixelFormat, C2_PARAMKEY_PIXEL_FORMAT)
142                 .withConstValue(new C2StreamPixelFormatInfo::output(
143                                      0u, HAL_PIXEL_FORMAT_YCBCR_420_888))
144                 .build());
145     }
146 
SizeSetter(bool mayBlock,const C2P<C2VideoSizeStreamInfo::output> & oldMe,C2P<C2VideoSizeStreamInfo::output> & me)147     static C2R SizeSetter(bool mayBlock, const C2P<C2VideoSizeStreamInfo::output> &oldMe,
148                           C2P<C2VideoSizeStreamInfo::output> &me) {
149         (void)mayBlock;
150         C2R res = C2R::Ok();
151         if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
152             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
153             me.set().width = oldMe.v.width;
154         }
155         if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
156             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
157             me.set().height = oldMe.v.height;
158         }
159         return res;
160     }
161 
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::input> & me,const C2P<C2StreamPictureSizeInfo::output> & size)162     static C2R ProfileLevelSetter(bool mayBlock, C2P<C2StreamProfileLevelInfo::input> &me,
163                                   const C2P<C2StreamPictureSizeInfo::output> &size) {
164         (void)mayBlock;
165         (void)size;
166         (void)me;  // TODO: validate
167         return C2R::Ok();
168     }
169 
170 private:
171     std::shared_ptr<C2StreamProfileLevelInfo::input> mProfileLevel;
172     std::shared_ptr<C2VideoSizeStreamInfo::output> mSize;
173     std::shared_ptr<C2StreamColorInfo::output> mColorInfo;
174     std::shared_ptr<C2StreamPixelFormatInfo::output> mPixelFormat;
175 };
176 
C2SoftMpeg4Dec(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)177 C2SoftMpeg4Dec::C2SoftMpeg4Dec(
178         const char *name,
179         c2_node_id_t id,
180         const std::shared_ptr<IntfImpl> &intfImpl)
181     : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
182       mIntf(intfImpl),
183       mDecHandle(nullptr),
184       mOutputBuffer{},
185       mInitialized(false) {
186 }
187 
~C2SoftMpeg4Dec()188 C2SoftMpeg4Dec::~C2SoftMpeg4Dec() {
189     onRelease();
190 }
191 
onInit()192 c2_status_t C2SoftMpeg4Dec::onInit() {
193     status_t err = initDecoder();
194     return err == OK ? C2_OK : C2_CORRUPTED;
195 }
196 
onStop()197 c2_status_t C2SoftMpeg4Dec::onStop() {
198     if (mInitialized) {
199         if (mDecHandle) {
200             PVCleanUpVideoDecoder(mDecHandle);
201         }
202         mInitialized = false;
203     }
204     for (int32_t i = 0; i < kNumOutputBuffers; ++i) {
205         if (mOutputBuffer[i]) {
206             free(mOutputBuffer[i]);
207             mOutputBuffer[i] = nullptr;
208         }
209     }
210     mNumSamplesOutput = 0;
211     mFramesConfigured = false;
212     mSignalledOutputEos = false;
213     mSignalledError = false;
214 
215     return C2_OK;
216 }
217 
onReset()218 void C2SoftMpeg4Dec::onReset() {
219     (void)onStop();
220     (void)onInit();
221 }
222 
onRelease()223 void C2SoftMpeg4Dec::onRelease() {
224     if (mInitialized) {
225         if (mDecHandle) {
226             PVCleanUpVideoDecoder(mDecHandle);
227             delete mDecHandle;
228             mDecHandle = nullptr;
229         }
230         mInitialized = false;
231     }
232     if (mOutBlock) {
233         mOutBlock.reset();
234     }
235     for (int32_t i = 0; i < kNumOutputBuffers; ++i) {
236         if (mOutputBuffer[i]) {
237             free(mOutputBuffer[i]);
238             mOutputBuffer[i] = nullptr;
239         }
240     }
241 }
242 
onFlush_sm()243 c2_status_t C2SoftMpeg4Dec::onFlush_sm() {
244     if (mInitialized) {
245         if (PV_TRUE != PVResetVideoDecoder(mDecHandle)) {
246             return C2_CORRUPTED;
247         }
248     }
249     mSignalledOutputEos = false;
250     mSignalledError = false;
251     return C2_OK;
252 }
253 
initDecoder()254 status_t C2SoftMpeg4Dec::initDecoder() {
255 #ifdef MPEG4
256     mIsMpeg4 = true;
257 #else
258     mIsMpeg4 = false;
259 #endif
260     if (!mDecHandle) {
261         mDecHandle = new tagvideoDecControls;
262     }
263     memset(mDecHandle, 0, sizeof(tagvideoDecControls));
264 
265     /* TODO: bring these values to 352 and 288. It cannot be done as of now
266      * because, h263 doesn't seem to allow port reconfiguration. In OMX, the
267      * problem of larger width and height than default width and height is
268      * overcome by adaptivePlayBack() api call. This call gets width and height
269      * information from extractor. Such a thing is not possible here.
270      * So we are configuring to larger values.*/
271     mWidth = 1408;
272     mHeight = 1152;
273     mNumSamplesOutput = 0;
274     mInitialized = false;
275     mFramesConfigured = false;
276     mSignalledOutputEos = false;
277     mSignalledError = false;
278 
279     return OK;
280 }
281 
fillEmptyWork(const std::unique_ptr<C2Work> & work)282 void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
283     uint32_t flags = 0;
284     if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
285         flags |= C2FrameData::FLAG_END_OF_STREAM;
286         ALOGV("signalling eos");
287     }
288     work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
289     work->worklets.front()->output.buffers.clear();
290     work->worklets.front()->output.ordinal = work->input.ordinal;
291     work->workletsProcessed = 1u;
292 }
293 
finishWork(uint64_t index,const std::unique_ptr<C2Work> & work)294 void C2SoftMpeg4Dec::finishWork(uint64_t index, const std::unique_ptr<C2Work> &work) {
295     std::shared_ptr<C2Buffer> buffer = createGraphicBuffer(std::move(mOutBlock),
296                                                            C2Rect(mWidth, mHeight));
297     mOutBlock = nullptr;
298     auto fillWork = [buffer, index](const std::unique_ptr<C2Work> &work) {
299         uint32_t flags = 0;
300         if ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) &&
301                 (c2_cntr64_t(index) == work->input.ordinal.frameIndex)) {
302             flags |= C2FrameData::FLAG_END_OF_STREAM;
303             ALOGV("signalling eos");
304         }
305         work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
306         work->worklets.front()->output.buffers.clear();
307         work->worklets.front()->output.buffers.push_back(buffer);
308         work->worklets.front()->output.ordinal = work->input.ordinal;
309         work->workletsProcessed = 1u;
310     };
311     if (work && c2_cntr64_t(index) == work->input.ordinal.frameIndex) {
312         fillWork(work);
313     } else {
314         finish(index, fillWork);
315     }
316 }
317 
ensureDecoderState(const std::shared_ptr<C2BlockPool> & pool)318 c2_status_t C2SoftMpeg4Dec::ensureDecoderState(const std::shared_ptr<C2BlockPool> &pool) {
319     if (!mDecHandle) {
320         ALOGE("not supposed to be here, invalid decoder context");
321         return C2_CORRUPTED;
322     }
323 
324     uint32_t outSize = align(mWidth, 16) * align(mHeight, 16) * 3 / 2;
325     for (int32_t i = 0; i < kNumOutputBuffers; ++i) {
326         if (!mOutputBuffer[i]) {
327             mOutputBuffer[i] = (uint8_t *)malloc(outSize * sizeof(uint8_t));
328             if (!mOutputBuffer[i]) {
329                 return C2_NO_MEMORY;
330             }
331         }
332     }
333     if (mOutBlock &&
334             (mOutBlock->width() != align(mWidth, 16) || mOutBlock->height() != mHeight)) {
335         mOutBlock.reset();
336     }
337     if (!mOutBlock) {
338         uint32_t format = HAL_PIXEL_FORMAT_YV12;
339         C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
340         c2_status_t err = pool->fetchGraphicBlock(align(mWidth, 16), mHeight, format, usage, &mOutBlock);
341         if (err != C2_OK) {
342             ALOGE("fetchGraphicBlock for Output failed with status %d", err);
343             return err;
344         }
345         ALOGV("provided (%dx%d) required (%dx%d)",
346               mOutBlock->width(), mOutBlock->height(), mWidth, mHeight);
347     }
348     return C2_OK;
349 }
350 
handleResChange(const std::unique_ptr<C2Work> & work)351 bool C2SoftMpeg4Dec::handleResChange(const std::unique_ptr<C2Work> &work) {
352     uint32_t disp_width, disp_height;
353     PVGetVideoDimensions(mDecHandle, (int32 *)&disp_width, (int32 *)&disp_height);
354 
355     uint32_t buf_width, buf_height;
356     PVGetBufferDimensions(mDecHandle, (int32 *)&buf_width, (int32 *)&buf_height);
357 
358     CHECK_LE(disp_width, buf_width);
359     CHECK_LE(disp_height, buf_height);
360 
361     ALOGV("display size (%dx%d), buffer size (%dx%d)",
362            disp_width, disp_height, buf_width, buf_height);
363 
364     bool resChanged = false;
365     if (disp_width != mWidth || disp_height != mHeight) {
366         mWidth = disp_width;
367         mHeight = disp_height;
368         resChanged = true;
369         for (int32_t i = 0; i < kNumOutputBuffers; ++i) {
370             if (mOutputBuffer[i]) {
371                 free(mOutputBuffer[i]);
372                 mOutputBuffer[i] = nullptr;
373             }
374         }
375 
376         if (!mIsMpeg4) {
377             PVCleanUpVideoDecoder(mDecHandle);
378 
379             uint8_t *vol_data[1]{};
380             int32_t vol_size = 0;
381 
382             if (!PVInitVideoDecoder(
383                     mDecHandle, vol_data, &vol_size, 1, mWidth, mHeight, H263_MODE)) {
384                 ALOGE("Error in PVInitVideoDecoder H263_MODE while resChanged was set to true");
385                 work->result = C2_CORRUPTED;
386                 mSignalledError = true;
387                 return true;
388             }
389         }
390         mFramesConfigured = false;
391     }
392     return resChanged;
393 }
394 
395 /* TODO: can remove temporary copy after library supports writing to display
396  * buffer Y, U and V plane pointers using stride info. */
copyOutputBufferToYV12Frame(uint8_t * dst,uint8_t * src,size_t dstYStride,size_t srcYStride,uint32_t width,uint32_t height)397 static void copyOutputBufferToYV12Frame(uint8_t *dst, uint8_t *src, size_t dstYStride,
398                                         size_t srcYStride, uint32_t width, uint32_t height) {
399     size_t dstUVStride = align(dstYStride / 2, 16);
400     size_t srcUVStride = srcYStride / 2;
401     uint8_t *srcStart = src;
402     uint8_t *dstStart = dst;
403     size_t vStride = align(height, 16);
404     for (size_t i = 0; i < height; ++i) {
405          memcpy(dst, src, width);
406          src += srcYStride;
407          dst += dstYStride;
408     }
409     /* U buffer */
410     src = srcStart + vStride * srcYStride;
411     dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
412     for (size_t i = 0; i < height / 2; ++i) {
413          memcpy(dst, src, width / 2);
414          src += srcUVStride;
415          dst += dstUVStride;
416     }
417     /* V buffer */
418     src = srcStart + vStride * srcYStride * 5 / 4;
419     dst = dstStart + (dstYStride * height);
420     for (size_t i = 0; i < height / 2; ++i) {
421          memcpy(dst, src, width / 2);
422          src += srcUVStride;
423          dst += dstUVStride;
424     }
425 }
426 
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)427 void C2SoftMpeg4Dec::process(
428         const std::unique_ptr<C2Work> &work,
429         const std::shared_ptr<C2BlockPool> &pool) {
430     work->result = C2_OK;
431     work->workletsProcessed = 0u;
432     work->worklets.front()->output.configUpdate.clear();
433     if (mSignalledError || mSignalledOutputEos) {
434         work->result = C2_BAD_VALUE;
435         return;
436     }
437 
438     size_t inOffset = 0u;
439     size_t inSize = 0u;
440     uint32_t workIndex = work->input.ordinal.frameIndex.peeku() & 0xFFFFFFFF;
441     C2ReadView rView = mDummyReadView;
442     if (!work->input.buffers.empty()) {
443         rView = work->input.buffers[0]->data().linearBlocks().front().map().get();
444         inSize = rView.capacity();
445         if (inSize && rView.error()) {
446             ALOGE("read view map failed %d", rView.error());
447             work->result = C2_CORRUPTED;
448             return;
449         }
450     }
451     ALOGV("in buffer attr. size %zu timestamp %d frameindex %d, flags %x",
452           inSize, (int)work->input.ordinal.timestamp.peeku(),
453           (int)work->input.ordinal.frameIndex.peeku(), work->input.flags);
454 
455     bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
456     if (inSize == 0) {
457         fillEmptyWork(work);
458         if (eos) {
459             mSignalledOutputEos = true;
460         }
461         return;
462     }
463 
464     uint8_t *bitstream = const_cast<uint8_t *>(rView.data() + inOffset);
465     uint32_t *start_code = (uint32_t *)bitstream;
466     bool volHeader = *start_code == 0xB0010000;
467     if (volHeader) {
468         PVCleanUpVideoDecoder(mDecHandle);
469         mInitialized = false;
470     }
471 
472     if (!mInitialized) {
473         uint8_t *vol_data[1]{};
474         int32_t vol_size = 0;
475 
476         bool codecConfig = (work->input.flags & C2FrameData::FLAG_CODEC_CONFIG) != 0;
477         if (codecConfig || volHeader) {
478             vol_data[0] = bitstream;
479             vol_size = inSize;
480         }
481         MP4DecodingMode mode = (mIsMpeg4) ? MPEG4_MODE : H263_MODE;
482 
483         if (!PVInitVideoDecoder(
484                 mDecHandle, vol_data, &vol_size, 1,
485                 mWidth, mHeight, mode)) {
486             ALOGE("PVInitVideoDecoder failed. Unsupported content?");
487             work->result = C2_CORRUPTED;
488             mSignalledError = true;
489             return;
490         }
491         mInitialized = true;
492         MP4DecodingMode actualMode = PVGetDecBitstreamMode(mDecHandle);
493         if (mode != actualMode) {
494             ALOGE("Decoded mode not same as actual mode of the decoder");
495             work->result = C2_CORRUPTED;
496             mSignalledError = true;
497             return;
498         }
499 
500         PVSetPostProcType(mDecHandle, 0);
501         if (handleResChange(work)) {
502             ALOGI("Setting width and height");
503             C2VideoSizeStreamInfo::output size(0u, mWidth, mHeight);
504             std::vector<std::unique_ptr<C2SettingResult>> failures;
505             c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
506             if (err == OK) {
507                 work->worklets.front()->output.configUpdate.push_back(
508                     C2Param::Copy(size));
509             } else {
510                 ALOGE("Config update size failed");
511                 mSignalledError = true;
512                 work->result = C2_CORRUPTED;
513                 return;
514             }
515         }
516         if (codecConfig) {
517             fillEmptyWork(work);
518             return;
519         }
520     }
521 
522     size_t inPos = 0;
523     while (inPos < inSize) {
524         c2_status_t err = ensureDecoderState(pool);
525         if (C2_OK != err) {
526             mSignalledError = true;
527             work->result = err;
528             return;
529         }
530         C2GraphicView wView = mOutBlock->map().get();
531         if (wView.error()) {
532             ALOGE("graphic view map failed %d", wView.error());
533             work->result = C2_CORRUPTED;
534             return;
535         }
536 
537         uint32_t outSize = align(mWidth, 16) * align(mHeight, 16) * 3 / 2;
538         uint32_t yFrameSize = sizeof(uint8) * mDecHandle->size;
539         if (outSize < yFrameSize * 3 / 2){
540             ALOGE("Too small output buffer: %d bytes", outSize);
541             work->result = C2_NO_MEMORY;
542             mSignalledError = true;
543             return;
544         }
545 
546         if (!mFramesConfigured) {
547             PVSetReferenceYUV(mDecHandle,mOutputBuffer[1]);
548             mFramesConfigured = true;
549         }
550 
551         // Need to check if header contains new info, e.g., width/height, etc.
552         VopHeaderInfo header_info;
553         uint32_t useExtTimestamp = (inPos == 0);
554         int32_t tmpInSize = (int32_t)inSize;
555         uint8_t *bitstreamTmp = bitstream;
556         uint32_t timestamp = workIndex;
557         if (PVDecodeVopHeader(
558                     mDecHandle, &bitstreamTmp, &timestamp, &tmpInSize,
559                     &header_info, &useExtTimestamp,
560                     mOutputBuffer[mNumSamplesOutput & 1]) != PV_TRUE) {
561             ALOGE("failed to decode vop header.");
562             work->result = C2_CORRUPTED;
563             mSignalledError = true;
564             return;
565         }
566 
567         // H263 doesn't have VOL header, the frame size information is in short header, i.e. the
568         // decoder may detect size change after PVDecodeVopHeader.
569         bool resChange = handleResChange(work);
570         if (mIsMpeg4 && resChange) {
571             work->result = C2_CORRUPTED;
572             mSignalledError = true;
573             return;
574         } else if (resChange) {
575             ALOGI("Setting width and height");
576             C2VideoSizeStreamInfo::output size(0u, mWidth, mHeight);
577             std::vector<std::unique_ptr<C2SettingResult>> failures;
578             c2_status_t err = mIntf->config({&size}, C2_MAY_BLOCK, &failures);
579             if (err == OK) {
580                 work->worklets.front()->output.configUpdate.push_back(C2Param::Copy(size));
581             } else {
582                 ALOGE("Config update size failed");
583                 mSignalledError = true;
584                 work->result = C2_CORRUPTED;
585                 return;
586             }
587             continue;
588         }
589 
590         if (PVDecodeVopBody(mDecHandle, &tmpInSize) != PV_TRUE) {
591             ALOGE("failed to decode video frame.");
592             work->result = C2_CORRUPTED;
593             mSignalledError = true;
594             return;
595         }
596         if (handleResChange(work)) {
597             work->result = C2_CORRUPTED;
598             mSignalledError = true;
599             return;
600         }
601 
602         uint8_t *outputBufferY = wView.data()[C2PlanarLayout::PLANE_Y];
603         (void)copyOutputBufferToYV12Frame(outputBufferY, mOutputBuffer[mNumSamplesOutput & 1],
604                                           wView.width(), align(mWidth, 16), mWidth, mHeight);
605 
606         inPos += inSize - (size_t)tmpInSize;
607         finishWork(workIndex, work);
608         ++mNumSamplesOutput;
609         if (inSize - inPos != 0) {
610             ALOGD("decoded frame, ignoring further trailing bytes %d",
611                   (int)inSize - (int)inPos);
612             break;
613         }
614     }
615 }
616 
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)617 c2_status_t C2SoftMpeg4Dec::drain(
618         uint32_t drainMode,
619         const std::shared_ptr<C2BlockPool> &pool) {
620     (void)pool;
621     if (drainMode == NO_DRAIN) {
622         ALOGW("drain with NO_DRAIN: no-op");
623         return C2_OK;
624     }
625     if (drainMode == DRAIN_CHAIN) {
626         ALOGW("DRAIN_CHAIN not supported");
627         return C2_OMITTED;
628     }
629     return C2_OK;
630 }
631 
632 class C2SoftMpeg4DecFactory : public C2ComponentFactory {
633 public:
C2SoftMpeg4DecFactory()634     C2SoftMpeg4DecFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
635         GetCodec2PlatformComponentStore()->getParamReflector())) {
636     }
637 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)638     virtual c2_status_t createComponent(
639             c2_node_id_t id,
640             std::shared_ptr<C2Component>* const component,
641             std::function<void(C2Component*)> deleter) override {
642         *component = std::shared_ptr<C2Component>(
643                 new C2SoftMpeg4Dec(COMPONENT_NAME,
644                                    id,
645                                    std::make_shared<C2SoftMpeg4Dec::IntfImpl>(mHelper)),
646                 deleter);
647         return C2_OK;
648     }
649 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)650     virtual c2_status_t createInterface(
651             c2_node_id_t id,
652             std::shared_ptr<C2ComponentInterface>* const interface,
653             std::function<void(C2ComponentInterface*)> deleter) override {
654         *interface = std::shared_ptr<C2ComponentInterface>(
655                 new SimpleInterface<C2SoftMpeg4Dec::IntfImpl>(
656                         COMPONENT_NAME, id, std::make_shared<C2SoftMpeg4Dec::IntfImpl>(mHelper)),
657                 deleter);
658         return C2_OK;
659     }
660 
661     virtual ~C2SoftMpeg4DecFactory() override = default;
662 
663 private:
664     std::shared_ptr<C2ReflectorHelper> mHelper;
665 };
666 
667 }  // namespace android
668 
CreateCodec2Factory()669 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
670     ALOGV("in %s", __func__);
671     return new ::android::C2SoftMpeg4DecFactory();
672 }
673 
DestroyCodec2Factory(::C2ComponentFactory * factory)674 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
675     ALOGV("in %s", __func__);
676     delete factory;
677 }
678