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 #define LOG_TAG "C2SoftAvcEnc"
19 #include <log/log.h>
20 #include <utils/misc.h>
21 
22 #include <media/hardware/VideoAPI.h>
23 #include <media/stagefright/MediaDefs.h>
24 #include <media/stagefright/MediaErrors.h>
25 #include <media/stagefright/MetaData.h>
26 #include <media/stagefright/foundation/AUtils.h>
27 
28 #include <C2Debug.h>
29 #include <C2PlatformSupport.h>
30 #include <Codec2BufferUtils.h>
31 #include <SimpleC2Interface.h>
32 #include <util/C2InterfaceHelper.h>
33 
34 #include "C2SoftAvcEnc.h"
35 #include "ih264e.h"
36 #include "ih264e_error.h"
37 
38 namespace android {
39 
40 namespace {
41 
42 constexpr char COMPONENT_NAME[] = "c2.android.avc.encoder";
43 constexpr uint32_t kMinOutBufferSize = 524288;
ParseGop(const C2StreamGopTuning::output & gop,uint32_t * syncInterval,uint32_t * iInterval,uint32_t * maxBframes)44 void ParseGop(
45         const C2StreamGopTuning::output &gop,
46         uint32_t *syncInterval, uint32_t *iInterval, uint32_t *maxBframes) {
47     uint32_t syncInt = 1;
48     uint32_t iInt = 1;
49     for (size_t i = 0; i < gop.flexCount(); ++i) {
50         const C2GopLayerStruct &layer = gop.m.values[i];
51         if (layer.count == UINT32_MAX) {
52             syncInt = 0;
53         } else if (syncInt <= UINT32_MAX / (layer.count + 1)) {
54             syncInt *= (layer.count + 1);
55         }
56         if ((layer.type_ & I_FRAME) == 0) {
57             if (layer.count == UINT32_MAX) {
58                 iInt = 0;
59             } else if (iInt <= UINT32_MAX / (layer.count + 1)) {
60                 iInt *= (layer.count + 1);
61             }
62         }
63         if (layer.type_ == C2Config::picture_type_t(P_FRAME | B_FRAME) && maxBframes) {
64             *maxBframes = layer.count;
65         }
66     }
67     if (syncInterval) {
68         *syncInterval = syncInt;
69     }
70     if (iInterval) {
71         *iInterval = iInt;
72     }
73 }
74 
75 }  // namespace
76 
77 class C2SoftAvcEnc::IntfImpl : public SimpleInterface<void>::BaseParams {
78 public:
IntfImpl(const std::shared_ptr<C2ReflectorHelper> & helper)79     explicit IntfImpl(const std::shared_ptr<C2ReflectorHelper> &helper)
80         : SimpleInterface<void>::BaseParams(
81                 helper,
82                 COMPONENT_NAME,
83                 C2Component::KIND_ENCODER,
84                 C2Component::DOMAIN_VIDEO,
85                 MEDIA_MIMETYPE_VIDEO_AVC) {
86         noPrivateBuffers(); // TODO: account for our buffers here
87         noInputReferences();
88         noOutputReferences();
89         noTimeStretch();
90         setDerivedInstance(this);
91 
92         addParameter(
93                 DefineParam(mUsage, C2_PARAMKEY_INPUT_STREAM_USAGE)
94                 .withConstValue(new C2StreamUsageTuning::input(
95                         0u, (uint64_t)C2MemoryUsage::CPU_READ))
96                 .build());
97 
98         addParameter(
99                 DefineParam(mAttrib, C2_PARAMKEY_COMPONENT_ATTRIBUTES)
100                 .withConstValue(new C2ComponentAttributesSetting(
101                     C2Component::ATTRIB_IS_TEMPORAL))
102                 .build());
103 
104         addParameter(
105                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
106                 .withDefault(new C2StreamPictureSizeInfo::input(0u, 16, 16))
107                 .withFields({
108                     C2F(mSize, width).inRange(2, 2560, 2),
109                     C2F(mSize, height).inRange(2, 2560, 2),
110                 })
111                 .withSetter(SizeSetter)
112                 .build());
113 
114         addParameter(
115                 DefineParam(mGop, C2_PARAMKEY_GOP)
116                 .withDefault(C2StreamGopTuning::output::AllocShared(
117                         0 /* flexCount */, 0u /* stream */))
118                 .withFields({C2F(mGop, m.values[0].type_).any(),
119                              C2F(mGop, m.values[0].count).any()})
120                 .withSetter(GopSetter)
121                 .build());
122 
123         addParameter(
124                 DefineParam(mActualInputDelay, C2_PARAMKEY_INPUT_DELAY)
125                 .withDefault(new C2PortActualDelayTuning::input(DEFAULT_B_FRAMES))
126                 .withFields({C2F(mActualInputDelay, value).inRange(0, MAX_B_FRAMES)})
127                 .calculatedAs(InputDelaySetter, mGop)
128                 .build());
129 
130         addParameter(
131                 DefineParam(mFrameRate, C2_PARAMKEY_FRAME_RATE)
132                 .withDefault(new C2StreamFrameRateInfo::output(0u, 1.))
133                 // TODO: More restriction?
134                 .withFields({C2F(mFrameRate, value).greaterThan(0.)})
135                 .withSetter(Setter<decltype(*mFrameRate)>::StrictValueWithNoDeps)
136                 .build());
137 
138         addParameter(
139                 DefineParam(mBitrate, C2_PARAMKEY_BITRATE)
140                 .withDefault(new C2StreamBitrateInfo::output(0u, 64000))
141                 .withFields({C2F(mBitrate, value).inRange(4096, 12000000)})
142                 .withSetter(BitrateSetter)
143                 .build());
144 
145         addParameter(
146                 DefineParam(mIntraRefresh, C2_PARAMKEY_INTRA_REFRESH)
147                 .withDefault(new C2StreamIntraRefreshTuning::output(
148                         0u, C2Config::INTRA_REFRESH_DISABLED, 0.))
149                 .withFields({
150                     C2F(mIntraRefresh, mode).oneOf({
151                         C2Config::INTRA_REFRESH_DISABLED, C2Config::INTRA_REFRESH_ARBITRARY }),
152                     C2F(mIntraRefresh, period).any()
153                 })
154                 .withSetter(IntraRefreshSetter)
155                 .build());
156 
157         addParameter(
158                 DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL)
159                 .withDefault(new C2StreamProfileLevelInfo::output(
160                         0u, PROFILE_AVC_CONSTRAINED_BASELINE, LEVEL_AVC_4_1))
161                 .withFields({
162                     C2F(mProfileLevel, profile).oneOf({
163                         PROFILE_AVC_BASELINE,
164                         PROFILE_AVC_CONSTRAINED_BASELINE,
165                         PROFILE_AVC_MAIN,
166                     }),
167                     C2F(mProfileLevel, level).oneOf({
168                         LEVEL_AVC_1,
169                         LEVEL_AVC_1B,
170                         LEVEL_AVC_1_1,
171                         LEVEL_AVC_1_2,
172                         LEVEL_AVC_1_3,
173                         LEVEL_AVC_2,
174                         LEVEL_AVC_2_1,
175                         LEVEL_AVC_2_2,
176                         LEVEL_AVC_3,
177                         LEVEL_AVC_3_1,
178                         LEVEL_AVC_3_2,
179                         LEVEL_AVC_4,
180                         LEVEL_AVC_4_1,
181                         LEVEL_AVC_4_2,
182                         LEVEL_AVC_5,
183                     }),
184                 })
185                 .withSetter(ProfileLevelSetter, mSize, mFrameRate, mBitrate)
186                 .build());
187 
188         addParameter(
189                 DefineParam(mRequestSync, C2_PARAMKEY_REQUEST_SYNC_FRAME)
190                 .withDefault(new C2StreamRequestSyncFrameTuning::output(0u, C2_FALSE))
191                 .withFields({C2F(mRequestSync, value).oneOf({ C2_FALSE, C2_TRUE }) })
192                 .withSetter(Setter<decltype(*mRequestSync)>::NonStrictValueWithNoDeps)
193                 .build());
194 
195         addParameter(
196                 DefineParam(mSyncFramePeriod, C2_PARAMKEY_SYNC_FRAME_INTERVAL)
197                 .withDefault(new C2StreamSyncFrameIntervalTuning::output(0u, 1000000))
198                 .withFields({C2F(mSyncFramePeriod, value).any()})
199                 .withSetter(Setter<decltype(*mSyncFramePeriod)>::StrictValueWithNoDeps)
200                 .build());
201     }
202 
InputDelaySetter(bool mayBlock,C2P<C2PortActualDelayTuning::input> & me,const C2P<C2StreamGopTuning::output> & gop)203     static C2R InputDelaySetter(
204             bool mayBlock,
205             C2P<C2PortActualDelayTuning::input> &me,
206             const C2P<C2StreamGopTuning::output> &gop) {
207         (void)mayBlock;
208         uint32_t maxBframes = 0;
209         ParseGop(gop.v, nullptr, nullptr, &maxBframes);
210         me.set().value = maxBframes;
211         return C2R::Ok();
212     }
213 
BitrateSetter(bool mayBlock,C2P<C2StreamBitrateInfo::output> & me)214     static C2R BitrateSetter(bool mayBlock, C2P<C2StreamBitrateInfo::output> &me) {
215         (void)mayBlock;
216         C2R res = C2R::Ok();
217         if (me.v.value <= 4096) {
218             me.set().value = 4096;
219         }
220         return res;
221     }
222 
SizeSetter(bool mayBlock,const C2P<C2StreamPictureSizeInfo::input> & oldMe,C2P<C2StreamPictureSizeInfo::input> & me)223     static C2R SizeSetter(bool mayBlock, const C2P<C2StreamPictureSizeInfo::input> &oldMe,
224                           C2P<C2StreamPictureSizeInfo::input> &me) {
225         (void)mayBlock;
226         C2R res = C2R::Ok();
227         if (!me.F(me.v.width).supportsAtAll(me.v.width)) {
228             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.width)));
229             me.set().width = oldMe.v.width;
230         }
231         if (!me.F(me.v.height).supportsAtAll(me.v.height)) {
232             res = res.plus(C2SettingResultBuilder::BadValue(me.F(me.v.height)));
233             me.set().height = oldMe.v.height;
234         }
235         return res;
236     }
237 
ProfileLevelSetter(bool mayBlock,C2P<C2StreamProfileLevelInfo::output> & me,const C2P<C2StreamPictureSizeInfo::input> & size,const C2P<C2StreamFrameRateInfo::output> & frameRate,const C2P<C2StreamBitrateInfo::output> & bitrate)238     static C2R ProfileLevelSetter(
239             bool mayBlock,
240             C2P<C2StreamProfileLevelInfo::output> &me,
241             const C2P<C2StreamPictureSizeInfo::input> &size,
242             const C2P<C2StreamFrameRateInfo::output> &frameRate,
243             const C2P<C2StreamBitrateInfo::output> &bitrate) {
244         (void)mayBlock;
245         if (!me.F(me.v.profile).supportsAtAll(me.v.profile)) {
246             me.set().profile = PROFILE_AVC_CONSTRAINED_BASELINE;
247         }
248 
249         struct LevelLimits {
250             C2Config::level_t level;
251             float mbsPerSec;
252             uint64_t mbs;
253             uint32_t bitrate;
254         };
255         constexpr LevelLimits kLimits[] = {
256             { LEVEL_AVC_1,     1485,    99,     64000 },
257             // Decoder does not properly handle level 1b.
258             // { LEVEL_AVC_1B,    1485,   99,   128000 },
259             { LEVEL_AVC_1_1,   3000,   396,    192000 },
260             { LEVEL_AVC_1_2,   6000,   396,    384000 },
261             { LEVEL_AVC_1_3,  11880,   396,    768000 },
262             { LEVEL_AVC_2,    11880,   396,   2000000 },
263             { LEVEL_AVC_2_1,  19800,   792,   4000000 },
264             { LEVEL_AVC_2_2,  20250,  1620,   4000000 },
265             { LEVEL_AVC_3,    40500,  1620,  10000000 },
266             { LEVEL_AVC_3_1, 108000,  3600,  14000000 },
267             { LEVEL_AVC_3_2, 216000,  5120,  20000000 },
268             { LEVEL_AVC_4,   245760,  8192,  20000000 },
269             { LEVEL_AVC_4_1, 245760,  8192,  50000000 },
270             { LEVEL_AVC_4_2, 522240,  8704,  50000000 },
271             { LEVEL_AVC_5,   589824, 22080, 135000000 },
272         };
273 
274         uint64_t mbs = uint64_t((size.v.width + 15) / 16) * ((size.v.height + 15) / 16);
275         float mbsPerSec = float(mbs) * frameRate.v.value;
276 
277         // Check if the supplied level meets the MB / bitrate requirements. If
278         // not, update the level with the lowest level meeting the requirements.
279 
280         bool found = false;
281         // By default needsUpdate = false in case the supplied level does meet
282         // the requirements. For Level 1b, we want to update the level anyway,
283         // so we set it to true in that case.
284         bool needsUpdate = (me.v.level == LEVEL_AVC_1B);
285         for (const LevelLimits &limit : kLimits) {
286             if (mbs <= limit.mbs && mbsPerSec <= limit.mbsPerSec &&
287                     bitrate.v.value <= limit.bitrate) {
288                 // This is the lowest level that meets the requirements, and if
289                 // we haven't seen the supplied level yet, that means we don't
290                 // need the update.
291                 if (needsUpdate) {
292                     ALOGD("Given level %x does not cover current configuration: "
293                           "adjusting to %x", me.v.level, limit.level);
294                     me.set().level = limit.level;
295                 }
296                 found = true;
297                 break;
298             }
299             if (me.v.level == limit.level) {
300                 // We break out of the loop when the lowest feasible level is
301                 // found. The fact that we're here means that our level doesn't
302                 // meet the requirement and needs to be updated.
303                 needsUpdate = true;
304             }
305         }
306         if (!found) {
307             // We set to the highest supported level.
308             me.set().level = LEVEL_AVC_5;
309         }
310 
311         return C2R::Ok();
312     }
313 
IntraRefreshSetter(bool mayBlock,C2P<C2StreamIntraRefreshTuning::output> & me)314     static C2R IntraRefreshSetter(bool mayBlock, C2P<C2StreamIntraRefreshTuning::output> &me) {
315         (void)mayBlock;
316         C2R res = C2R::Ok();
317         if (me.v.period < 1) {
318             me.set().mode = C2Config::INTRA_REFRESH_DISABLED;
319             me.set().period = 0;
320         } else {
321             // only support arbitrary mode (cyclic in our case)
322             me.set().mode = C2Config::INTRA_REFRESH_ARBITRARY;
323         }
324         return res;
325     }
326 
GopSetter(bool mayBlock,C2P<C2StreamGopTuning::output> & me)327     static C2R GopSetter(bool mayBlock, C2P<C2StreamGopTuning::output> &me) {
328         (void)mayBlock;
329         for (size_t i = 0; i < me.v.flexCount(); ++i) {
330             const C2GopLayerStruct &layer = me.v.m.values[0];
331             if (layer.type_ == C2Config::picture_type_t(P_FRAME | B_FRAME)
332                     && layer.count > MAX_B_FRAMES) {
333                 me.set().m.values[i].count = MAX_B_FRAMES;
334             }
335         }
336         return C2R::Ok();
337     }
338 
getProfile_l() const339     IV_PROFILE_T getProfile_l() const {
340         switch (mProfileLevel->profile) {
341         case PROFILE_AVC_CONSTRAINED_BASELINE:  [[fallthrough]];
342         case PROFILE_AVC_BASELINE: return IV_PROFILE_BASE;
343         case PROFILE_AVC_MAIN:     return IV_PROFILE_MAIN;
344         default:
345             ALOGD("Unrecognized profile: %x", mProfileLevel->profile);
346             return IV_PROFILE_DEFAULT;
347         }
348     }
349 
getLevel_l() const350     UWORD32 getLevel_l() const {
351         struct Level {
352             C2Config::level_t c2Level;
353             UWORD32 avcLevel;
354         };
355         constexpr Level levels[] = {
356             { LEVEL_AVC_1,   10 },
357             { LEVEL_AVC_1B,   9 },
358             { LEVEL_AVC_1_1, 11 },
359             { LEVEL_AVC_1_2, 12 },
360             { LEVEL_AVC_1_3, 13 },
361             { LEVEL_AVC_2,   20 },
362             { LEVEL_AVC_2_1, 21 },
363             { LEVEL_AVC_2_2, 22 },
364             { LEVEL_AVC_3,   30 },
365             { LEVEL_AVC_3_1, 31 },
366             { LEVEL_AVC_3_2, 32 },
367             { LEVEL_AVC_4,   40 },
368             { LEVEL_AVC_4_1, 41 },
369             { LEVEL_AVC_4_2, 42 },
370             { LEVEL_AVC_5,   50 },
371         };
372         for (const Level &level : levels) {
373             if (mProfileLevel->level == level.c2Level) {
374                 return level.avcLevel;
375             }
376         }
377         ALOGD("Unrecognized level: %x", mProfileLevel->level);
378         return 41;
379     }
380 
getSyncFramePeriod_l() const381     uint32_t getSyncFramePeriod_l() const {
382         if (mSyncFramePeriod->value < 0 || mSyncFramePeriod->value == INT64_MAX) {
383             return 0;
384         }
385         double period = mSyncFramePeriod->value / 1e6 * mFrameRate->value;
386         return (uint32_t)c2_max(c2_min(period + 0.5, double(UINT32_MAX)), 1.);
387     }
388 
389     // unsafe getters
getSize_l() const390     std::shared_ptr<C2StreamPictureSizeInfo::input> getSize_l() const { return mSize; }
getIntraRefresh_l() const391     std::shared_ptr<C2StreamIntraRefreshTuning::output> getIntraRefresh_l() const { return mIntraRefresh; }
getFrameRate_l() const392     std::shared_ptr<C2StreamFrameRateInfo::output> getFrameRate_l() const { return mFrameRate; }
getBitrate_l() const393     std::shared_ptr<C2StreamBitrateInfo::output> getBitrate_l() const { return mBitrate; }
getRequestSync_l() const394     std::shared_ptr<C2StreamRequestSyncFrameTuning::output> getRequestSync_l() const { return mRequestSync; }
getGop_l() const395     std::shared_ptr<C2StreamGopTuning::output> getGop_l() const { return mGop; }
396 
397 private:
398     std::shared_ptr<C2StreamUsageTuning::input> mUsage;
399     std::shared_ptr<C2StreamPictureSizeInfo::input> mSize;
400     std::shared_ptr<C2StreamFrameRateInfo::output> mFrameRate;
401     std::shared_ptr<C2StreamRequestSyncFrameTuning::output> mRequestSync;
402     std::shared_ptr<C2StreamIntraRefreshTuning::output> mIntraRefresh;
403     std::shared_ptr<C2StreamBitrateInfo::output> mBitrate;
404     std::shared_ptr<C2StreamProfileLevelInfo::output> mProfileLevel;
405     std::shared_ptr<C2StreamSyncFrameIntervalTuning::output> mSyncFramePeriod;
406     std::shared_ptr<C2StreamGopTuning::output> mGop;
407 };
408 
409 #define ive_api_function  ih264e_api_function
410 
411 namespace {
412 
413 // From external/libavc/encoder/ih264e_bitstream.h
414 constexpr uint32_t MIN_STREAM_SIZE = 0x800;
415 
GetCPUCoreCount()416 static size_t GetCPUCoreCount() {
417     long cpuCoreCount = 1;
418 #if defined(_SC_NPROCESSORS_ONLN)
419     cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
420 #else
421     // _SC_NPROC_ONLN must be defined...
422     cpuCoreCount = sysconf(_SC_NPROC_ONLN);
423 #endif
424     CHECK(cpuCoreCount >= 1);
425     ALOGV("Number of CPU cores: %ld", cpuCoreCount);
426     return (size_t)cpuCoreCount;
427 }
428 
429 }  // namespace
430 
C2SoftAvcEnc(const char * name,c2_node_id_t id,const std::shared_ptr<IntfImpl> & intfImpl)431 C2SoftAvcEnc::C2SoftAvcEnc(
432         const char *name, c2_node_id_t id, const std::shared_ptr<IntfImpl> &intfImpl)
433     : SimpleC2Component(std::make_shared<SimpleInterface<IntfImpl>>(name, id, intfImpl)),
434       mIntf(intfImpl),
435       mIvVideoColorFormat(IV_YUV_420P),
436       mAVCEncProfile(IV_PROFILE_BASE),
437       mAVCEncLevel(41),
438       mStarted(false),
439       mSawInputEOS(false),
440       mSignalledError(false),
441       mCodecCtx(nullptr),
442       mOutBlock(nullptr),
443       mOutBufferSize(kMinOutBufferSize) {
444 
445     // If dump is enabled, then open create an empty file
446     GENERATE_FILE_NAMES();
447     CREATE_DUMP_FILE(mInFile);
448     CREATE_DUMP_FILE(mOutFile);
449 
450     initEncParams();
451 }
452 
~C2SoftAvcEnc()453 C2SoftAvcEnc::~C2SoftAvcEnc() {
454     onRelease();
455 }
456 
onInit()457 c2_status_t C2SoftAvcEnc::onInit() {
458     return C2_OK;
459 }
460 
onStop()461 c2_status_t C2SoftAvcEnc::onStop() {
462     return C2_OK;
463 }
464 
onReset()465 void C2SoftAvcEnc::onReset() {
466     // TODO: use IVE_CMD_CTL_RESET?
467     releaseEncoder();
468     if (mOutBlock) {
469         mOutBlock.reset();
470     }
471     initEncParams();
472 }
473 
onRelease()474 void C2SoftAvcEnc::onRelease() {
475     releaseEncoder();
476     if (mOutBlock) {
477         mOutBlock.reset();
478     }
479 }
480 
onFlush_sm()481 c2_status_t C2SoftAvcEnc::onFlush_sm() {
482     // TODO: use IVE_CMD_CTL_FLUSH?
483     return C2_OK;
484 }
485 
initEncParams()486 void  C2SoftAvcEnc::initEncParams() {
487     mCodecCtx = nullptr;
488     mMemRecords = nullptr;
489     mNumMemRecords = DEFAULT_MEM_REC_CNT;
490     mHeaderGenerated = 0;
491     mNumCores = GetCPUCoreCount();
492     mArch = DEFAULT_ARCH;
493     mSliceMode = DEFAULT_SLICE_MODE;
494     mSliceParam = DEFAULT_SLICE_PARAM;
495     mHalfPelEnable = DEFAULT_HPEL;
496     mIInterval = DEFAULT_I_INTERVAL;
497     mIDRInterval = DEFAULT_IDR_INTERVAL;
498     mDisableDeblkLevel = DEFAULT_DISABLE_DEBLK_LEVEL;
499     mEnableFastSad = DEFAULT_ENABLE_FAST_SAD;
500     mEnableAltRef = DEFAULT_ENABLE_ALT_REF;
501     mEncSpeed = DEFAULT_ENC_SPEED;
502     mIntra4x4 = DEFAULT_INTRA4x4;
503     mConstrainedIntraFlag = DEFAULT_CONSTRAINED_INTRA;
504     mPSNREnable = DEFAULT_PSNR_ENABLE;
505     mReconEnable = DEFAULT_RECON_ENABLE;
506     mEntropyMode = DEFAULT_ENTROPY_MODE;
507     mBframes = DEFAULT_B_FRAMES;
508 
509     gettimeofday(&mTimeStart, nullptr);
510     gettimeofday(&mTimeEnd, nullptr);
511 }
512 
setDimensions()513 c2_status_t C2SoftAvcEnc::setDimensions() {
514     ive_ctl_set_dimensions_ip_t s_dimensions_ip;
515     ive_ctl_set_dimensions_op_t s_dimensions_op;
516     IV_STATUS_T status;
517 
518     s_dimensions_ip.e_cmd = IVE_CMD_VIDEO_CTL;
519     s_dimensions_ip.e_sub_cmd = IVE_CMD_CTL_SET_DIMENSIONS;
520     s_dimensions_ip.u4_ht = mSize->height;
521     s_dimensions_ip.u4_wd = mSize->width;
522 
523     s_dimensions_ip.u4_timestamp_high = -1;
524     s_dimensions_ip.u4_timestamp_low = -1;
525 
526     s_dimensions_ip.u4_size = sizeof(ive_ctl_set_dimensions_ip_t);
527     s_dimensions_op.u4_size = sizeof(ive_ctl_set_dimensions_op_t);
528 
529     status = ive_api_function(mCodecCtx, &s_dimensions_ip, &s_dimensions_op);
530     if (status != IV_SUCCESS) {
531         ALOGE("Unable to set frame dimensions = 0x%x\n",
532                 s_dimensions_op.u4_error_code);
533         return C2_CORRUPTED;
534     }
535     return C2_OK;
536 }
537 
setNumCores()538 c2_status_t C2SoftAvcEnc::setNumCores() {
539     IV_STATUS_T status;
540     ive_ctl_set_num_cores_ip_t s_num_cores_ip;
541     ive_ctl_set_num_cores_op_t s_num_cores_op;
542     s_num_cores_ip.e_cmd = IVE_CMD_VIDEO_CTL;
543     s_num_cores_ip.e_sub_cmd = IVE_CMD_CTL_SET_NUM_CORES;
544     s_num_cores_ip.u4_num_cores = MIN(mNumCores, CODEC_MAX_CORES);
545     s_num_cores_ip.u4_timestamp_high = -1;
546     s_num_cores_ip.u4_timestamp_low = -1;
547     s_num_cores_ip.u4_size = sizeof(ive_ctl_set_num_cores_ip_t);
548 
549     s_num_cores_op.u4_size = sizeof(ive_ctl_set_num_cores_op_t);
550 
551     status = ive_api_function(
552             mCodecCtx, (void *) &s_num_cores_ip, (void *) &s_num_cores_op);
553     if (status != IV_SUCCESS) {
554         ALOGE("Unable to set processor params = 0x%x\n",
555                 s_num_cores_op.u4_error_code);
556         return C2_CORRUPTED;
557     }
558     return C2_OK;
559 }
560 
setFrameRate()561 c2_status_t C2SoftAvcEnc::setFrameRate() {
562     ive_ctl_set_frame_rate_ip_t s_frame_rate_ip;
563     ive_ctl_set_frame_rate_op_t s_frame_rate_op;
564     IV_STATUS_T status;
565 
566     s_frame_rate_ip.e_cmd = IVE_CMD_VIDEO_CTL;
567     s_frame_rate_ip.e_sub_cmd = IVE_CMD_CTL_SET_FRAMERATE;
568 
569     s_frame_rate_ip.u4_src_frame_rate = mFrameRate->value + 0.5;
570     s_frame_rate_ip.u4_tgt_frame_rate = mFrameRate->value + 0.5;
571 
572     s_frame_rate_ip.u4_timestamp_high = -1;
573     s_frame_rate_ip.u4_timestamp_low = -1;
574 
575     s_frame_rate_ip.u4_size = sizeof(ive_ctl_set_frame_rate_ip_t);
576     s_frame_rate_op.u4_size = sizeof(ive_ctl_set_frame_rate_op_t);
577 
578     status = ive_api_function(mCodecCtx, &s_frame_rate_ip, &s_frame_rate_op);
579     if (status != IV_SUCCESS) {
580         ALOGE("Unable to set frame rate = 0x%x\n",
581                 s_frame_rate_op.u4_error_code);
582         return C2_CORRUPTED;
583     }
584     return C2_OK;
585 }
586 
setIpeParams()587 c2_status_t C2SoftAvcEnc::setIpeParams() {
588     ive_ctl_set_ipe_params_ip_t s_ipe_params_ip;
589     ive_ctl_set_ipe_params_op_t s_ipe_params_op;
590     IV_STATUS_T status;
591 
592     s_ipe_params_ip.e_cmd = IVE_CMD_VIDEO_CTL;
593     s_ipe_params_ip.e_sub_cmd = IVE_CMD_CTL_SET_IPE_PARAMS;
594 
595     s_ipe_params_ip.u4_enable_intra_4x4 = mIntra4x4;
596     s_ipe_params_ip.u4_enc_speed_preset = mEncSpeed;
597     s_ipe_params_ip.u4_constrained_intra_pred = mConstrainedIntraFlag;
598 
599     s_ipe_params_ip.u4_timestamp_high = -1;
600     s_ipe_params_ip.u4_timestamp_low = -1;
601 
602     s_ipe_params_ip.u4_size = sizeof(ive_ctl_set_ipe_params_ip_t);
603     s_ipe_params_op.u4_size = sizeof(ive_ctl_set_ipe_params_op_t);
604 
605     status = ive_api_function(mCodecCtx, &s_ipe_params_ip, &s_ipe_params_op);
606     if (status != IV_SUCCESS) {
607         ALOGE("Unable to set ipe params = 0x%x\n",
608                 s_ipe_params_op.u4_error_code);
609         return C2_CORRUPTED;
610     }
611     return C2_OK;
612 }
613 
setBitRate()614 c2_status_t C2SoftAvcEnc::setBitRate() {
615     ive_ctl_set_bitrate_ip_t s_bitrate_ip;
616     ive_ctl_set_bitrate_op_t s_bitrate_op;
617     IV_STATUS_T status;
618 
619     s_bitrate_ip.e_cmd = IVE_CMD_VIDEO_CTL;
620     s_bitrate_ip.e_sub_cmd = IVE_CMD_CTL_SET_BITRATE;
621 
622     s_bitrate_ip.u4_target_bitrate = mBitrate->value;
623 
624     s_bitrate_ip.u4_timestamp_high = -1;
625     s_bitrate_ip.u4_timestamp_low = -1;
626 
627     s_bitrate_ip.u4_size = sizeof(ive_ctl_set_bitrate_ip_t);
628     s_bitrate_op.u4_size = sizeof(ive_ctl_set_bitrate_op_t);
629 
630     status = ive_api_function(mCodecCtx, &s_bitrate_ip, &s_bitrate_op);
631     if (status != IV_SUCCESS) {
632         ALOGE("Unable to set bit rate = 0x%x\n", s_bitrate_op.u4_error_code);
633         return C2_CORRUPTED;
634     }
635     return C2_OK;
636 }
637 
setFrameType(IV_PICTURE_CODING_TYPE_T e_frame_type)638 c2_status_t C2SoftAvcEnc::setFrameType(IV_PICTURE_CODING_TYPE_T e_frame_type) {
639     ive_ctl_set_frame_type_ip_t s_frame_type_ip;
640     ive_ctl_set_frame_type_op_t s_frame_type_op;
641     IV_STATUS_T status;
642     s_frame_type_ip.e_cmd = IVE_CMD_VIDEO_CTL;
643     s_frame_type_ip.e_sub_cmd = IVE_CMD_CTL_SET_FRAMETYPE;
644 
645     s_frame_type_ip.e_frame_type = e_frame_type;
646 
647     s_frame_type_ip.u4_timestamp_high = -1;
648     s_frame_type_ip.u4_timestamp_low = -1;
649 
650     s_frame_type_ip.u4_size = sizeof(ive_ctl_set_frame_type_ip_t);
651     s_frame_type_op.u4_size = sizeof(ive_ctl_set_frame_type_op_t);
652 
653     status = ive_api_function(mCodecCtx, &s_frame_type_ip, &s_frame_type_op);
654     if (status != IV_SUCCESS) {
655         ALOGE("Unable to set frame type = 0x%x\n",
656                 s_frame_type_op.u4_error_code);
657         return C2_CORRUPTED;
658     }
659     return C2_OK;
660 }
661 
setQp()662 c2_status_t C2SoftAvcEnc::setQp() {
663     ive_ctl_set_qp_ip_t s_qp_ip;
664     ive_ctl_set_qp_op_t s_qp_op;
665     IV_STATUS_T status;
666 
667     s_qp_ip.e_cmd = IVE_CMD_VIDEO_CTL;
668     s_qp_ip.e_sub_cmd = IVE_CMD_CTL_SET_QP;
669 
670     s_qp_ip.u4_i_qp = DEFAULT_I_QP;
671     s_qp_ip.u4_i_qp_max = DEFAULT_QP_MAX;
672     s_qp_ip.u4_i_qp_min = DEFAULT_QP_MIN;
673 
674     s_qp_ip.u4_p_qp = DEFAULT_P_QP;
675     s_qp_ip.u4_p_qp_max = DEFAULT_QP_MAX;
676     s_qp_ip.u4_p_qp_min = DEFAULT_QP_MIN;
677 
678     s_qp_ip.u4_b_qp = DEFAULT_P_QP;
679     s_qp_ip.u4_b_qp_max = DEFAULT_QP_MAX;
680     s_qp_ip.u4_b_qp_min = DEFAULT_QP_MIN;
681 
682     s_qp_ip.u4_timestamp_high = -1;
683     s_qp_ip.u4_timestamp_low = -1;
684 
685     s_qp_ip.u4_size = sizeof(ive_ctl_set_qp_ip_t);
686     s_qp_op.u4_size = sizeof(ive_ctl_set_qp_op_t);
687 
688     status = ive_api_function(mCodecCtx, &s_qp_ip, &s_qp_op);
689     if (status != IV_SUCCESS) {
690         ALOGE("Unable to set qp 0x%x\n", s_qp_op.u4_error_code);
691         return C2_CORRUPTED;
692     }
693     return C2_OK;
694 }
695 
setEncMode(IVE_ENC_MODE_T e_enc_mode)696 c2_status_t C2SoftAvcEnc::setEncMode(IVE_ENC_MODE_T e_enc_mode) {
697     IV_STATUS_T status;
698     ive_ctl_set_enc_mode_ip_t s_enc_mode_ip;
699     ive_ctl_set_enc_mode_op_t s_enc_mode_op;
700 
701     s_enc_mode_ip.e_cmd = IVE_CMD_VIDEO_CTL;
702     s_enc_mode_ip.e_sub_cmd = IVE_CMD_CTL_SET_ENC_MODE;
703 
704     s_enc_mode_ip.e_enc_mode = e_enc_mode;
705 
706     s_enc_mode_ip.u4_timestamp_high = -1;
707     s_enc_mode_ip.u4_timestamp_low = -1;
708 
709     s_enc_mode_ip.u4_size = sizeof(ive_ctl_set_enc_mode_ip_t);
710     s_enc_mode_op.u4_size = sizeof(ive_ctl_set_enc_mode_op_t);
711 
712     status = ive_api_function(mCodecCtx, &s_enc_mode_ip, &s_enc_mode_op);
713     if (status != IV_SUCCESS) {
714         ALOGE("Unable to set in header encode mode = 0x%x\n",
715                 s_enc_mode_op.u4_error_code);
716         return C2_CORRUPTED;
717     }
718     return C2_OK;
719 }
720 
setVbvParams()721 c2_status_t C2SoftAvcEnc::setVbvParams() {
722     ive_ctl_set_vbv_params_ip_t s_vbv_ip;
723     ive_ctl_set_vbv_params_op_t s_vbv_op;
724     IV_STATUS_T status;
725 
726     s_vbv_ip.e_cmd = IVE_CMD_VIDEO_CTL;
727     s_vbv_ip.e_sub_cmd = IVE_CMD_CTL_SET_VBV_PARAMS;
728 
729     s_vbv_ip.u4_vbv_buf_size = 0;
730     s_vbv_ip.u4_vbv_buffer_delay = 1000;
731 
732     s_vbv_ip.u4_timestamp_high = -1;
733     s_vbv_ip.u4_timestamp_low = -1;
734 
735     s_vbv_ip.u4_size = sizeof(ive_ctl_set_vbv_params_ip_t);
736     s_vbv_op.u4_size = sizeof(ive_ctl_set_vbv_params_op_t);
737 
738     status = ive_api_function(mCodecCtx, &s_vbv_ip, &s_vbv_op);
739     if (status != IV_SUCCESS) {
740         ALOGE("Unable to set VBV params = 0x%x\n", s_vbv_op.u4_error_code);
741         return C2_CORRUPTED;
742     }
743     return C2_OK;
744 }
745 
setAirParams()746 c2_status_t C2SoftAvcEnc::setAirParams() {
747     ive_ctl_set_air_params_ip_t s_air_ip;
748     ive_ctl_set_air_params_op_t s_air_op;
749     IV_STATUS_T status;
750 
751     s_air_ip.e_cmd = IVE_CMD_VIDEO_CTL;
752     s_air_ip.e_sub_cmd = IVE_CMD_CTL_SET_AIR_PARAMS;
753 
754     s_air_ip.e_air_mode =
755         (mIntraRefresh->mode == C2Config::INTRA_REFRESH_DISABLED || mIntraRefresh->period < 1)
756             ? IVE_AIR_MODE_NONE : IVE_AIR_MODE_CYCLIC;
757     s_air_ip.u4_air_refresh_period = mIntraRefresh->period;
758 
759     s_air_ip.u4_timestamp_high = -1;
760     s_air_ip.u4_timestamp_low = -1;
761 
762     s_air_ip.u4_size = sizeof(ive_ctl_set_air_params_ip_t);
763     s_air_op.u4_size = sizeof(ive_ctl_set_air_params_op_t);
764 
765     status = ive_api_function(mCodecCtx, &s_air_ip, &s_air_op);
766     if (status != IV_SUCCESS) {
767         ALOGE("Unable to set air params = 0x%x\n", s_air_op.u4_error_code);
768         return C2_CORRUPTED;
769     }
770     return C2_OK;
771 }
772 
setMeParams()773 c2_status_t C2SoftAvcEnc::setMeParams() {
774     IV_STATUS_T status;
775     ive_ctl_set_me_params_ip_t s_me_params_ip;
776     ive_ctl_set_me_params_op_t s_me_params_op;
777 
778     s_me_params_ip.e_cmd = IVE_CMD_VIDEO_CTL;
779     s_me_params_ip.e_sub_cmd = IVE_CMD_CTL_SET_ME_PARAMS;
780 
781     s_me_params_ip.u4_enable_fast_sad = mEnableFastSad;
782     s_me_params_ip.u4_enable_alt_ref = mEnableAltRef;
783 
784     s_me_params_ip.u4_enable_hpel = mHalfPelEnable;
785     s_me_params_ip.u4_enable_qpel = DEFAULT_QPEL;
786     s_me_params_ip.u4_me_speed_preset = DEFAULT_ME_SPEED;
787     s_me_params_ip.u4_srch_rng_x = DEFAULT_SRCH_RNG_X;
788     s_me_params_ip.u4_srch_rng_y = DEFAULT_SRCH_RNG_Y;
789 
790     s_me_params_ip.u4_timestamp_high = -1;
791     s_me_params_ip.u4_timestamp_low = -1;
792 
793     s_me_params_ip.u4_size = sizeof(ive_ctl_set_me_params_ip_t);
794     s_me_params_op.u4_size = sizeof(ive_ctl_set_me_params_op_t);
795 
796     status = ive_api_function(mCodecCtx, &s_me_params_ip, &s_me_params_op);
797     if (status != IV_SUCCESS) {
798         ALOGE("Unable to set me params = 0x%x\n", s_me_params_op.u4_error_code);
799         return C2_CORRUPTED;
800     }
801     return C2_OK;
802 }
803 
setGopParams()804 c2_status_t C2SoftAvcEnc::setGopParams() {
805     IV_STATUS_T status;
806     ive_ctl_set_gop_params_ip_t s_gop_params_ip;
807     ive_ctl_set_gop_params_op_t s_gop_params_op;
808 
809     s_gop_params_ip.e_cmd = IVE_CMD_VIDEO_CTL;
810     s_gop_params_ip.e_sub_cmd = IVE_CMD_CTL_SET_GOP_PARAMS;
811 
812     s_gop_params_ip.u4_i_frm_interval = mIInterval;
813     s_gop_params_ip.u4_idr_frm_interval = mIDRInterval;
814 
815     s_gop_params_ip.u4_timestamp_high = -1;
816     s_gop_params_ip.u4_timestamp_low = -1;
817 
818     s_gop_params_ip.u4_size = sizeof(ive_ctl_set_gop_params_ip_t);
819     s_gop_params_op.u4_size = sizeof(ive_ctl_set_gop_params_op_t);
820 
821     status = ive_api_function(mCodecCtx, &s_gop_params_ip, &s_gop_params_op);
822     if (status != IV_SUCCESS) {
823         ALOGE("Unable to set GOP params = 0x%x\n",
824                 s_gop_params_op.u4_error_code);
825         return C2_CORRUPTED;
826     }
827     return C2_OK;
828 }
829 
setProfileParams()830 c2_status_t C2SoftAvcEnc::setProfileParams() {
831     IntfImpl::Lock lock = mIntf->lock();
832 
833     IV_STATUS_T status;
834     ive_ctl_set_profile_params_ip_t s_profile_params_ip;
835     ive_ctl_set_profile_params_op_t s_profile_params_op;
836 
837     s_profile_params_ip.e_cmd = IVE_CMD_VIDEO_CTL;
838     s_profile_params_ip.e_sub_cmd = IVE_CMD_CTL_SET_PROFILE_PARAMS;
839 
840     s_profile_params_ip.e_profile = mIntf->getProfile_l();
841     if (s_profile_params_ip.e_profile == IV_PROFILE_BASE) {
842         s_profile_params_ip.u4_entropy_coding_mode = 0;
843     } else {
844         s_profile_params_ip.u4_entropy_coding_mode = 1;
845     }
846     s_profile_params_ip.u4_timestamp_high = -1;
847     s_profile_params_ip.u4_timestamp_low = -1;
848 
849     s_profile_params_ip.u4_size = sizeof(ive_ctl_set_profile_params_ip_t);
850     s_profile_params_op.u4_size = sizeof(ive_ctl_set_profile_params_op_t);
851     lock.unlock();
852 
853     status = ive_api_function(mCodecCtx, &s_profile_params_ip, &s_profile_params_op);
854     if (status != IV_SUCCESS) {
855         ALOGE("Unable to set profile params = 0x%x\n",
856                 s_profile_params_op.u4_error_code);
857         return C2_CORRUPTED;
858     }
859     return C2_OK;
860 }
861 
setDeblockParams()862 c2_status_t C2SoftAvcEnc::setDeblockParams() {
863     IV_STATUS_T status;
864     ive_ctl_set_deblock_params_ip_t s_deblock_params_ip;
865     ive_ctl_set_deblock_params_op_t s_deblock_params_op;
866 
867     s_deblock_params_ip.e_cmd = IVE_CMD_VIDEO_CTL;
868     s_deblock_params_ip.e_sub_cmd = IVE_CMD_CTL_SET_DEBLOCK_PARAMS;
869 
870     s_deblock_params_ip.u4_disable_deblock_level = mDisableDeblkLevel;
871 
872     s_deblock_params_ip.u4_timestamp_high = -1;
873     s_deblock_params_ip.u4_timestamp_low = -1;
874 
875     s_deblock_params_ip.u4_size = sizeof(ive_ctl_set_deblock_params_ip_t);
876     s_deblock_params_op.u4_size = sizeof(ive_ctl_set_deblock_params_op_t);
877 
878     status = ive_api_function(mCodecCtx, &s_deblock_params_ip, &s_deblock_params_op);
879     if (status != IV_SUCCESS) {
880         ALOGE("Unable to enable/disable deblock params = 0x%x\n",
881                 s_deblock_params_op.u4_error_code);
882         return C2_CORRUPTED;
883     }
884     return C2_OK;
885 }
886 
logVersion()887 void C2SoftAvcEnc::logVersion() {
888     ive_ctl_getversioninfo_ip_t s_ctl_ip;
889     ive_ctl_getversioninfo_op_t s_ctl_op;
890     UWORD8 au1_buf[512];
891     IV_STATUS_T status;
892 
893     s_ctl_ip.e_cmd = IVE_CMD_VIDEO_CTL;
894     s_ctl_ip.e_sub_cmd = IVE_CMD_CTL_GETVERSION;
895     s_ctl_ip.u4_size = sizeof(ive_ctl_getversioninfo_ip_t);
896     s_ctl_op.u4_size = sizeof(ive_ctl_getversioninfo_op_t);
897     s_ctl_ip.pu1_version = au1_buf;
898     s_ctl_ip.u4_version_bufsize = sizeof(au1_buf);
899 
900     status = ive_api_function(mCodecCtx, (void *) &s_ctl_ip, (void *) &s_ctl_op);
901 
902     if (status != IV_SUCCESS) {
903         ALOGE("Error in getting version: 0x%x", s_ctl_op.u4_error_code);
904     } else {
905         ALOGV("Ittiam encoder version: %s", (char *)s_ctl_ip.pu1_version);
906     }
907     return;
908 }
909 
initEncoder()910 c2_status_t C2SoftAvcEnc::initEncoder() {
911     IV_STATUS_T status;
912     WORD32 level;
913 
914     CHECK(!mStarted);
915 
916     c2_status_t errType = C2_OK;
917 
918     std::shared_ptr<C2StreamGopTuning::output> gop;
919     {
920         IntfImpl::Lock lock = mIntf->lock();
921         mSize = mIntf->getSize_l();
922         mBitrate = mIntf->getBitrate_l();
923         mFrameRate = mIntf->getFrameRate_l();
924         mIntraRefresh = mIntf->getIntraRefresh_l();
925         mAVCEncLevel = mIntf->getLevel_l();
926         mIInterval = mIntf->getSyncFramePeriod_l();
927         mIDRInterval = mIntf->getSyncFramePeriod_l();
928         gop = mIntf->getGop_l();
929     }
930     if (gop && gop->flexCount() > 0) {
931         uint32_t syncInterval = 1;
932         uint32_t iInterval = 1;
933         uint32_t maxBframes = 0;
934         ParseGop(*gop, &syncInterval, &iInterval, &maxBframes);
935         if (syncInterval > 0) {
936             ALOGD("Updating IDR interval from GOP: old %u new %u", mIDRInterval, syncInterval);
937             mIDRInterval = syncInterval;
938         }
939         if (iInterval > 0) {
940             ALOGD("Updating I interval from GOP: old %u new %u", mIInterval, iInterval);
941             mIInterval = iInterval;
942         }
943         if (mBframes != maxBframes) {
944             ALOGD("Updating max B frames from GOP: old %u new %u", mBframes, maxBframes);
945             mBframes = maxBframes;
946         }
947     }
948     uint32_t width = mSize->width;
949     uint32_t height = mSize->height;
950 
951     mStride = width;
952 
953     // Assume worst case output buffer size to be equal to number of bytes in input
954     mOutBufferSize = std::max(width * height * 3 / 2, kMinOutBufferSize);
955 
956     // TODO
957     mIvVideoColorFormat = IV_YUV_420P;
958 
959     ALOGD("Params width %d height %d level %d colorFormat %d bframes %d", width,
960             height, mAVCEncLevel, mIvVideoColorFormat, mBframes);
961 
962     /* Getting Number of MemRecords */
963     {
964         iv_num_mem_rec_ip_t s_num_mem_rec_ip;
965         iv_num_mem_rec_op_t s_num_mem_rec_op;
966 
967         s_num_mem_rec_ip.u4_size = sizeof(iv_num_mem_rec_ip_t);
968         s_num_mem_rec_op.u4_size = sizeof(iv_num_mem_rec_op_t);
969 
970         s_num_mem_rec_ip.e_cmd = IV_CMD_GET_NUM_MEM_REC;
971 
972         status = ive_api_function(nullptr, &s_num_mem_rec_ip, &s_num_mem_rec_op);
973 
974         if (status != IV_SUCCESS) {
975             ALOGE("Get number of memory records failed = 0x%x\n",
976                     s_num_mem_rec_op.u4_error_code);
977             return C2_CORRUPTED;
978         }
979 
980         mNumMemRecords = s_num_mem_rec_op.u4_num_mem_rec;
981     }
982 
983     /* Allocate array to hold memory records */
984     if (mNumMemRecords > SIZE_MAX / sizeof(iv_mem_rec_t)) {
985         ALOGE("requested memory size is too big.");
986         return C2_CORRUPTED;
987     }
988     mMemRecords = (iv_mem_rec_t *)malloc(mNumMemRecords * sizeof(iv_mem_rec_t));
989     if (nullptr == mMemRecords) {
990         ALOGE("Unable to allocate memory for hold memory records: Size %zu",
991                 mNumMemRecords * sizeof(iv_mem_rec_t));
992         mSignalledError = true;
993         return C2_CORRUPTED;
994     }
995 
996     {
997         iv_mem_rec_t *ps_mem_rec;
998         ps_mem_rec = mMemRecords;
999         for (size_t i = 0; i < mNumMemRecords; i++) {
1000             ps_mem_rec->u4_size = sizeof(iv_mem_rec_t);
1001             ps_mem_rec->pv_base = nullptr;
1002             ps_mem_rec->u4_mem_size = 0;
1003             ps_mem_rec->u4_mem_alignment = 0;
1004             ps_mem_rec->e_mem_type = IV_NA_MEM_TYPE;
1005 
1006             ps_mem_rec++;
1007         }
1008     }
1009 
1010     /* Getting MemRecords Attributes */
1011     {
1012         iv_fill_mem_rec_ip_t s_fill_mem_rec_ip;
1013         iv_fill_mem_rec_op_t s_fill_mem_rec_op;
1014 
1015         s_fill_mem_rec_ip.u4_size = sizeof(iv_fill_mem_rec_ip_t);
1016         s_fill_mem_rec_op.u4_size = sizeof(iv_fill_mem_rec_op_t);
1017 
1018         s_fill_mem_rec_ip.e_cmd = IV_CMD_FILL_NUM_MEM_REC;
1019         s_fill_mem_rec_ip.ps_mem_rec = mMemRecords;
1020         s_fill_mem_rec_ip.u4_num_mem_rec = mNumMemRecords;
1021         s_fill_mem_rec_ip.u4_max_wd = width;
1022         s_fill_mem_rec_ip.u4_max_ht = height;
1023         s_fill_mem_rec_ip.u4_max_level = mAVCEncLevel;
1024         s_fill_mem_rec_ip.e_color_format = DEFAULT_INP_COLOR_FORMAT;
1025         s_fill_mem_rec_ip.u4_max_ref_cnt = DEFAULT_MAX_REF_FRM;
1026         s_fill_mem_rec_ip.u4_max_reorder_cnt = DEFAULT_MAX_REORDER_FRM;
1027         s_fill_mem_rec_ip.u4_max_srch_rng_x = DEFAULT_MAX_SRCH_RANGE_X;
1028         s_fill_mem_rec_ip.u4_max_srch_rng_y = DEFAULT_MAX_SRCH_RANGE_Y;
1029 
1030         status = ive_api_function(nullptr, &s_fill_mem_rec_ip, &s_fill_mem_rec_op);
1031 
1032         if (status != IV_SUCCESS) {
1033             ALOGE("Fill memory records failed = 0x%x\n",
1034                     s_fill_mem_rec_op.u4_error_code);
1035             return C2_CORRUPTED;
1036         }
1037     }
1038 
1039     /* Allocating Memory for Mem Records */
1040     {
1041         WORD32 total_size;
1042         iv_mem_rec_t *ps_mem_rec;
1043         total_size = 0;
1044         ps_mem_rec = mMemRecords;
1045 
1046         for (size_t i = 0; i < mNumMemRecords; i++) {
1047             ps_mem_rec->pv_base = ive_aligned_malloc(
1048                     ps_mem_rec->u4_mem_alignment, ps_mem_rec->u4_mem_size);
1049             if (ps_mem_rec->pv_base == nullptr) {
1050                 ALOGE("Allocation failure for mem record id %zu size %u\n", i,
1051                         ps_mem_rec->u4_mem_size);
1052                 return C2_CORRUPTED;
1053 
1054             }
1055             total_size += ps_mem_rec->u4_mem_size;
1056 
1057             ps_mem_rec++;
1058         }
1059     }
1060 
1061     /* Codec Instance Creation */
1062     {
1063         ive_init_ip_t s_init_ip;
1064         ive_init_op_t s_init_op;
1065 
1066         mCodecCtx = (iv_obj_t *)mMemRecords[0].pv_base;
1067         mCodecCtx->u4_size = sizeof(iv_obj_t);
1068         mCodecCtx->pv_fxns = (void *)ive_api_function;
1069 
1070         s_init_ip.u4_size = sizeof(ive_init_ip_t);
1071         s_init_op.u4_size = sizeof(ive_init_op_t);
1072 
1073         s_init_ip.e_cmd = IV_CMD_INIT;
1074         s_init_ip.u4_num_mem_rec = mNumMemRecords;
1075         s_init_ip.ps_mem_rec = mMemRecords;
1076         s_init_ip.u4_max_wd = width;
1077         s_init_ip.u4_max_ht = height;
1078         s_init_ip.u4_max_ref_cnt = DEFAULT_MAX_REF_FRM;
1079         s_init_ip.u4_max_reorder_cnt = DEFAULT_MAX_REORDER_FRM;
1080         s_init_ip.u4_max_level = mAVCEncLevel;
1081         s_init_ip.e_inp_color_fmt = mIvVideoColorFormat;
1082 
1083         if (mReconEnable || mPSNREnable) {
1084             s_init_ip.u4_enable_recon = 1;
1085         } else {
1086             s_init_ip.u4_enable_recon = 0;
1087         }
1088         s_init_ip.e_recon_color_fmt = DEFAULT_RECON_COLOR_FORMAT;
1089         s_init_ip.e_rc_mode = DEFAULT_RC_MODE;
1090         s_init_ip.u4_max_framerate = DEFAULT_MAX_FRAMERATE;
1091         s_init_ip.u4_max_bitrate = DEFAULT_MAX_BITRATE;
1092         s_init_ip.u4_num_bframes = mBframes;
1093         s_init_ip.e_content_type = IV_PROGRESSIVE;
1094         s_init_ip.u4_max_srch_rng_x = DEFAULT_MAX_SRCH_RANGE_X;
1095         s_init_ip.u4_max_srch_rng_y = DEFAULT_MAX_SRCH_RANGE_Y;
1096         s_init_ip.e_slice_mode = mSliceMode;
1097         s_init_ip.u4_slice_param = mSliceParam;
1098         s_init_ip.e_arch = mArch;
1099         s_init_ip.e_soc = DEFAULT_SOC;
1100 
1101         status = ive_api_function(mCodecCtx, &s_init_ip, &s_init_op);
1102 
1103         if (status != IV_SUCCESS) {
1104             ALOGE("Init encoder failed = 0x%x\n", s_init_op.u4_error_code);
1105             return C2_CORRUPTED;
1106         }
1107     }
1108 
1109     /* Get Codec Version */
1110     logVersion();
1111 
1112     /* set processor details */
1113     setNumCores();
1114 
1115     /* Video control Set Frame dimensions */
1116     setDimensions();
1117 
1118     /* Video control Set Frame rates */
1119     setFrameRate();
1120 
1121     /* Video control Set IPE Params */
1122     setIpeParams();
1123 
1124     /* Video control Set Bitrate */
1125     setBitRate();
1126 
1127     /* Video control Set QP */
1128     setQp();
1129 
1130     /* Video control Set AIR params */
1131     setAirParams();
1132 
1133     /* Video control Set VBV params */
1134     setVbvParams();
1135 
1136     /* Video control Set Motion estimation params */
1137     setMeParams();
1138 
1139     /* Video control Set GOP params */
1140     setGopParams();
1141 
1142     /* Video control Set Deblock params */
1143     setDeblockParams();
1144 
1145     /* Video control Set Profile params */
1146     setProfileParams();
1147 
1148     /* Video control Set in Encode header mode */
1149     setEncMode(IVE_ENC_MODE_HEADER);
1150 
1151     ALOGV("init_codec successfull");
1152 
1153     mSpsPpsHeaderReceived = false;
1154     mStarted = true;
1155 
1156     return C2_OK;
1157 }
1158 
releaseEncoder()1159 c2_status_t C2SoftAvcEnc::releaseEncoder() {
1160     IV_STATUS_T status = IV_SUCCESS;
1161     iv_retrieve_mem_rec_ip_t s_retrieve_mem_ip;
1162     iv_retrieve_mem_rec_op_t s_retrieve_mem_op;
1163     iv_mem_rec_t *ps_mem_rec;
1164 
1165     if (!mStarted) {
1166         return C2_OK;
1167     }
1168 
1169     s_retrieve_mem_ip.u4_size = sizeof(iv_retrieve_mem_rec_ip_t);
1170     s_retrieve_mem_op.u4_size = sizeof(iv_retrieve_mem_rec_op_t);
1171     s_retrieve_mem_ip.e_cmd = IV_CMD_RETRIEVE_MEMREC;
1172     s_retrieve_mem_ip.ps_mem_rec = mMemRecords;
1173 
1174     status = ive_api_function(mCodecCtx, &s_retrieve_mem_ip, &s_retrieve_mem_op);
1175 
1176     if (status != IV_SUCCESS) {
1177         ALOGE("Unable to retrieve memory records = 0x%x\n",
1178                 s_retrieve_mem_op.u4_error_code);
1179         return C2_CORRUPTED;
1180     }
1181 
1182     /* Free memory records */
1183     ps_mem_rec = mMemRecords;
1184     for (size_t i = 0; i < s_retrieve_mem_op.u4_num_mem_rec_filled; i++) {
1185         if (ps_mem_rec) ive_aligned_free(ps_mem_rec->pv_base);
1186         else {
1187             ALOGE("memory record is null.");
1188             return C2_CORRUPTED;
1189         }
1190         ps_mem_rec++;
1191     }
1192 
1193     if (mMemRecords) free(mMemRecords);
1194 
1195     // clear other pointers into the space being free()d
1196     mCodecCtx = nullptr;
1197 
1198     mStarted = false;
1199 
1200     return C2_OK;
1201 }
1202 
setEncodeArgs(ive_video_encode_ip_t * ps_encode_ip,ive_video_encode_op_t * ps_encode_op,const C2GraphicView * const input,uint8_t * base,uint32_t capacity,uint64_t workIndex)1203 c2_status_t C2SoftAvcEnc::setEncodeArgs(
1204         ive_video_encode_ip_t *ps_encode_ip,
1205         ive_video_encode_op_t *ps_encode_op,
1206         const C2GraphicView *const input,
1207         uint8_t *base,
1208         uint32_t capacity,
1209         uint64_t workIndex) {
1210     iv_raw_buf_t *ps_inp_raw_buf;
1211     memset(ps_encode_ip, 0, sizeof(*ps_encode_ip));
1212     memset(ps_encode_op, 0, sizeof(*ps_encode_op));
1213 
1214     ps_inp_raw_buf = &ps_encode_ip->s_inp_buf;
1215     ps_encode_ip->s_out_buf.pv_buf = base;
1216     ps_encode_ip->s_out_buf.u4_bytes = 0;
1217     ps_encode_ip->s_out_buf.u4_bufsize = capacity;
1218     ps_encode_ip->u4_size = sizeof(ive_video_encode_ip_t);
1219     ps_encode_op->u4_size = sizeof(ive_video_encode_op_t);
1220 
1221     ps_encode_ip->e_cmd = IVE_CMD_VIDEO_ENCODE;
1222     ps_encode_ip->pv_bufs = nullptr;
1223     ps_encode_ip->pv_mb_info = nullptr;
1224     ps_encode_ip->pv_pic_info = nullptr;
1225     ps_encode_ip->u4_mb_info_type = 0;
1226     ps_encode_ip->u4_pic_info_type = 0;
1227     ps_encode_ip->u4_is_last = 0;
1228     ps_encode_ip->u4_timestamp_high = workIndex >> 32;
1229     ps_encode_ip->u4_timestamp_low = workIndex & 0xFFFFFFFF;
1230     ps_encode_op->s_out_buf.pv_buf = nullptr;
1231 
1232     /* Initialize color formats */
1233     memset(ps_inp_raw_buf, 0, sizeof(iv_raw_buf_t));
1234     ps_inp_raw_buf->u4_size = sizeof(iv_raw_buf_t);
1235     ps_inp_raw_buf->e_color_fmt = mIvVideoColorFormat;
1236     if (input == nullptr) {
1237         if (mSawInputEOS) {
1238             ps_encode_ip->u4_is_last = 1;
1239         }
1240         return C2_OK;
1241     }
1242 
1243     if (input->width() < mSize->width ||
1244         input->height() < mSize->height) {
1245         /* Expect width height to be configured */
1246         ALOGW("unexpected Capacity Aspect %d(%d) x %d(%d)", input->width(),
1247               mSize->width, input->height(), mSize->height);
1248         return C2_BAD_VALUE;
1249     }
1250     ALOGV("width = %d, height = %d", input->width(), input->height());
1251     const C2PlanarLayout &layout = input->layout();
1252     uint8_t *yPlane = const_cast<uint8_t *>(input->data()[C2PlanarLayout::PLANE_Y]);
1253     uint8_t *uPlane = const_cast<uint8_t *>(input->data()[C2PlanarLayout::PLANE_U]);
1254     uint8_t *vPlane = const_cast<uint8_t *>(input->data()[C2PlanarLayout::PLANE_V]);
1255     int32_t yStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
1256     int32_t uStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
1257     int32_t vStride = layout.planes[C2PlanarLayout::PLANE_V].rowInc;
1258 
1259     uint32_t width = mSize->width;
1260     uint32_t height = mSize->height;
1261     // width and height are always even (as block size is 16x16)
1262     CHECK_EQ((width & 1u), 0u);
1263     CHECK_EQ((height & 1u), 0u);
1264     size_t yPlaneSize = width * height;
1265 
1266     switch (layout.type) {
1267         case C2PlanarLayout::TYPE_RGB:
1268             [[fallthrough]];
1269         case C2PlanarLayout::TYPE_RGBA: {
1270             ALOGV("yPlaneSize = %zu", yPlaneSize);
1271             MemoryBlock conversionBuffer = mConversionBuffers.fetch(yPlaneSize * 3 / 2);
1272             mConversionBuffersInUse.emplace(conversionBuffer.data(), conversionBuffer);
1273             yPlane = conversionBuffer.data();
1274             uPlane = yPlane + yPlaneSize;
1275             vPlane = uPlane + yPlaneSize / 4;
1276             yStride = width;
1277             uStride = vStride = yStride / 2;
1278             ConvertRGBToPlanarYUV(yPlane, yStride, height, conversionBuffer.size(), *input);
1279             break;
1280         }
1281         case C2PlanarLayout::TYPE_YUV: {
1282             if (!IsYUV420(*input)) {
1283                 ALOGE("input is not YUV420");
1284                 return C2_BAD_VALUE;
1285             }
1286 
1287             if (layout.planes[layout.PLANE_Y].colInc == 1
1288                     && layout.planes[layout.PLANE_U].colInc == 1
1289                     && layout.planes[layout.PLANE_V].colInc == 1
1290                     && uStride == vStride
1291                     && yStride == 2 * vStride) {
1292                 // I420 compatible - already set up above
1293                 break;
1294             }
1295 
1296             // copy to I420
1297             yStride = width;
1298             uStride = vStride = yStride / 2;
1299             MemoryBlock conversionBuffer = mConversionBuffers.fetch(yPlaneSize * 3 / 2);
1300             mConversionBuffersInUse.emplace(conversionBuffer.data(), conversionBuffer);
1301             MediaImage2 img = CreateYUV420PlanarMediaImage2(width, height, yStride, height);
1302             status_t err = ImageCopy(conversionBuffer.data(), &img, *input);
1303             if (err != OK) {
1304                 ALOGE("Buffer conversion failed: %d", err);
1305                 return C2_BAD_VALUE;
1306             }
1307             yPlane = conversionBuffer.data();
1308             uPlane = yPlane + yPlaneSize;
1309             vPlane = uPlane + yPlaneSize / 4;
1310             break;
1311 
1312         }
1313 
1314         case C2PlanarLayout::TYPE_YUVA:
1315             ALOGE("YUVA plane type is not supported");
1316             return C2_BAD_VALUE;
1317 
1318         default:
1319             ALOGE("Unrecognized plane type: %d", layout.type);
1320             return C2_BAD_VALUE;
1321     }
1322 
1323     switch (mIvVideoColorFormat) {
1324         case IV_YUV_420P:
1325         {
1326             // input buffer is supposed to be const but Ittiam API wants bare pointer.
1327             ps_inp_raw_buf->apv_bufs[0] = yPlane;
1328             ps_inp_raw_buf->apv_bufs[1] = uPlane;
1329             ps_inp_raw_buf->apv_bufs[2] = vPlane;
1330 
1331             ps_inp_raw_buf->au4_wd[0] = input->width();
1332             ps_inp_raw_buf->au4_wd[1] = input->width() / 2;
1333             ps_inp_raw_buf->au4_wd[2] = input->width() / 2;
1334 
1335             ps_inp_raw_buf->au4_ht[0] = input->height();
1336             ps_inp_raw_buf->au4_ht[1] = input->height() / 2;
1337             ps_inp_raw_buf->au4_ht[2] = input->height() / 2;
1338 
1339             ps_inp_raw_buf->au4_strd[0] = yStride;
1340             ps_inp_raw_buf->au4_strd[1] = uStride;
1341             ps_inp_raw_buf->au4_strd[2] = vStride;
1342             break;
1343         }
1344 
1345         case IV_YUV_422ILE:
1346         {
1347             // TODO
1348             // ps_inp_raw_buf->apv_bufs[0] = pu1_buf;
1349             // ps_inp_raw_buf->au4_wd[0] = mWidth * 2;
1350             // ps_inp_raw_buf->au4_ht[0] = mHeight;
1351             // ps_inp_raw_buf->au4_strd[0] = mStride * 2;
1352             break;
1353         }
1354 
1355         case IV_YUV_420SP_UV:
1356         case IV_YUV_420SP_VU:
1357         default:
1358         {
1359             ps_inp_raw_buf->apv_bufs[0] = yPlane;
1360             ps_inp_raw_buf->apv_bufs[1] = uPlane;
1361 
1362             ps_inp_raw_buf->au4_wd[0] = input->width();
1363             ps_inp_raw_buf->au4_wd[1] = input->width();
1364 
1365             ps_inp_raw_buf->au4_ht[0] = input->height();
1366             ps_inp_raw_buf->au4_ht[1] = input->height() / 2;
1367 
1368             ps_inp_raw_buf->au4_strd[0] = yStride;
1369             ps_inp_raw_buf->au4_strd[1] = uStride;
1370             break;
1371         }
1372     }
1373     return C2_OK;
1374 }
1375 
finishWork(uint64_t workIndex,const std::unique_ptr<C2Work> & work,ive_video_encode_op_t * ps_encode_op)1376 void C2SoftAvcEnc::finishWork(uint64_t workIndex, const std::unique_ptr<C2Work> &work,
1377                               ive_video_encode_op_t *ps_encode_op) {
1378     std::shared_ptr<C2Buffer> buffer =
1379             createLinearBuffer(mOutBlock, 0, ps_encode_op->s_out_buf.u4_bytes);
1380     if (IV_IDR_FRAME == ps_encode_op->u4_encoded_frame_type) {
1381         ALOGV("IDR frame produced");
1382         buffer->setInfo(std::make_shared<C2StreamPictureTypeMaskInfo::output>(
1383                 0u /* stream id */, C2Config::SYNC_FRAME));
1384     }
1385     mOutBlock = nullptr;
1386 
1387     auto fillWork = [buffer](const std::unique_ptr<C2Work> &work) {
1388         work->worklets.front()->output.flags = (C2FrameData::flags_t)0;
1389         work->worklets.front()->output.buffers.clear();
1390         work->worklets.front()->output.buffers.push_back(buffer);
1391         work->worklets.front()->output.ordinal = work->input.ordinal;
1392         work->workletsProcessed = 1u;
1393     };
1394     if (work && c2_cntr64_t(workIndex) == work->input.ordinal.frameIndex) {
1395         fillWork(work);
1396         if (mSawInputEOS) {
1397             work->worklets.front()->output.flags = C2FrameData::FLAG_END_OF_STREAM;
1398         }
1399     } else {
1400         finish(workIndex, fillWork);
1401     }
1402 }
1403 
process(const std::unique_ptr<C2Work> & work,const std::shared_ptr<C2BlockPool> & pool)1404 void C2SoftAvcEnc::process(
1405         const std::unique_ptr<C2Work> &work,
1406         const std::shared_ptr<C2BlockPool> &pool) {
1407     // Initialize output work
1408     work->result = C2_OK;
1409     work->workletsProcessed = 0u;
1410     work->worklets.front()->output.flags = work->input.flags;
1411 
1412     IV_STATUS_T status;
1413     WORD32 timeDelay = 0;
1414     WORD32 timeTaken = 0;
1415     uint64_t workIndex = work->input.ordinal.frameIndex.peekull();
1416 
1417     // Initialize encoder if not already initialized
1418     if (mCodecCtx == nullptr) {
1419         if (C2_OK != initEncoder()) {
1420             ALOGE("Failed to initialize encoder");
1421             mSignalledError = true;
1422             work->result = C2_CORRUPTED;
1423             work->workletsProcessed = 1u;
1424             return;
1425         }
1426     }
1427     if (mSignalledError) {
1428         return;
1429     }
1430     // while (!mSawOutputEOS && !outQueue.empty()) {
1431     c2_status_t error;
1432     ive_video_encode_ip_t s_encode_ip;
1433     ive_video_encode_op_t s_encode_op;
1434     memset(&s_encode_op, 0, sizeof(s_encode_op));
1435 
1436     if (!mSpsPpsHeaderReceived) {
1437         constexpr uint32_t kHeaderLength = MIN_STREAM_SIZE;
1438         uint8_t header[kHeaderLength];
1439         error = setEncodeArgs(
1440                 &s_encode_ip, &s_encode_op, nullptr, header, kHeaderLength, workIndex);
1441         if (error != C2_OK) {
1442             ALOGE("setEncodeArgs failed: %d", error);
1443             mSignalledError = true;
1444             work->result = C2_CORRUPTED;
1445             work->workletsProcessed = 1u;
1446             return;
1447         }
1448         status = ive_api_function(mCodecCtx, &s_encode_ip, &s_encode_op);
1449 
1450         if (IV_SUCCESS != status) {
1451             ALOGE("Encode header failed = 0x%x\n",
1452                     s_encode_op.u4_error_code);
1453             work->workletsProcessed = 1u;
1454             return;
1455         } else {
1456             ALOGV("Bytes Generated in header %d\n",
1457                     s_encode_op.s_out_buf.u4_bytes);
1458         }
1459 
1460         mSpsPpsHeaderReceived = true;
1461 
1462         std::unique_ptr<C2StreamInitDataInfo::output> csd =
1463             C2StreamInitDataInfo::output::AllocUnique(s_encode_op.s_out_buf.u4_bytes, 0u);
1464         if (!csd) {
1465             ALOGE("CSD allocation failed");
1466             mSignalledError = true;
1467             work->result = C2_NO_MEMORY;
1468             work->workletsProcessed = 1u;
1469             return;
1470         }
1471         memcpy(csd->m.value, header, s_encode_op.s_out_buf.u4_bytes);
1472         work->worklets.front()->output.configUpdate.push_back(std::move(csd));
1473 
1474         DUMP_TO_FILE(
1475                 mOutFile, csd->m.value, csd->flexCount());
1476         if (work->input.buffers.empty()) {
1477             work->workletsProcessed = 1u;
1478             return;
1479         }
1480     }
1481 
1482     // handle dynamic config parameters
1483     {
1484         IntfImpl::Lock lock = mIntf->lock();
1485         std::shared_ptr<C2StreamIntraRefreshTuning::output> intraRefresh = mIntf->getIntraRefresh_l();
1486         std::shared_ptr<C2StreamBitrateInfo::output> bitrate = mIntf->getBitrate_l();
1487         std::shared_ptr<C2StreamRequestSyncFrameTuning::output> requestSync = mIntf->getRequestSync_l();
1488         lock.unlock();
1489 
1490         if (bitrate != mBitrate) {
1491             mBitrate = bitrate;
1492             setBitRate();
1493         }
1494 
1495         if (intraRefresh != mIntraRefresh) {
1496             mIntraRefresh = intraRefresh;
1497             setAirParams();
1498         }
1499 
1500         if (requestSync != mRequestSync) {
1501             // we can handle IDR immediately
1502             if (requestSync->value) {
1503                 // unset request
1504                 C2StreamRequestSyncFrameTuning::output clearSync(0u, C2_FALSE);
1505                 std::vector<std::unique_ptr<C2SettingResult>> failures;
1506                 mIntf->config({ &clearSync }, C2_MAY_BLOCK, &failures);
1507                 ALOGV("Got sync request");
1508                 setFrameType(IV_IDR_FRAME);
1509             }
1510             mRequestSync = requestSync;
1511         }
1512     }
1513 
1514     if (work->input.flags & C2FrameData::FLAG_END_OF_STREAM) {
1515         mSawInputEOS = true;
1516     }
1517 
1518     /* In normal mode, store inputBufferInfo and this will be returned
1519        when encoder consumes this input */
1520     // if (!mInputDataIsMeta && (inputBufferInfo != NULL)) {
1521     //     for (size_t i = 0; i < MAX_INPUT_BUFFER_HEADERS; i++) {
1522     //         if (NULL == mInputBufferInfo[i]) {
1523     //             mInputBufferInfo[i] = inputBufferInfo;
1524     //             break;
1525     //         }
1526     //     }
1527     // }
1528     std::shared_ptr<const C2GraphicView> view;
1529     std::shared_ptr<C2Buffer> inputBuffer;
1530     if (!work->input.buffers.empty()) {
1531         inputBuffer = work->input.buffers[0];
1532         view = std::make_shared<const C2GraphicView>(
1533                 inputBuffer->data().graphicBlocks().front().map().get());
1534         if (view->error() != C2_OK) {
1535             ALOGE("graphic view map err = %d", view->error());
1536             work->workletsProcessed = 1u;
1537             return;
1538         }
1539     }
1540 
1541     do {
1542         if (mSawInputEOS && work->input.buffers.empty()) break;
1543         if (!mOutBlock) {
1544             C2MemoryUsage usage = {C2MemoryUsage::CPU_READ,
1545                                    C2MemoryUsage::CPU_WRITE};
1546             // TODO: error handling, proper usage, etc.
1547             c2_status_t err =
1548                 pool->fetchLinearBlock(mOutBufferSize, usage, &mOutBlock);
1549             if (err != C2_OK) {
1550                 ALOGE("fetch linear block err = %d", err);
1551                 work->result = err;
1552                 work->workletsProcessed = 1u;
1553                 return;
1554             }
1555         }
1556         C2WriteView wView = mOutBlock->map().get();
1557         if (wView.error() != C2_OK) {
1558             ALOGE("write view map err = %d", wView.error());
1559             work->result = wView.error();
1560             work->workletsProcessed = 1u;
1561             return;
1562         }
1563 
1564         error = setEncodeArgs(
1565                 &s_encode_ip, &s_encode_op, view.get(), wView.base(), wView.capacity(), workIndex);
1566         if (error != C2_OK) {
1567             ALOGE("setEncodeArgs failed : %d", error);
1568             mSignalledError = true;
1569             work->result = error;
1570             work->workletsProcessed = 1u;
1571             return;
1572         }
1573 
1574         // DUMP_TO_FILE(
1575         //         mInFile, s_encode_ip.s_inp_buf.apv_bufs[0],
1576         //         (mHeight * mStride * 3 / 2));
1577 
1578         GETTIME(&mTimeStart, nullptr);
1579         /* Compute time elapsed between end of previous decode()
1580          * to start of current decode() */
1581         TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
1582         status = ive_api_function(mCodecCtx, &s_encode_ip, &s_encode_op);
1583 
1584         if (IV_SUCCESS != status) {
1585             if ((s_encode_op.u4_error_code & 0xFF) == IH264E_BITSTREAM_BUFFER_OVERFLOW) {
1586                 // TODO: use IVE_CMD_CTL_GETBUFINFO for proper max input size?
1587                 mOutBufferSize *= 2;
1588                 mOutBlock.reset();
1589                 continue;
1590             }
1591             ALOGE("Encode Frame failed = 0x%x\n",
1592                     s_encode_op.u4_error_code);
1593             mSignalledError = true;
1594             work->result = C2_CORRUPTED;
1595             work->workletsProcessed = 1u;
1596             return;
1597         }
1598     } while (IV_SUCCESS != status);
1599 
1600     // Hold input buffer reference
1601     if (inputBuffer) {
1602         mBuffers[s_encode_ip.s_inp_buf.apv_bufs[0]] = inputBuffer;
1603     }
1604 
1605     GETTIME(&mTimeEnd, nullptr);
1606     /* Compute time taken for decode() */
1607     TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
1608 
1609     ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
1610             s_encode_op.s_out_buf.u4_bytes);
1611 
1612     void *freed = s_encode_op.s_inp_buf.apv_bufs[0];
1613     /* If encoder frees up an input buffer, mark it as free */
1614     if (freed != nullptr) {
1615         if (mBuffers.count(freed) == 0u) {
1616             ALOGD("buffer not tracked");
1617         } else {
1618             // Release input buffer reference
1619             mBuffers.erase(freed);
1620             mConversionBuffersInUse.erase(freed);
1621         }
1622     }
1623 
1624     if (s_encode_op.output_present) {
1625         if (!s_encode_op.s_out_buf.u4_bytes) {
1626             ALOGE("Error: Output present but bytes generated is zero");
1627             mSignalledError = true;
1628             work->result = C2_CORRUPTED;
1629             work->workletsProcessed = 1u;
1630             return;
1631         }
1632         uint64_t workId = ((uint64_t)s_encode_op.u4_timestamp_high << 32) |
1633                       s_encode_op.u4_timestamp_low;
1634         finishWork(workId, work, &s_encode_op);
1635     }
1636     if (mSawInputEOS) {
1637         drainInternal(DRAIN_COMPONENT_WITH_EOS, pool, work);
1638     }
1639 }
1640 
drainInternal(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool,const std::unique_ptr<C2Work> & work)1641 c2_status_t C2SoftAvcEnc::drainInternal(
1642         uint32_t drainMode,
1643         const std::shared_ptr<C2BlockPool> &pool,
1644         const std::unique_ptr<C2Work> &work) {
1645 
1646     if (drainMode == NO_DRAIN) {
1647         ALOGW("drain with NO_DRAIN: no-op");
1648         return C2_OK;
1649     }
1650     if (drainMode == DRAIN_CHAIN) {
1651         ALOGW("DRAIN_CHAIN not supported");
1652         return C2_OMITTED;
1653     }
1654 
1655     while (true) {
1656         if (!mOutBlock) {
1657             C2MemoryUsage usage = {C2MemoryUsage::CPU_READ,
1658                                    C2MemoryUsage::CPU_WRITE};
1659             // TODO: error handling, proper usage, etc.
1660             c2_status_t err =
1661                 pool->fetchLinearBlock(mOutBufferSize, usage, &mOutBlock);
1662             if (err != C2_OK) {
1663                 ALOGE("fetch linear block err = %d", err);
1664                 work->result = err;
1665                 work->workletsProcessed = 1u;
1666                 return err;
1667             }
1668         }
1669         C2WriteView wView = mOutBlock->map().get();
1670         if (wView.error()) {
1671             ALOGE("graphic view map failed %d", wView.error());
1672             return C2_CORRUPTED;
1673         }
1674         ive_video_encode_ip_t s_encode_ip;
1675         ive_video_encode_op_t s_encode_op;
1676         if (C2_OK != setEncodeArgs(&s_encode_ip, &s_encode_op, nullptr,
1677                                    wView.base(), wView.capacity(), 0)) {
1678             ALOGE("setEncodeArgs failed for drainInternal");
1679             mSignalledError = true;
1680             work->result = C2_CORRUPTED;
1681             work->workletsProcessed = 1u;
1682             return C2_CORRUPTED;
1683         }
1684         (void)ive_api_function(mCodecCtx, &s_encode_ip, &s_encode_op);
1685 
1686         void *freed = s_encode_op.s_inp_buf.apv_bufs[0];
1687         /* If encoder frees up an input buffer, mark it as free */
1688         if (freed != nullptr) {
1689             if (mBuffers.count(freed) == 0u) {
1690                 ALOGD("buffer not tracked");
1691             } else {
1692                 // Release input buffer reference
1693                 mBuffers.erase(freed);
1694                 mConversionBuffersInUse.erase(freed);
1695             }
1696         }
1697 
1698         if (s_encode_op.output_present) {
1699             uint64_t workId = ((uint64_t)s_encode_op.u4_timestamp_high << 32) |
1700                           s_encode_op.u4_timestamp_low;
1701             finishWork(workId, work, &s_encode_op);
1702         } else {
1703             if (work->workletsProcessed != 1u) {
1704                 work->worklets.front()->output.flags = work->input.flags;
1705                 work->worklets.front()->output.ordinal = work->input.ordinal;
1706                 work->worklets.front()->output.buffers.clear();
1707                 work->workletsProcessed = 1u;
1708             }
1709             break;
1710         }
1711     }
1712 
1713     return C2_OK;
1714 }
1715 
drain(uint32_t drainMode,const std::shared_ptr<C2BlockPool> & pool)1716 c2_status_t C2SoftAvcEnc::drain(
1717         uint32_t drainMode,
1718         const std::shared_ptr<C2BlockPool> &pool) {
1719     return drainInternal(drainMode, pool, nullptr);
1720 }
1721 
1722 class C2SoftAvcEncFactory : public C2ComponentFactory {
1723 public:
C2SoftAvcEncFactory()1724     C2SoftAvcEncFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
1725         GetCodec2PlatformComponentStore()->getParamReflector())) {
1726     }
1727 
createComponent(c2_node_id_t id,std::shared_ptr<C2Component> * const component,std::function<void (C2Component *)> deleter)1728     virtual c2_status_t createComponent(
1729             c2_node_id_t id,
1730             std::shared_ptr<C2Component>* const component,
1731             std::function<void(C2Component*)> deleter) override {
1732         *component = std::shared_ptr<C2Component>(
1733                 new C2SoftAvcEnc(COMPONENT_NAME,
1734                                  id,
1735                                  std::make_shared<C2SoftAvcEnc::IntfImpl>(mHelper)),
1736                 deleter);
1737         return C2_OK;
1738     }
1739 
createInterface(c2_node_id_t id,std::shared_ptr<C2ComponentInterface> * const interface,std::function<void (C2ComponentInterface *)> deleter)1740     virtual c2_status_t createInterface(
1741             c2_node_id_t id,
1742             std::shared_ptr<C2ComponentInterface>* const interface,
1743             std::function<void(C2ComponentInterface*)> deleter) override {
1744         *interface = std::shared_ptr<C2ComponentInterface>(
1745                 new SimpleInterface<C2SoftAvcEnc::IntfImpl>(
1746                         COMPONENT_NAME, id, std::make_shared<C2SoftAvcEnc::IntfImpl>(mHelper)),
1747                 deleter);
1748         return C2_OK;
1749     }
1750 
1751     virtual ~C2SoftAvcEncFactory() override = default;
1752 
1753 private:
1754     std::shared_ptr<C2ReflectorHelper> mHelper;
1755 };
1756 
1757 }  // namespace android
1758 
CreateCodec2Factory()1759 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
1760     ALOGV("in %s", __func__);
1761     return new ::android::C2SoftAvcEncFactory();
1762 }
1763 
DestroyCodec2Factory(::C2ComponentFactory * factory)1764 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
1765     ALOGV("in %s", __func__);
1766     delete factory;
1767 }
1768