• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #ifdef MPEG4
19   #define LOG_TAG "C2SoftMpeg4Enc"
20 #else
21   #define LOG_TAG "C2SoftH263Enc"
22 #endif
23 #include <log/log.h>
24 
25 #include <inttypes.h>
26 
27 #include <media/hardware/VideoAPI.h>
28 #include <media/stagefright/foundation/AUtils.h>
29 #include <media/stagefright/MediaDefs.h>
30 #include <utils/misc.h>
31 
32 #include <C2Debug.h>
33 #include <C2PlatformSupport.h>
34 #include <SimpleC2Interface.h>
35 #include <util/C2InterfaceHelper.h>
36 
37 #include "C2SoftMpeg4Enc.h"
38 #include "mp4enc_api.h"
39 
40 namespace android {
41 
42 #ifdef MPEG4
43 constexpr char COMPONENT_NAME[] = "c2.android.mpeg4.encoder";
44 #else
45 constexpr char COMPONENT_NAME[] = "c2.android.h263.encoder";
46 #endif
47 
48 class C2SoftMpeg4Enc::IntfImpl : public C2InterfaceHelper {
49    public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)50     explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper>& helper)
51         : C2InterfaceHelper(helper) {
52         setDerivedInstance(this);
53 
54         addParameter(
55             DefineParam(mInputFormat, C2_NAME_INPUT_STREAM_FORMAT_SETTING)
56                 .withConstValue(
57                     new C2StreamFormatConfig::input(0u, C2FormatVideo))
58                 .build());
59 
60         addParameter(
61             DefineParam(mOutputFormat, C2_NAME_OUTPUT_STREAM_FORMAT_SETTING)
62                 .withConstValue(
63                     new C2StreamFormatConfig::output(0u, C2FormatCompressed))
64                 .build());
65 
66         addParameter(
67             DefineParam(mInputMediaType, C2_NAME_INPUT_PORT_MIME_SETTING)
68                 .withConstValue(AllocSharedString<C2PortMimeConfig::input>(
69                     MEDIA_MIMETYPE_VIDEO_RAW))
70                 .build());
71 
72         addParameter(
73             DefineParam(mOutputMediaType, C2_NAME_OUTPUT_PORT_MIME_SETTING)
74                 .withConstValue(AllocSharedString<C2PortMimeConfig::output>(
75 #ifdef MPEG4
76                     MEDIA_MIMETYPE_VIDEO_MPEG4
77 #else
78                     MEDIA_MIMETYPE_VIDEO_H263
79 #endif
80                     ))
81                 .build());
82 
83         addParameter(DefineParam(mUsage, C2_NAME_INPUT_STREAM_USAGE_SETTING)
84                          .withConstValue(new C2StreamUsageTuning::input(
85                              0u, (uint64_t)C2MemoryUsage::CPU_READ))
86                          .build());
87 
88         addParameter(
89             DefineParam(mSize, C2_NAME_STREAM_VIDEO_SIZE_SETTING)
90                 .withDefault(new C2VideoSizeStreamTuning::input(0u, 176, 144))
91                 .withFields({
92 #ifdef MPEG4
93                     C2F(mSize, width).inRange(16, 176, 16),
94                     C2F(mSize, height).inRange(16, 144, 16),
95 #else
96                     C2F(mSize, width).oneOf({176, 352}),
97                     C2F(mSize, height).oneOf({144, 288}),
98 #endif
99                 })
100                 .withSetter(SizeSetter)
101                 .build());
102 
103         addParameter(
104             DefineParam(mFrameRate, C2_NAME_STREAM_FRAME_RATE_SETTING)
105                 .withDefault(new C2StreamFrameRateInfo::output(0u, 17.))
106                 // TODO: More restriction?
107                 .withFields({C2F(mFrameRate, value).greaterThan(0.)})
108                 .withSetter(
109                     Setter<decltype(*mFrameRate)>::StrictValueWithNoDeps)
110                 .build());
111 
112         addParameter(
113             DefineParam(mBitrate, C2_NAME_STREAM_BITRATE_SETTING)
114                 .withDefault(new C2BitrateTuning::output(0u, 64000))
115                 .withFields({C2F(mBitrate, value).inRange(4096, 12000000)})
116                 .withSetter(BitrateSetter)
117                 .build());
118 
119         addParameter(
120                 DefineParam(mSyncFramePeriod, C2_PARAMKEY_SYNC_FRAME_INTERVAL)
121                 .withDefault(new C2StreamSyncFrameIntervalTuning::output(0u, 1000000))
122                 .withFields({C2F(mSyncFramePeriod, value).any()})
123                 .withSetter(Setter<decltype(*mSyncFramePeriod)>::StrictValueWithNoDeps)
124                 .build());
125 
126 #ifdef MPEG4
127         addParameter(
128                 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
129                 .withDefault(new C2StreamProfileLevelInfo::output(
130                         0u, PROFILE_MP4V_SIMPLE, LEVEL_MP4V_2))
131                 .withFields({
132                     C2F(mProfileLevel, profile).equalTo(
133                             PROFILE_MP4V_SIMPLE),
134                     C2F(mProfileLevel, level).oneOf({
135                             C2Config::LEVEL_MP4V_0,
136                             C2Config::LEVEL_MP4V_0B,
137                             C2Config::LEVEL_MP4V_1,
138                             C2Config::LEVEL_MP4V_2})
139                 })
140                 .withSetter(ProfileLevelSetter)
141                 .build());
142 #else
143         addParameter(
144                 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
145                 .withDefault(new C2StreamProfileLevelInfo::output(
146                         0u, PROFILE_H263_BASELINE, LEVEL_H263_45))
147                 .withFields({
148                     C2F(mProfileLevel, profile).equalTo(
149                             PROFILE_H263_BASELINE),
150                     C2F(mProfileLevel, level).oneOf({
151                             C2Config::LEVEL_H263_10,
152                             C2Config::LEVEL_H263_20,
153                             C2Config::LEVEL_H263_30,
154                             C2Config::LEVEL_H263_40,
155                             C2Config::LEVEL_H263_45})
156                 })
157                 .withSetter(ProfileLevelSetter)
158                 .build());
159 #endif
160     }
161 
BitrateSetter(bool mayBlock,C2P<C2StreamBitrateInfo::output> & me)162     static C2R BitrateSetter(bool mayBlock, C2P<C2StreamBitrateInfo::output> &me) {
163         (void)mayBlock;
164         C2R res = C2R::Ok();
165         if (me.v.value <= 4096) {
166             me.set().value = 4096;
167         }
168         return res;
169     }
170 
SizeSetter(bool mayBlock,const C2P<C2StreamPictureSizeInfo::input> & oldMe,C2P<C2StreamPictureSizeInfo::input> & me)171     static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::input> &oldMe,
172                           C2P<C2StreamPictureSizeInfo::input> &me) {
173         (void)mayBlock;
174         C2R res = C2R::Ok();
175         if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
176             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
177             me.set().width = oldMe.v.width;
178         }
179         if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
180             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
181             me.set().height = oldMe.v.height;
182         }
183         return res;
184     }
185 
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::output> & me)186     static C2R ProfileLevelSetter(
187             bool mayBlock,
188             C2P<C2StreamProfileLevelInfo::output> &me) {
189         (void)mayBlock;
190         if (!me.F(me.v.profile).supportsAtAll(me.v.profile)) {
191 #ifdef MPEG4
192             me.set().profile = PROFILE_MP4V_SIMPLE;
193 #else
194             me.set().profile = PROFILE_H263_BASELINE;
195 #endif
196         }
197         if (!me.F(me.v.level).supportsAtAll(me.v.level)) {
198 #ifdef MPEG4
199             me.set().level = LEVEL_MP4V_2;
200 #else
201             me.set().level = LEVEL_H263_45;
202 #endif
203         }
204         return C2R::Ok();
205     }
206 
207     // unsafe getters
getSize_l() const208     std::shared_ptr<C2StreamPictureSizeInfo::input> getSize_l() const { return mSize; }
getFrameRate_l() const209     std::shared_ptr<C2StreamFrameRateInfo::output> getFrameRate_l() const { return mFrameRate; }
getBitrate_l() const210     std::shared_ptr<C2StreamBitrateInfo::output> getBitrate_l() const { return mBitrate; }
getSyncFramePeriod() const211     uint32_t getSyncFramePeriod() const {
212         if (mSyncFramePeriod->value < 0 || mSyncFramePeriod->value == INT64_MAX) {
213             return 0;
214         }
215         double period = mSyncFramePeriod->value / 1e6 * mFrameRate->value;
216         return (uint32_t)c2_max(c2_min(period + 0.5, double(UINT32_MAX)), 1.);
217     }
218 
219    private:
220     std::shared_ptr<C2StreamFormatConfig::input> mInputFormat;
221     std::shared_ptr<C2StreamFormatConfig::output> mOutputFormat;
222     std::shared_ptr<C2PortMimeConfig::input> mInputMediaType;
223     std::shared_ptr<C2PortMimeConfig::output> mOutputMediaType;
224     std::shared_ptr<C2StreamUsageTuning::input> mUsage;
225     std::shared_ptr<C2VideoSizeStreamTuning::input> mSize;
226     std::shared_ptr<C2StreamFrameRateInfo::output> mFrameRate;
227     std::shared_ptr<C2BitrateTuning::output> mBitrate;
228     std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
229     std::shared_ptr<C2StreamSyncFrameIntervalTuning::output> mSyncFramePeriod;
230 };
231 
C2SoftMpeg4Enc(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)232 C2SoftMpeg4Enc::C2SoftMpeg4Enc(const char* name, c2_node_id_t id,
233                                const std::shared_ptr<IntfImpl>& intfImpl)
234     : SimpleC2Component(
235           std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
236       mIntf(intfImpl),
237       mHandle(nullptr),
238       mEncParams(nullptr),
239       mStarted(false),
240       mOutBufferSize(524288) {
241 }
242 
~C2SoftMpeg4Enc()243 C2SoftMpeg4Enc::~C2SoftMpeg4Enc() {
244     onRelease();
245 }
246 
onInit()247 c2_status_t C2SoftMpeg4Enc::onInit() {
248 #ifdef MPEG4
249     mEncodeMode = COMBINE_MODE_WITH_ERR_RES;
250 #else
251     mEncodeMode = H263_MODE;
252 #endif
253     if (!mHandle) {
254         mHandle = new tagvideoEncControls;
255     }
256 
257     if (!mEncParams) {
258         mEncParams = new tagvideoEncOptions;
259     }
260 
261     if (!(mEncParams && mHandle)) return C2_NO_MEMORY;
262 
263     mSignalledOutputEos = false;
264     mSignalledError = false;
265 
266     return initEncoder();
267 }
268 
onStop()269 c2_status_t C2SoftMpeg4Enc::onStop() {
270     if (!mStarted) {
271         return C2_OK;
272     }
273     if (mHandle) {
274         (void)PVCleanUpVideoEncoder(mHandle);
275     }
276     mStarted = false;
277     mSignalledOutputEos = false;
278     mSignalledError = false;
279     return C2_OK;
280 }
281 
onReset()282 void C2SoftMpeg4Enc::onReset() {
283     onStop();
284     initEncoder();
285 }
286 
onRelease()287 void C2SoftMpeg4Enc::onRelease() {
288     onStop();
289     if (mEncParams) {
290         delete mEncParams;
291         mEncParams = nullptr;
292     }
293     if (mHandle) {
294         delete mHandle;
295         mHandle = nullptr;
296     }
297 }
298 
onFlush_sm()299 c2_status_t C2SoftMpeg4Enc::onFlush_sm() {
300     return C2_OK;
301 }
302 
fillEmptyWork(const std::unique_ptr<C2Work> & work)303 static void fillEmptyWork(const std::unique_ptr<C2Work> &work) {
304     uint32_t flags = 0;
305     if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
306         flags |= C2FrameData::FLAG_END_OF_STREAM;
307         ALOGV("signalling eos");
308     }
309     work->worklets.front()->output.flags = (C2FrameData::flags_t)flags;
310     work->worklets.front()->output.buffers.clear();
311     work->worklets.front()->output.ordinal = work->input.ordinal;
312     work->workletsProcessed = 1u;
313 }
314 
initEncParams()315 c2_status_t C2SoftMpeg4Enc::initEncParams() {
316     if (mHandle) {
317         memset(mHandle, 0, sizeof(tagvideoEncControls));
318     } else return C2_CORRUPTED;
319     if (mEncParams) {
320         memset(mEncParams, 0, sizeof(tagvideoEncOptions));
321     } else return C2_CORRUPTED;
322 
323     if (!PVGetDefaultEncOption(mEncParams, 0)) {
324         ALOGE("Failed to get default encoding parameters");
325         return C2_CORRUPTED;
326     }
327 
328     if (mFrameRate->value == 0) {
329         ALOGE("Framerate should not be 0");
330         return C2_BAD_VALUE;
331     }
332 
333     mEncParams->encMode = mEncodeMode;
334     mEncParams->encWidth[0] = mSize->width;
335     mEncParams->encHeight[0] = mSize->height;
336     mEncParams->encFrameRate[0] = mFrameRate->value + 0.5;
337     mEncParams->rcType = VBR_1;
338     mEncParams->vbvDelay = 5.0f;
339     mEncParams->profile_level = CORE_PROFILE_LEVEL2;
340     mEncParams->packetSize = 32;
341     mEncParams->rvlcEnable = PV_OFF;
342     mEncParams->numLayers = 1;
343     mEncParams->timeIncRes = 1000;
344     mEncParams->tickPerSrc = mEncParams->timeIncRes / (mFrameRate->value + 0.5);
345     mEncParams->bitRate[0] = mBitrate->value;
346     mEncParams->iQuant[0] = 15;
347     mEncParams->pQuant[0] = 12;
348     mEncParams->quantType[0] = 0;
349     mEncParams->noFrameSkipped = PV_OFF;
350 
351     // PV's MPEG4 encoder requires the video dimension of multiple
352     if (mSize->width % 16 != 0 || mSize->height % 16 != 0) {
353         ALOGE("Video frame size %dx%d must be a multiple of 16",
354               mSize->width, mSize->height);
355         return C2_BAD_VALUE;
356     }
357 
358     // Set IDR frame refresh interval
359     mEncParams->intraPeriod = mIntf->getSyncFramePeriod();
360     mEncParams->numIntraMB = 0;
361     mEncParams->sceneDetect = PV_ON;
362     mEncParams->searchRange = 16;
363     mEncParams->mv8x8Enable = PV_OFF;
364     mEncParams->gobHeaderInterval = 0;
365     mEncParams->useACPred = PV_ON;
366     mEncParams->intraDCVlcTh = 0;
367 
368     return C2_OK;
369 }
370 
initEncoder()371 c2_status_t C2SoftMpeg4Enc::initEncoder() {
372     if (mStarted) {
373         return C2_OK;
374     }
375     {
376         IntfImpl::Lock lock = mIntf->lock();
377         mSize = mIntf->getSize_l();
378         mBitrate = mIntf->getBitrate_l();
379         mFrameRate = mIntf->getFrameRate_l();
380     }
381     c2_status_t err = initEncParams();
382     if (C2_OK != err) {
383         ALOGE("Failed to initialized encoder params");
384         mSignalledError = true;
385         return err;
386     }
387     if (!PVInitVideoEncoder(mHandle, mEncParams)) {
388         ALOGE("Failed to initialize the encoder");
389         mSignalledError = true;
390         return C2_CORRUPTED;
391     }
392 
393     // 1st buffer for codec specific data
394     mNumInputFrames = -1;
395     mStarted = true;
396     return C2_OK;
397 }
398 
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)399 void C2SoftMpeg4Enc::process(
400         const std::unique_ptr<C2Work> &work,
401         const std::shared_ptr<C2BlockPool> &pool) {
402     // Initialize output work
403     work->result = C2_OK;
404     work->workletsProcessed = 1u;
405     work->worklets.front()->output.flags = work->input.flags;
406     if (mSignalledError || mSignalledOutputEos) {
407         work->result = C2_BAD_VALUE;
408         return;
409     }
410 
411     // Initialize encoder if not already initialized
412     if (!mStarted && C2_OK != initEncoder()) {
413         ALOGE("Failed to initialize encoder");
414         mSignalledError = true;
415         work->result = C2_CORRUPTED;
416         return;
417     }
418 
419     std::shared_ptr<C2LinearBlock> block;
420     C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
421     c2_status_t err = pool->fetchLinearBlock(mOutBufferSize, usage, &block);
422     if (err != C2_OK) {
423         ALOGE("fetchLinearBlock for Output failed with status %d", err);
424         work->result = C2_NO_MEMORY;
425         return;
426     }
427 
428     C2WriteView wView = block->map().get();
429     if (wView.error()) {
430         ALOGE("write view map failed %d", wView.error());
431         work->result = wView.error();
432         return;
433     }
434 
435     uint8_t *outPtr = (uint8_t *)wView.data();
436     if (mNumInputFrames < 0) {
437         // The very first thing we want to output is the codec specific data.
438         int32_t outputSize = mOutBufferSize;
439         if (!PVGetVolHeader(mHandle, outPtr, &outputSize, 0)) {
440             ALOGE("Failed to get VOL header");
441             mSignalledError = true;
442             work->result = C2_CORRUPTED;
443             return;
444         } else {
445             ALOGV("Bytes Generated in header %d\n", outputSize);
446         }
447 
448         ++mNumInputFrames;
449         std::unique_ptr<C2StreamCsdInfo::output> csd =
450             C2StreamCsdInfo::output::AllocUnique(outputSize, 0u);
451         if (!csd) {
452             ALOGE("CSD allocation failed");
453             mSignalledError = true;
454             work->result = C2_NO_MEMORY;
455             return;
456         }
457         memcpy(csd->m.value, outPtr, outputSize);
458         work->worklets.front()->output.configUpdate.push_back(std::move(csd));
459     }
460 
461     std::shared_ptr<const C2GraphicView> rView;
462     std::shared_ptr<C2Buffer> inputBuffer;
463     bool eos = ((work->input.flags & C2FrameData::FLAG_END_OF_STREAM) != 0);
464     if (!work->input.buffers.empty()) {
465         inputBuffer = work->input.buffers[0];
466         rView = std::make_shared<const C2GraphicView>(
467                 inputBuffer->data().graphicBlocks().front().map().get());
468         if (rView->error() != C2_OK) {
469             ALOGE("graphic view map err = %d", rView->error());
470             work->result = rView->error();
471             return;
472         }
473     } else {
474         fillEmptyWork(work);
475         if (eos) {
476             mSignalledOutputEos = true;
477             ALOGV("signalled EOS");
478         }
479         return;
480     }
481 
482     uint64_t inputTimeStamp = work->input.ordinal.timestamp.peekull();
483     const C2ConstGraphicBlock inBuffer = inputBuffer->data().graphicBlocks().front();
484     if (inBuffer.width() < mSize->width ||
485         inBuffer.height() < mSize->height) {
486         /* Expect width height to be configured */
487         ALOGW("unexpected Capacity Aspect %d(%d) x %d(%d)", inBuffer.width(),
488               mSize->width, inBuffer.height(), mSize->height);
489         work->result = C2_BAD_VALUE;
490         return;
491     }
492 
493     const C2PlanarLayout &layout = rView->layout();
494     uint8_t *yPlane = const_cast<uint8_t *>(rView->data()[C2PlanarLayout::PLANE_Y]);
495     uint8_t *uPlane = const_cast<uint8_t *>(rView->data()[C2PlanarLayout::PLANE_U]);
496     uint8_t *vPlane = const_cast<uint8_t *>(rView->data()[C2PlanarLayout::PLANE_V]);
497     int32_t yStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
498     int32_t uStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
499     int32_t vStride = layout.planes[C2PlanarLayout::PLANE_V].rowInc;
500     uint32_t width = mSize->width;
501     uint32_t height = mSize->height;
502     // width and height are always even (as block size is 16x16)
503     CHECK_EQ((width & 1u), 0u);
504     CHECK_EQ((height & 1u), 0u);
505     size_t yPlaneSize = width * height;
506     switch (layout.type) {
507         case C2PlanarLayout::TYPE_RGB:
508             [[fallthrough]];
509         case C2PlanarLayout::TYPE_RGBA: {
510             MemoryBlock conversionBuffer = mConversionBuffers.fetch(yPlaneSize * 3 / 2);
511             mConversionBuffersInUse.emplace(conversionBuffer.data(), conversionBuffer);
512             yPlane = conversionBuffer.data();
513             uPlane = yPlane + yPlaneSize;
514             vPlane = uPlane + yPlaneSize / 4;
515             yStride = width;
516             uStride = vStride = width / 2;
517             ConvertRGBToPlanarYUV(yPlane, yStride, height, conversionBuffer.size(), *rView.get());
518             break;
519         }
520         case C2PlanarLayout::TYPE_YUV: {
521             if (!IsYUV420(*rView)) {
522                 ALOGE("input is not YUV420");
523                 work->result = C2_BAD_VALUE;
524                 break;
525             }
526 
527             if (layout.planes[layout.PLANE_Y].colInc == 1
528                     && layout.planes[layout.PLANE_U].colInc == 1
529                     && layout.planes[layout.PLANE_V].colInc == 1
530                     && uStride == vStride
531                     && yStride == 2 * vStride) {
532                 // I420 compatible - planes are already set up above
533                 break;
534             }
535 
536             // copy to I420
537             MemoryBlock conversionBuffer = mConversionBuffers.fetch(yPlaneSize * 3 / 2);
538             mConversionBuffersInUse.emplace(conversionBuffer.data(), conversionBuffer);
539             MediaImage2 img = CreateYUV420PlanarMediaImage2(width, height, width, height);
540             status_t err = ImageCopy(conversionBuffer.data(), &img, *rView);
541             if (err != OK) {
542                 ALOGE("Buffer conversion failed: %d", err);
543                 work->result = C2_BAD_VALUE;
544                 return;
545             }
546             yPlane = conversionBuffer.data();
547             uPlane = yPlane + yPlaneSize;
548             vPlane = uPlane + yPlaneSize / 4;
549             yStride = width;
550             uStride = vStride = width / 2;
551             break;
552         }
553 
554         case C2PlanarLayout::TYPE_YUVA:
555             ALOGE("YUVA plane type is not supported");
556             work->result = C2_BAD_VALUE;
557             return;
558 
559         default:
560             ALOGE("Unrecognized plane type: %d", layout.type);
561             work->result = C2_BAD_VALUE;
562             return;
563     }
564 
565     CHECK(NULL != yPlane);
566     /* Encode frames */
567     VideoEncFrameIO vin, vout;
568     memset(&vin, 0, sizeof(vin));
569     memset(&vout, 0, sizeof(vout));
570     vin.yChan = yPlane;
571     vin.uChan = uPlane;
572     vin.vChan = vPlane;
573     vin.timestamp = (inputTimeStamp + 500) / 1000;  // in ms
574     vin.height = align(height, 16);
575     vin.pitch = align(width, 16);
576 
577     uint32_t modTimeMs = 0;
578     int32_t nLayer = 0;
579     MP4HintTrack hintTrack;
580     int32_t outputSize = mOutBufferSize;
581     if (!PVEncodeVideoFrame(mHandle, &vin, &vout, &modTimeMs, outPtr, &outputSize, &nLayer) ||
582         !PVGetHintTrack(mHandle, &hintTrack)) {
583         ALOGE("Failed to encode frame or get hint track at frame %" PRId64, mNumInputFrames);
584         mSignalledError = true;
585         work->result = C2_CORRUPTED;
586         return;
587     }
588     ALOGV("outputSize filled : %d", outputSize);
589     ++mNumInputFrames;
590     CHECK(NULL == PVGetOverrunBuffer(mHandle));
591 
592     fillEmptyWork(work);
593     if (outputSize) {
594         std::shared_ptr<C2Buffer> buffer = createLinearBuffer(block, 0, outputSize);
595         work->worklets.front()->output.ordinal.timestamp = inputTimeStamp;
596         if (hintTrack.CodeType == 0) {
597             buffer->setInfo(std::make_shared<C2StreamPictureTypeMaskInfo::output>(
598                     0u /* stream id */, C2PictureTypeKeyFrame));
599         }
600         work->worklets.front()->output.buffers.push_back(buffer);
601     }
602     if (eos) {
603         mSignalledOutputEos = true;
604     }
605 
606     mConversionBuffersInUse.erase(yPlane);
607 }
608 
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)609 c2_status_t C2SoftMpeg4Enc::drain(
610         uint32_t drainMode,
611         const std::shared_ptr<C2BlockPool> &pool) {
612     (void)pool;
613     if (drainMode == NO_DRAIN) {
614         ALOGW("drain with NO_DRAIN: no-op");
615         return C2_OK;
616     }
617     if (drainMode == DRAIN_CHAIN) {
618         ALOGW("DRAIN_CHAIN not supported");
619         return C2_OMITTED;
620     }
621 
622     return C2_OK;
623 }
624 
625 class C2SoftMpeg4EncFactory : public C2ComponentFactory {
626 public:
C2SoftMpeg4EncFactory()627     C2SoftMpeg4EncFactory()
628         : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
629               GetCodec2PlatformComponentStore()->getParamReflector())) {}
630 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)631     virtual c2_status_t createComponent(
632             c2_node_id_t id,
633             std::shared_ptr<C2Component>* const component,
634             std::function<void(C2Component*)> deleter) override {
635         *component = std::shared_ptr<C2Component>(
636             new C2SoftMpeg4Enc(
637                 COMPONENT_NAME, id,
638                 std::make_shared<C2SoftMpeg4Enc::IntfImpl>(mHelper)),
639             deleter);
640         return C2_OK;
641     }
642 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)643     virtual c2_status_t createInterface(
644             c2_node_id_t id,
645             std::shared_ptr<C2ComponentInterface>* const interface,
646             std::function<void(C2ComponentInterface*)> deleter) override {
647         *interface = std::shared_ptr<C2ComponentInterface>(
648             new SimpleInterface<C2SoftMpeg4Enc::IntfImpl>(
649                 COMPONENT_NAME, id,
650                 std::make_shared<C2SoftMpeg4Enc::IntfImpl>(mHelper)),
651             deleter);
652         return C2_OK;
653     }
654 
655     virtual ~C2SoftMpeg4EncFactory() override = default;
656 
657 private:
658     std::shared_ptr<C2ReflectorHelper> mHelper;
659 };
660 
661 }  // namespace android
662 
CreateCodec2Factory()663 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
664     ALOGV("in %s", __func__);
665     return new ::android::C2SoftMpeg4EncFactory();
666 }
667 
DestroyCodec2Factory(::C2ComponentFactory * factory)668 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
669     ALOGV("in %s", __func__);
670     delete factory;
671 }
672